


'''simple docstring'''



# Copyright (c) 2021-, NVIDIA CORPORATION.  All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

####################################################################################################

#
# Note: If when running this conversion script you're getting an exception:
#     ModuleNotFoundError: No module named 'megatron.model.enums'
# you need to tell python where to find the clone of Megatron-LM, e.g.:
#
# cd /tmp
# git clone https://github.com/NVIDIA/Megatron-LM
# PYTHONPATH=/tmp/Megatron-LM python src/transformers/models/megatron_bert/convert_megatron_bert_checkpoint.py ...
#
# if you already have it cloned elsewhere, simply adjust the path to the existing path
#
# If the training was done using a Megatron-LM fork, e.g.,
# https://github.com/microsoft/Megatron-DeepSpeed/ then chances are that you need to have that one
# in your path, i.e., /path/to/Megatron-DeepSpeed/
#

import argparse
import os
import re
import zipfile

import torch

from transformers import MegatronBertConfig




def       _a      (		_lowercase   :      List[Any]     ,   _lowercase   :      Optional[int]     ,   _lowercase   :      str=0    ):





     '''simple docstring'''






     if name is None:
          __UpperCAmelCase      :					Union[str, Any]    				=     None
     else:
          __UpperCAmelCase      :					Union[str, Any]    				=     '''.''' * max(0     ,   spaces - 2    ) + '''# {:''' + str(50 - spaces    ) + '''s}'''
          __UpperCAmelCase      :					Union[str, Any]    				=     fmt.format(_lowercase    )

     # Print and recurse (if needed).
     if isinstance(_lowercase     ,   _lowercase    ):
          if msg is not None:
               print(_lowercase    )
          for k in val.keys():
               recursive_print(_lowercase     ,   val[k]     ,   spaces + 2    )
     elif isinstance(_lowercase     ,   torch.Tensor    ):
          print(_lowercase     ,   ''':'''     ,   val.size()    )
     else:
          print(_lowercase     ,   ''':'''     ,   _lowercase    )




def       _a      (		_lowercase   :      List[Any]     ,   _lowercase   :      Union[str, Any]     ,   _lowercase   :      int     ,   _lowercase   :      Optional[Any]     ,   _lowercase   :      Dict    ):





     '''simple docstring'''






     __UpperCAmelCase      :					List[str]    				=     param.size()
     if checkpoint_version == 1.0:
          # version 1.0 stores [num_heads * hidden_size * num_splits, :]
          __UpperCAmelCase      :					Dict    				=     (num_heads, hidden_size, num_splits) + input_shape[1:]
          __UpperCAmelCase      :					Any    				=     param.view(*_lowercase    )
          __UpperCAmelCase      :					str    				=     param.transpose(0     ,   2    )
          __UpperCAmelCase      :					List[Any]    				=     param.transpose(1     ,   2    ).contiguous()
     elif checkpoint_version >= 2.0:
          # other versions store [num_heads * num_splits * hidden_size, :]
          __UpperCAmelCase      :					Dict    				=     (num_heads, num_splits, hidden_size) + input_shape[1:]
          __UpperCAmelCase      :					Tuple    				=     param.view(*_lowercase    )
          __UpperCAmelCase      :					Union[str, Any]    				=     param.transpose(0     ,   1    ).contiguous()
     __UpperCAmelCase      :					Optional[int]    				=     param.view(*_lowercase    )
     return param




def       _a      (		_lowercase   :      Tuple     ,   _lowercase   :      Tuple     ,   _lowercase   :      Any    ):





     '''simple docstring'''






     __UpperCAmelCase      :					List[Any]    				=     {}

     # old versions did not store training args
     __UpperCAmelCase      :					Tuple    				=     input_state_dict.get('''args'''     ,   _lowercase    )
     if ds_args is not None:
          # do not make the user write a config file when the exact dimensions/sizes are already in the checkpoint
          # from pprint import pprint
          # pprint(vars(ds_args))

          __UpperCAmelCase      :					List[Any]    				=     ds_args.tokenizer_type
          __UpperCAmelCase      :					Tuple    				=     ds_args.padded_vocab_size
          __UpperCAmelCase      :					Optional[int]    				=     ds_args.max_position_embeddings
          __UpperCAmelCase      :					int    				=     ds_args.hidden_size
          __UpperCAmelCase      :					Optional[int]    				=     ds_args.num_layers
          __UpperCAmelCase      :					List[str]    				=     ds_args.num_attention_heads
          __UpperCAmelCase      :					int    				=     ds_args.ffn_hidden_size if '''ffn_hidden_size''' in ds_args else 4 * ds_args.hidden_size
          # pprint(config)

     # The number of heads.
     __UpperCAmelCase      :					Tuple    				=     config.num_attention_heads
     # The hidden_size per head.
     __UpperCAmelCase      :					List[str]    				=     config.hidden_size // heads
     # Megatron-LM checkpoint version
     if "checkpoint_version" in input_state_dict.keys():
          __UpperCAmelCase      :					Dict    				=     input_state_dict['''checkpoint_version''']
     else:
          __UpperCAmelCase      :					Dict    				=     0.0

     # The model.
     __UpperCAmelCase      :					Union[str, Any]    				=     input_state_dict['''model''']
     # The language model.
     __UpperCAmelCase      :					Any    				=     model['''language_model''']
     # The embeddings.
     __UpperCAmelCase      :					Union[str, Any]    				=     lm['''embedding''']

     # The word embeddings.
     __UpperCAmelCase      :					List[str]    				=     embeddings['''word_embeddings''']['''weight''']
     # Truncate the embedding table to vocab_size rows.
     __UpperCAmelCase      :					Optional[int]    				=     word_embeddings[: config.vocab_size, :]
     # Store the word embeddings.
     __UpperCAmelCase      :					List[str]    				=     word_embeddings

     # The position embeddings.
     __UpperCAmelCase      :					List[Any]    				=     embeddings['''position_embeddings''']['''weight''']
     assert pos_embeddings.size(0    ) == config.max_position_embeddings and pos_embeddings.size(1    ) == config.hidden_size
     # Store the position embeddings.
     __UpperCAmelCase      :					Tuple    				=     pos_embeddings

     # The token-type embeddings.
     __UpperCAmelCase      :					str    				=     embeddings['''tokentype_embeddings''']['''weight''']
     # Store the position embeddings.
     __UpperCAmelCase      :					Tuple    				=     tokentype_embeddings

     # The transformer.
     __UpperCAmelCase      :					List[Any]    				=     lm['''transformer'''] if '''transformer''' in lm.keys() else lm['''encoder''']

     # The regex to extract layer names.
     __UpperCAmelCase      :					List[str]    				=     re.compile(R'''layers\.(\d+)\.([a-z0-9_.]+)\.([a-z]+)'''    )

     # The simple map of names for "automated" rules.
     __UpperCAmelCase      :					Dict    				=     {
         '''attention.dense''': '''.attention.output.dense.''',
         '''self_attention.dense''': '''.attention.output.dense.''',
         '''mlp.dense_h_to_4h''': '''.intermediate.dense.''',
         '''mlp.dense_4h_to_h''': '''.output.dense.''',
     }

     # Keep track of the attention/query/value tensor.
     __UpperCAmelCase      :					Union[str, Any]    				=     None

     # Extract the layers.
     for key, val in transformer.items():
          # Match the name.
          __UpperCAmelCase      :					Union[str, Any]    				=     layer_re.match(_lowercase    )

          # Stop if that's not a layer
          if m is None:
               break

          # The index of the layer.
          __UpperCAmelCase      :					str    				=     int(m.group(1    )    )
          # The name of the operation.
          __UpperCAmelCase      :					List[str]    				=     m.group(2    )
          # Is it a weight or a bias?
          __UpperCAmelCase      :					Any    				=     m.group(3    )

          # The name of the layer.
          __UpperCAmelCase      :					List[str]    				=     F'bert.encoder.layer.{layer_idx}'

          # For layernorm(s), simply store the layer norm.
          if op_name.endswith('''layernorm'''    ):
               __UpperCAmelCase      :					str    				=     '''attention.ln''' if op_name.startswith('''input'''    ) else '''ln'''
               __UpperCAmelCase      :					int    				=     val

          # Transpose the QKV matrix.
          elif (
              op_name == "attention.query_key_value" or op_name == "self_attention.query_key_value"
          ) and weight_or_bias == "weight":
               # Make sure the QKV pointer is nil.
               assert attention_qkv_weight is None, ""

               __UpperCAmelCase      :					List[Any]    				=     fix_query_key_value_ordering(_lowercase     ,   _lowercase     ,   3     ,   _lowercase     ,   _lowercase    )
               # Store the tensor as we need the bias as well to interleave QKV and biases.
               __UpperCAmelCase      :					Union[str, Any]    				=     out_val

          # Transpose the bias.
          elif (
              op_name == "attention.query_key_value" or op_name == "self_attention.query_key_value"
          ) and weight_or_bias == "bias":
               # Make sure we read the weight tensor.
               assert attention_qkv_weight is not None, ""

               # Split the QKV matrix into Q, K and V. Megatron stores Q,K,V interleaved.
               __UpperCAmelCase      :					Any    				=     attention_qkv_weight[0 * config.hidden_size : 1 * config.hidden_size, :]
               __UpperCAmelCase      :					Tuple    				=     attention_qkv_weight[1 * config.hidden_size : 2 * config.hidden_size, :]
               __UpperCAmelCase      :					Any    				=     attention_qkv_weight[2 * config.hidden_size : 3 * config.hidden_size, :]

               __UpperCAmelCase      :					Any    				=     fix_query_key_value_ordering(_lowercase     ,   _lowercase     ,   3     ,   _lowercase     ,   _lowercase    )
               # Split the bias.
               __UpperCAmelCase      :					Optional[int]    				=     out_val[0 * config.hidden_size : 1 * config.hidden_size]
               __UpperCAmelCase      :					List[str]    				=     out_val[1 * config.hidden_size : 2 * config.hidden_size]
               __UpperCAmelCase      :					Union[str, Any]    				=     out_val[2 * config.hidden_size : 3 * config.hidden_size]

               # Store.
               __UpperCAmelCase      :					List[Any]    				=     q
               __UpperCAmelCase      :					Optional[Any]    				=     q_bias
               __UpperCAmelCase      :					int    				=     k
               __UpperCAmelCase      :					str    				=     k_bias
               __UpperCAmelCase      :					List[Any]    				=     v
               __UpperCAmelCase      :					List[Any]    				=     v_bias

               # Clear the stored tensor.
               __UpperCAmelCase      :					Dict    				=     None

          # Copy weights and biases as is.
          elif weight_or_bias in ["weight", "bias"]:
               __UpperCAmelCase      :					List[str]    				=     megatron_to_transformers[op_name]
               __UpperCAmelCase      :					Any    				=     val

    # The final layernorm.
     __UpperCAmelCase      :					str    				=     transformer['''final_layernorm.weight''']
     __UpperCAmelCase      :					str    				=     transformer['''final_layernorm.bias''']

     # The pooler.
     __UpperCAmelCase      :					str    				=     lm['''pooler''']

     # Store the matrix and the bias.
     __UpperCAmelCase      :					str    				=     pooler['''dense.weight''']
     __UpperCAmelCase      :					List[str]    				=     pooler['''dense.bias''']

     # The LM head from Megatron (for RACE).
     __UpperCAmelCase      :					Optional[int]    				=     model['''lm_head''']

     # The transform matrix.
     __UpperCAmelCase      :					str    				=     lm_head['''dense.weight''']
     __UpperCAmelCase      :					List[str]    				=     lm_head['''dense.bias''']

     # The transform LN.
     __UpperCAmelCase      :					Any    				=     lm_head['''layernorm.weight''']
     __UpperCAmelCase      :					Union[str, Any]    				=     lm_head['''layernorm.bias''']

     # For the decoder, we replicate the weights.
     __UpperCAmelCase      :					Union[str, Any]    				=     word_embeddings
     __UpperCAmelCase      :					str    				=     lm_head['''bias''']

     # The classifier from Megatron (for MLNI).
     __UpperCAmelCase      :					Optional[Any]    				=     model['''binary_head''']

     # Store the classifier.
     __UpperCAmelCase      :					Dict    				=     binary_head['''weight''']
     __UpperCAmelCase      :					str    				=     binary_head['''bias''']

     # It should be done!
     return output_state_dict




def       _a      (		):





     '''simple docstring'''






     __UpperCAmelCase      :					Optional[Any]    				=     argparse.ArgumentParser()
     parser.add_argument('''--print-checkpoint-structure'''     ,   action='''store_true'''    )
     parser.add_argument('''path_to_checkpoint'''     ,   type=_lowercase     ,   help='''Path to the ZIP file containing the checkpoint'''    )
     parser.add_argument(
         '''--config_file'''     ,   default=''''''     ,   type=_lowercase     ,   help='''An optional config json file describing the pre-trained model.'''     ,   )
     __UpperCAmelCase      :					Any    				=     parser.parse_args()

     # Extract the basename.
     __UpperCAmelCase      :					int    				=     os.path.dirname(args.path_to_checkpoint    )

     # Load the model.
     # the .zip is very optional, let's keep it for backward compatibility
     print(F'Extracting PyTorch state dictionary from "{args.path_to_checkpoint}"'    )
     if args.path_to_checkpoint.endswith('''.zip'''    ):
          with zipfile.ZipFile(args.path_to_checkpoint     ,   '''r'''    ) as checkpoint:
               with checkpoint.open('''release/mp_rank_00/model_optim_rng.pt'''    ) as pytorch_dict:
                    __UpperCAmelCase      :					str    				=     torch.load(_lowercase     ,   map_location='''cpu'''    )
     else:
          __UpperCAmelCase      :					Tuple    				=     torch.load(args.path_to_checkpoint     ,   map_location='''cpu'''    )

     if args.config_file == "":
          # Default config of megatron-bert 345m
          __UpperCAmelCase      :					Union[str, Any]    				=     MegatronBertConfig()

          # different megatron-bert-*-345m models have different vocab sizes, so override the default
          # config (which is for megatron-bert-cased-345m) with the actual vocab dimension
          __UpperCAmelCase      :					Optional[Any]    				=     input_state_dict['''model''']['''lm_head''']['''bias'''].numel()
     else:
          __UpperCAmelCase      :					str    				=     MegatronBertConfig.from_json_file(args.config_file    )

     # Convert.
     print('''Converting'''    )
     __UpperCAmelCase      :					Dict    				=     convert_megatron_checkpoint(_lowercase     ,   _lowercase     ,   _lowercase    )

     # Print the structure of converted state dict.
     if args.print_checkpoint_structure:
          recursive_print(_lowercase     ,   _lowercase    )

     # Store the config to file.
     print('''Saving config'''    )
     config.save_pretrained(_lowercase    )

     # Store the state_dict to file.
     __UpperCAmelCase      :					Optional[int]    				=     os.path.join(_lowercase     ,   '''pytorch_model.bin'''    )
     print(F'Saving checkpoint to "{output_checkpoint_file}"'    )
     torch.save(_lowercase     ,   _lowercase    )


####################################################################################################

if __name__ == "__main__":
      main()

####################################################################################################



'''simple docstring'''



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	:						int				,					snake_case	:						str				,					snake_case	:						str=13				,					snake_case	:						List[str]=32				,					snake_case	:						Tuple=3				,					snake_case	:						Dict=[3, 3, 5]				,					snake_case	:						Tuple=[32, 16, 24]				,					snake_case	:						Any=[16, 24, 40]				,					snake_case	:						Dict=[1, 1, 2]				,					snake_case	:						Optional[int]=[1, 1, 2]				,					snake_case	:						Optional[int]=[1, 6, 6]				,					snake_case	:						List[str]=True				,					snake_case	:						int=True				,					snake_case	:						Tuple=37				,					snake_case	:						List[str]="gelu"				,					snake_case	:						Optional[int]=10				,					)		->				Optional[int]:
          __UpperCAmelCase      :					Union[str, Any]    				=     parent
          __UpperCAmelCase      :					Optional[int]    				=     batch_size
          __UpperCAmelCase      :					Union[str, Any]    				=     image_size
          __UpperCAmelCase      :					List[Any]    				=     num_channels
          __UpperCAmelCase      :					str    				=     kernel_sizes
          __UpperCAmelCase      :					Union[str, Any]    				=     in_channels
          __UpperCAmelCase      :					str    				=     out_channels
          __UpperCAmelCase      :					List[str]    				=     strides
          __UpperCAmelCase      :					List[str]    				=     num_block_repeats
          __UpperCAmelCase      :					List[str]    				=     expand_ratios
          __UpperCAmelCase      :					Union[str, Any]    				=     is_training
          __UpperCAmelCase      :					Optional[int]    				=     hidden_act
          __UpperCAmelCase      :					List[Any]    				=     num_labels
          __UpperCAmelCase      :					Dict    				=     use_labels

     def 					lowerCamelCase__					(							self	:						Dict     )		->				Tuple:
          __UpperCAmelCase      :					Tuple    				=     floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]     )

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

          __UpperCAmelCase      :					int    				=     self.get_config()
          return config, pixel_values, labels

     def 					lowerCamelCase__					(							self	:						str     )		->				Dict:
          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 					lowerCamelCase__					(							self	:						Any				,					snake_case	:						Tuple				,					snake_case	:						Tuple				,					snake_case	:						Optional[int]     )		->				Union[str, Any]:
          __UpperCAmelCase      :					Union[str, Any]    				=     EfficientNetModel(config=snake_case     )
          model.to(snake_case     )
          model.eval()
          __UpperCAmelCase      :					Union[str, Any]    				=     model(snake_case     )
          # 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 					lowerCamelCase__					(							self	:						List[str]				,					snake_case	:						Optional[int]				,					snake_case	:						List[str]				,					snake_case	:						List[str]     )		->				Optional[int]:
          __UpperCAmelCase      :					List[str]    				=     EfficientNetForImageClassification(snake_case     )
          model.to(snake_case     )
          model.eval()
          __UpperCAmelCase      :					Any    				=     model(snake_case				,					labels=snake_case     )
          self.parent.assertEqual(result.logits.shape				,					(self.batch_size, self.num_labels)     )






     def 					lowerCamelCase__					(							self	:						str     )		->				Tuple:
          __UpperCAmelCase      :					List[Any]    				=     self.prepare_config_and_inputs()
          __UpperCAmelCase				,  __UpperCAmelCase				,  __UpperCAmelCase      :					Union[str, Any]    				=     config_and_inputs
          __UpperCAmelCase      :					Union[str, Any]    				=     {'''pixel_values''': pixel_values}
          return config, inputs_dict



@require_torch
class       a							(						_a      ,    _a      ,    unittest.TestCase			):


     """simple docstring"""






     SCREAMING_SNAKE_CASE			:					str				  =  (EfficientNetModel, EfficientNetForImageClassification) if is_torch_available() else ()
     SCREAMING_SNAKE_CASE			:					List[str]				  =  (
         {"feature-extraction": EfficientNetModel, "image-classification": EfficientNetForImageClassification}
         if is_torch_available()
         else {}
     )

     SCREAMING_SNAKE_CASE			:					Union[str, Any]				  =  False
     SCREAMING_SNAKE_CASE			:					Optional[int]				  =  False
     SCREAMING_SNAKE_CASE			:					Optional[int]				  =  False
     SCREAMING_SNAKE_CASE			:					List[Any]				  =  False
     SCREAMING_SNAKE_CASE			:					List[str]				  =  False

     def 					lowerCamelCase__					(							self	:						List[str]     )		->				List[str]:
          __UpperCAmelCase      :					Dict    				=     EfficientNetModelTester(self     )
          __UpperCAmelCase      :					Optional[Any]    				=     ConfigTester(
              self				,					config_class=snake_case				,					has_text_modality=snake_case				,					hidden_size=37     )

     def 					lowerCamelCase__					(							self	:						List[str]     )		->				str:
          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     )		->				str:
          return

     @unittest.skip(reason='''EfficientNet does not use inputs_embeds'''     )
     def 					lowerCamelCase__					(							self	:						List[Any]     )		->				Optional[int]:
          pass

     @unittest.skip(reason='''EfficientNet does not support input and output embeddings'''     )
     def 					lowerCamelCase__					(							self	:						List[str]     )		->				Dict:
          pass

     @unittest.skip(reason='''EfficientNet does not use feedforward chunking'''     )
     def 					lowerCamelCase__					(							self	:						Union[str, Any]     )		->				Optional[int]:
          pass

     def 					lowerCamelCase__					(							self	:						List[str]     )		->				Optional[Any]:
          __UpperCAmelCase				,  __UpperCAmelCase      :					List[str]    				=     self.model_tester.prepare_config_and_inputs_for_common()

          for model_class in self.all_model_classes:
               __UpperCAmelCase      :					Tuple    				=     model_class(snake_case     )
               __UpperCAmelCase      :					Tuple    				=     inspect.signature(model.forward     )
               # signature.parameters is an OrderedDict => so arg_names order is deterministic
               __UpperCAmelCase      :					Optional[int]    				=     [*signature.parameters.keys()]

               __UpperCAmelCase      :					Union[str, Any]    				=     ['''pixel_values''']
               self.assertListEqual(arg_names[:1]				,					snake_case     )

     def 					lowerCamelCase__					(							self	:						int     )		->				List[str]:
          __UpperCAmelCase      :					Union[str, Any]    				=     self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_model(*snake_case     )

     def 					lowerCamelCase__					(							self	:						int     )		->				str:
          def check_hidden_states_output(snake_case	:						Union[str, Any]				,					snake_case	:						str				,					snake_case	:						Tuple     ):
               __UpperCAmelCase      :					List[str]    				=     model_class(snake_case     )
               model.to(snake_case     )
               model.eval()

               with torch.no_grad():
                    __UpperCAmelCase      :					int    				=     model(**self._prepare_for_class(snake_case				,					snake_case     )     )

               __UpperCAmelCase      :					Optional[int]    				=     outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states
               __UpperCAmelCase      :					List[str]    				=     sum(config.num_block_repeats     ) * 4
               self.assertEqual(len(snake_case     )				,					snake_case     )

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

          __UpperCAmelCase				,  __UpperCAmelCase      :					Union[str, Any]    				=     self.model_tester.prepare_config_and_inputs_for_common()

          for model_class in self.all_model_classes:
               __UpperCAmelCase      :					int    				=     True
               check_hidden_states_output(snake_case				,					snake_case				,					snake_case     )

               # check that output_hidden_states also work using config
               del inputs_dict["output_hidden_states"]
               __UpperCAmelCase      :					Union[str, Any]    				=     True

               check_hidden_states_output(snake_case				,					snake_case				,					snake_case     )

     def 					lowerCamelCase__					(							self	:						str     )		->				Any:
          __UpperCAmelCase      :					Any    				=     self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_image_classification(*snake_case     )

     @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.'''     )
     def 					lowerCamelCase__					(							self	:						List[Any]     )		->				Tuple:
          pass

     @slow
     def 					lowerCamelCase__					(							self	:						Optional[int]     )		->				List[str]:
          for model_name in EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
               __UpperCAmelCase      :					str    				=     EfficientNetModel.from_pretrained(snake_case     )
               self.assertIsNotNone(snake_case     )






     @is_pipeline_test
     @require_vision
     @slow
     def 					lowerCamelCase__					(							self	:						Union[str, Any]     )		->				List[str]:
          super().test_pipeline_image_classification()




def       _a      (		):





     '''simple docstring'''






     __UpperCAmelCase      :					Any    				=     Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''    )
     return image



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


     """simple docstring"""






     @cached_property
     def 					lowerCamelCase__					(							self	:						List[str]     )		->				Dict:
          return AutoImageProcessor.from_pretrained('''google/efficientnet-b7'''     ) if is_vision_available() else None






     @slow
     def 					lowerCamelCase__					(							self	:						str     )		->				Any:
          __UpperCAmelCase      :					Tuple    				=     EfficientNetForImageClassification.from_pretrained('''google/efficientnet-b7'''     ).to(snake_case     )

          __UpperCAmelCase      :					List[str]    				=     self.default_image_processor
          __UpperCAmelCase      :					List[Any]    				=     prepare_img()
          __UpperCAmelCase      :					Union[str, Any]    				=     image_processor(images=snake_case				,					return_tensors='''pt'''     ).to(snake_case     )

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

          # verify the logits
          __UpperCAmelCase      :					Any    				=     torch.Size((1, 1000)     )
          self.assertEqual(outputs.logits.shape				,					snake_case     )

          __UpperCAmelCase      :					Dict    				=     torch.tensor([0.0_001, 0.0_002, 0.0_002]     ).to(snake_case     )
          self.assertTrue(torch.allclose(outputs.logits[0, :3]				,					snake_case				,					atol=1E-4     )     )