

import tempfile
import unittest

import transformers
from transformers import XGLMConfig, XGLMTokenizer, is_flax_available, is_torch_available
from transformers.testing_utils import is_pt_flax_cross_test, require_flax, require_sentencepiece, slow

from ...generation.test_flax_utils import FlaxGenerationTesterMixin
from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask


if is_flax_available():
  import jax
  import jax.numpy as jnp
  import numpy as np

  from transformers.modeling_flax_pytorch_utils import (
      convert_pytorch_state_dict_to_flax,
      load_flax_weights_in_pytorch_model,
  )
  from transformers.models.xglm.modeling_flax_xglm import FlaxXGLMForCausalLM, FlaxXGLMModel


if is_torch_available():
  import torch







@require_flax
class     a__    :







  """simple docstring"""




  def __init__(     self      :	int			,			UpperCAmelCase__      :	Tuple			,			UpperCAmelCase__      :	Optional[Any]=1_4			,			UpperCAmelCase__      :	Optional[int]=7			,			UpperCAmelCase__      :	Optional[Any]=True			,			UpperCAmelCase__      :	Tuple=True			,			UpperCAmelCase__      :	str=True			,			UpperCAmelCase__      :	Optional[int]=9_9			,			UpperCAmelCase__      :	List[str]=3_2			,			UpperCAmelCase__      :	int=5			,			UpperCAmelCase__      :	List[Any]=4			,			UpperCAmelCase__      :	Optional[Any]=3_7			,			UpperCAmelCase__      :	str="gelu"			,			UpperCAmelCase__      :	List[str]=0.1			,			UpperCAmelCase__      :	int=0.1			,			UpperCAmelCase__      :	str=5_1_2			,			UpperCAmelCase__      :	Optional[Any]=0.02			,			UpperCAmelCase__      :	List[Any]=None			,			)   ->Any:
        """simple docstring"""







        SCREAMING_SNAKE_CASE	: Optional[Any]					       =				parent
        SCREAMING_SNAKE_CASE	: str					       =				batch_size
        SCREAMING_SNAKE_CASE	: Any					       =				seq_length
        SCREAMING_SNAKE_CASE	: Any					       =				is_training
        SCREAMING_SNAKE_CASE	: Tuple					       =				use_input_mask
        SCREAMING_SNAKE_CASE	: List[Any]					       =				use_labels
        SCREAMING_SNAKE_CASE	: List[Any]					       =				vocab_size
        SCREAMING_SNAKE_CASE	: Union[str, Any]					       =				d_model
        SCREAMING_SNAKE_CASE	: List[str]					       =				num_hidden_layers
        SCREAMING_SNAKE_CASE	: List[Any]					       =				num_attention_heads
        SCREAMING_SNAKE_CASE	: List[Any]					       =				ffn_dim
        SCREAMING_SNAKE_CASE	: Optional[int]					       =				activation_function
        SCREAMING_SNAKE_CASE	: int					       =				activation_dropout
        SCREAMING_SNAKE_CASE	: List[str]					       =				attention_dropout
        SCREAMING_SNAKE_CASE	: str					       =				max_position_embeddings
        SCREAMING_SNAKE_CASE	: Optional[int]					       =				initializer_range
        SCREAMING_SNAKE_CASE	: Union[str, Any]					       =				None
        SCREAMING_SNAKE_CASE	: Optional[Any]					       =				0
        SCREAMING_SNAKE_CASE	: Union[str, Any]					       =				2
        SCREAMING_SNAKE_CASE	: int					       =				1


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







        SCREAMING_SNAKE_CASE	: int					       =				np.clip(ids_tensor([self.batch_size, self.seq_length]			,			self.vocab_size						)			,			3			,			self.vocab_size						)

        SCREAMING_SNAKE_CASE	: Optional[int]					       =				None
        if self.use_input_mask:
              SCREAMING_SNAKE_CASE	: Any					       =				random_attention_mask([self.batch_size, self.seq_length]						)

        SCREAMING_SNAKE_CASE	: List[str]					       =				XGLMConfig(
            vocab_size=self.vocab_size			,			d_model=self.hidden_size			,			num_layers=self.num_hidden_layers			,			attention_heads=self.num_attention_heads			,			ffn_dim=self.ffn_dim			,			activation_function=self.activation_function			,			activation_dropout=self.activation_dropout			,			attention_dropout=self.attention_dropout			,			max_position_embeddings=self.max_position_embeddings			,			initializer_range=self.initializer_range			,			use_cache=UpperCAmelCase__			,			bos_token_id=self.bos_token_id			,			eos_token_id=self.eos_token_id			,			pad_token_id=self.pad_token_id			,			)

        return (config, input_ids, input_mask)


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







        SCREAMING_SNAKE_CASE	: Tuple					       =				self.prepare_config_and_inputs()
        SCREAMING_SNAKE_CASE       ,		SCREAMING_SNAKE_CASE       ,		SCREAMING_SNAKE_CASE	: List[Any]					       =				config_and_inputs
        SCREAMING_SNAKE_CASE	: Optional[Any]					       =				{"""input_ids""": input_ids, """attention_mask""": attention_mask}
        return config, inputs_dict


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







        SCREAMING_SNAKE_CASE       ,		SCREAMING_SNAKE_CASE       ,		SCREAMING_SNAKE_CASE	: Dict					       =				self.prepare_config_and_inputs()

        SCREAMING_SNAKE_CASE	: Optional[int]					       =				floats_tensor([self.batch_size, self.seq_length, self.hidden_size]						)
        SCREAMING_SNAKE_CASE	: Dict					       =				ids_tensor([self.batch_size, self.seq_length]			,			vocab_size=2						)

        return (
            config,
            input_ids,
            attention_mask,
            encoder_hidden_states,
            encoder_attention_mask,
        )


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







        SCREAMING_SNAKE_CASE	: Tuple					       =				2_0
        SCREAMING_SNAKE_CASE	: List[Any]					       =				model_class_name(UpperCAmelCase__						)

        SCREAMING_SNAKE_CASE	: List[str]					       =				model.init_cache(input_ids.shape[0]			,			UpperCAmelCase__						)
        SCREAMING_SNAKE_CASE	: Tuple					       =				jnp.ones((input_ids.shape[0], max_decoder_length)			,			dtype="""i4"""						)

        SCREAMING_SNAKE_CASE	: List[str]					       =				jnp.broadcast_to(
            jnp.arange(input_ids.shape[-1] - 1						)[None, :]			,			(input_ids.shape[0], input_ids.shape[-1] - 1)						)
        SCREAMING_SNAKE_CASE	: Union[str, Any]					       =				model(
            input_ids[:, :-1]			,			attention_mask=UpperCAmelCase__			,			past_key_values=UpperCAmelCase__			,			position_ids=UpperCAmelCase__			,			)

        SCREAMING_SNAKE_CASE	: Tuple					       =				jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]]			,			dtype="""i4"""						)
        SCREAMING_SNAKE_CASE	: Dict					       =				model(
            input_ids[:, -1:]			,			attention_mask=UpperCAmelCase__			,			past_key_values=outputs_cache.past_key_values			,			position_ids=UpperCAmelCase__			,			)

        SCREAMING_SNAKE_CASE	: Any					       =				model(UpperCAmelCase__						)

        SCREAMING_SNAKE_CASE	: str					       =				np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5])						)						)
        self.parent.assertTrue(diff < 1e-3			,			msg=f"Max diff is {diff}"						)




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







        SCREAMING_SNAKE_CASE	: Any					       =				2_0
        SCREAMING_SNAKE_CASE	: int					       =				model_class_name(UpperCAmelCase__						)

        SCREAMING_SNAKE_CASE	: int					       =				jnp.concatenate(
            [attention_mask, jnp.zeros((attention_mask.shape[0], max_decoder_length - attention_mask.shape[1])						)]			,			axis=-1			,			)

        SCREAMING_SNAKE_CASE	: List[Any]					       =				model.init_cache(input_ids.shape[0]			,			UpperCAmelCase__						)
        SCREAMING_SNAKE_CASE	: str					       =				jnp.broadcast_to(
            jnp.arange(input_ids.shape[-1] - 1						)[None, :]			,			(input_ids.shape[0], input_ids.shape[-1] - 1)						)

        SCREAMING_SNAKE_CASE	: Any					       =				model(
            input_ids[:, :-1]			,			attention_mask=UpperCAmelCase__			,			past_key_values=UpperCAmelCase__			,			position_ids=UpperCAmelCase__			,			)
        SCREAMING_SNAKE_CASE	: List[Any]					       =				jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]]			,			dtype="""i4"""						)
        SCREAMING_SNAKE_CASE	: str					       =				model(
            input_ids[:, -1:]			,			past_key_values=outputs_cache.past_key_values			,			attention_mask=UpperCAmelCase__			,			position_ids=UpperCAmelCase__			,			)

        SCREAMING_SNAKE_CASE	: List[Any]					       =				model(UpperCAmelCase__			,			attention_mask=UpperCAmelCase__						)
        SCREAMING_SNAKE_CASE	: Optional[Any]					       =				np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5])						)						)
        self.parent.assertTrue(diff < 1e-3			,			msg=f"Max diff is {diff}"						)







@require_sentencepiece
@require_flax
class     a__    (				UpperCAmelCase		,     UpperCAmelCase		,     unittest.TestCase    ):







  """simple docstring"""




  UpperCAmelCase__ :	Union[str, Any]         =(FlaxXGLMModel, FlaxXGLMForCausalLM) if is_flax_available() else ()
  UpperCAmelCase__ :	List[str]         =(FlaxXGLMForCausalLM,) if is_flax_available() else ()


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







        SCREAMING_SNAKE_CASE	: Any					       =				FlaxXGLMModelTester(self						)


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







        for model_class_name in self.all_model_classes:
              SCREAMING_SNAKE_CASE       ,		SCREAMING_SNAKE_CASE       ,		SCREAMING_SNAKE_CASE	: Dict					       =				self.model_tester.prepare_config_and_inputs()
              self.model_tester.check_use_cache_forward(UpperCAmelCase__			,			UpperCAmelCase__			,			UpperCAmelCase__			,			UpperCAmelCase__						)


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







        for model_class_name in self.all_model_classes:
              SCREAMING_SNAKE_CASE       ,		SCREAMING_SNAKE_CASE       ,		SCREAMING_SNAKE_CASE	: Optional[int]					       =				self.model_tester.prepare_config_and_inputs()
              self.model_tester.check_use_cache_forward_with_attn_mask(
                  UpperCAmelCase__			,			UpperCAmelCase__			,			UpperCAmelCase__			,			UpperCAmelCase__						)


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







        SCREAMING_SNAKE_CASE	: Optional[int]					       =				XGLMTokenizer.from_pretrained("""XGLM"""			,			padding_side="""left"""						)
        SCREAMING_SNAKE_CASE	: List[Any]					       =				tokenizer(["""Hello this is a long string""", """Hey"""]			,			return_tensors="""np"""			,			padding=UpperCAmelCase__			,			truncation=UpperCAmelCase__						)

        SCREAMING_SNAKE_CASE	: Dict					       =				FlaxXGLMForCausalLM.from_pretrained("""facebook/xglm-564M"""						)
        SCREAMING_SNAKE_CASE	: int					       =				1
        SCREAMING_SNAKE_CASE	: Union[str, Any]					       =				False

        SCREAMING_SNAKE_CASE	: Any					       =				jax.jit(model.generate						)

        SCREAMING_SNAKE_CASE	: Any					       =				jit_generate(inputs["""input_ids"""]			,			attention_mask=inputs["""attention_mask"""]						).sequences

        SCREAMING_SNAKE_CASE	: Tuple					       =				tokenizer.batch_decode(UpperCAmelCase__			,			skip_special_tokens=UpperCAmelCase__						)

        SCREAMING_SNAKE_CASE	: int					       =				[
            """Hello this is a long string of questions, but I'm not sure if I'm""",
            """Hey, I'm a newbie to the forum and I'""",
        ]

        self.assertListEqual(UpperCAmelCase__			,			UpperCAmelCase__						)


  @is_pt_flax_cross_test
  def 	_lowercase (     self      :	Optional[int]						)   ->Dict:
        """simple docstring"""







        SCREAMING_SNAKE_CASE       ,		SCREAMING_SNAKE_CASE	: List[str]					       =				self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
              with self.subTest(model_class.__name__						):
                    # prepare inputs
                    SCREAMING_SNAKE_CASE	: Any					       =				self._prepare_for_class(UpperCAmelCase__			,			UpperCAmelCase__						)
                    SCREAMING_SNAKE_CASE	: List[str]					       =				{k: torch.tensor(v.tolist()						) for k, v in prepared_inputs_dict.items()}

                    # load corresponding PyTorch class
                    SCREAMING_SNAKE_CASE	: str					       =				model_class.__name__[4:]  # Skip the "Flax" at the beginning
                    SCREAMING_SNAKE_CASE	: Any					       =				getattr(UpperCAmelCase__			,			UpperCAmelCase__						)

                    SCREAMING_SNAKE_CASE       ,		SCREAMING_SNAKE_CASE	: str					       =				pt_inputs["""input_ids"""].shape
                    SCREAMING_SNAKE_CASE	: Dict					       =				np.random.randint(0			,			seq_length - 1			,			size=(batch_size,)						)
                    for batch_idx, start_index in enumerate(UpperCAmelCase__						):
                          SCREAMING_SNAKE_CASE	: int					       =				0
                          SCREAMING_SNAKE_CASE	: Optional[Any]					       =				1
                          SCREAMING_SNAKE_CASE	: Dict					       =				0
                          SCREAMING_SNAKE_CASE	: Tuple					       =				1
                    SCREAMING_SNAKE_CASE	: Tuple					       =				pt_model_class(UpperCAmelCase__						).eval()
                    # Flax models don't use the `use_cache` option and cache is not returned as a default.
                    # So we disable `use_cache` here for PyTorch model.
                    SCREAMING_SNAKE_CASE	: Optional[Any]					       =				False
                    SCREAMING_SNAKE_CASE	: List[str]					       =				model_class(UpperCAmelCase__			,			dtype=jnp.floataa						)
                    SCREAMING_SNAKE_CASE	: Optional[int]					       =				convert_pytorch_state_dict_to_flax(pt_model.state_dict()			,			UpperCAmelCase__						)
                    SCREAMING_SNAKE_CASE	: List[str]					       =				fx_state

                    with torch.no_grad():
                          SCREAMING_SNAKE_CASE	: Union[str, Any]					       =				pt_model(**UpperCAmelCase__						).to_tuple()

                    SCREAMING_SNAKE_CASE	: str					       =				fx_model(**UpperCAmelCase__						).to_tuple()
                    self.assertEqual(len(UpperCAmelCase__						)			,			len(UpperCAmelCase__						)			,			"""Output lengths differ between Flax and PyTorch"""						)
                    for fx_output, pt_output in zip(UpperCAmelCase__			,			UpperCAmelCase__						):
                          self.assert_almost_equals(fx_output[:, -1]			,			pt_output[:, -1].numpy()			,			4e-2						)

                    with tempfile.TemporaryDirectory() as tmpdirname:
                          pt_model.save_pretrained(UpperCAmelCase__						)
                          SCREAMING_SNAKE_CASE	: Optional[Any]					       =				model_class.from_pretrained(UpperCAmelCase__			,			from_pt=UpperCAmelCase__						)

                    SCREAMING_SNAKE_CASE	: str					       =				fx_model_loaded(**UpperCAmelCase__						).to_tuple()
                    self.assertEqual(
                        len(UpperCAmelCase__						)			,			len(UpperCAmelCase__						)			,			"""Output lengths differ between Flax and PyTorch"""						)
                    for fx_output_loaded, pt_output in zip(UpperCAmelCase__			,			UpperCAmelCase__						):
                          self.assert_almost_equals(fx_output_loaded[:, -1]			,			pt_output[:, -1].numpy()			,			4e-2						)


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







        SCREAMING_SNAKE_CASE       ,		SCREAMING_SNAKE_CASE	: int					       =				self.model_tester.prepare_config_and_inputs_for_common()
        for model_class in self.all_model_classes:
              with self.subTest(model_class.__name__						):
                    # prepare inputs
                    SCREAMING_SNAKE_CASE	: Tuple					       =				self._prepare_for_class(UpperCAmelCase__			,			UpperCAmelCase__						)
                    SCREAMING_SNAKE_CASE	: str					       =				{k: torch.tensor(v.tolist()						) for k, v in prepared_inputs_dict.items()}

                    # load corresponding PyTorch class
                    SCREAMING_SNAKE_CASE	: int					       =				model_class.__name__[4:]  # Skip the "Flax" at the beginning
                    SCREAMING_SNAKE_CASE	: int					       =				getattr(UpperCAmelCase__			,			UpperCAmelCase__						)

                    SCREAMING_SNAKE_CASE	: Dict					       =				pt_model_class(UpperCAmelCase__						).eval()
                    SCREAMING_SNAKE_CASE	: Tuple					       =				False
                    SCREAMING_SNAKE_CASE	: Tuple					       =				model_class(UpperCAmelCase__			,			dtype=jnp.floataa						)

                    SCREAMING_SNAKE_CASE	: int					       =				load_flax_weights_in_pytorch_model(UpperCAmelCase__			,			fx_model.params						)
                    SCREAMING_SNAKE_CASE       ,		SCREAMING_SNAKE_CASE	: str					       =				pt_inputs["""input_ids"""].shape
                    SCREAMING_SNAKE_CASE	: List[str]					       =				np.random.randint(0			,			seq_length - 1			,			size=(batch_size,)						)
                    for batch_idx, start_index in enumerate(UpperCAmelCase__						):
                          SCREAMING_SNAKE_CASE	: Tuple					       =				0
                          SCREAMING_SNAKE_CASE	: Union[str, Any]					       =				1
                          SCREAMING_SNAKE_CASE	: int					       =				0
                          SCREAMING_SNAKE_CASE	: Optional[Any]					       =				1

                    # make sure weights are tied in PyTorch
                    pt_model.tie_weights()

                    with torch.no_grad():
                          SCREAMING_SNAKE_CASE	: Dict					       =				pt_model(**UpperCAmelCase__						).to_tuple()

                    SCREAMING_SNAKE_CASE	: List[str]					       =				fx_model(**UpperCAmelCase__						).to_tuple()
                    self.assertEqual(len(UpperCAmelCase__						)			,			len(UpperCAmelCase__						)			,			"""Output lengths differ between Flax and PyTorch"""						)
                    for fx_output, pt_output in zip(UpperCAmelCase__			,			UpperCAmelCase__						):
                          self.assert_almost_equals(fx_output[:, -1]			,			pt_output[:, -1].numpy()			,			4e-2						)

                    with tempfile.TemporaryDirectory() as tmpdirname:
                          fx_model.save_pretrained(UpperCAmelCase__						)
                          SCREAMING_SNAKE_CASE	: List[str]					       =				pt_model_class.from_pretrained(UpperCAmelCase__			,			from_flax=UpperCAmelCase__						)

                    with torch.no_grad():
                          SCREAMING_SNAKE_CASE	: Optional[Any]					       =				pt_model_loaded(**UpperCAmelCase__						).to_tuple()

                    self.assertEqual(
                        len(UpperCAmelCase__						)			,			len(UpperCAmelCase__						)			,			"""Output lengths differ between Flax and PyTorch"""						)
                    for fx_output, pt_output in zip(UpperCAmelCase__			,			UpperCAmelCase__						):
                          self.assert_almost_equals(fx_output[:, -1]			,			pt_output[:, -1].numpy()			,			4e-2						)




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







        for model_class_name in self.all_model_classes:
              SCREAMING_SNAKE_CASE	: int					       =				model_class_name.from_pretrained("""facebook/xglm-564M"""						)
              SCREAMING_SNAKE_CASE	: List[Any]					       =				model(np.ones((1, 1)						)						)
              self.assertIsNotNone(UpperCAmelCase__						)







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						)						)




