


'''simple docstring'''




import inspect
import unittest

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

from ...test_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 MobileNetVaForImageClassification, MobileNetVaModel
       from transformers.models.mobilenet_va.modeling_mobilenet_va import MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
       from PIL import Image

       from transformers import MobileNetVaImageProcessor

class 		UpperCAmelCase_      (  _A		):





     def 							__UpperCAmelCase      ( self       :      str    )				->  List[Any]:
        lowerCAmelCase     =			self.config_class(**self.inputs_dict    )
        self.parent.assertTrue(hasattr(UpperCamelCase__    ,      'tf_padding'    )    )
        self.parent.assertTrue(hasattr(UpperCamelCase__    ,      'depth_multiplier'    )    )




class 		UpperCAmelCase_      :





     def __init__( self       :      Dict    ,      UpperCAmelCase__       :      str    ,      UpperCAmelCase__       :      Any=1_3    ,      UpperCAmelCase__       :      Optional[int]=3    ,      UpperCAmelCase__       :      str=3_2    ,      UpperCAmelCase__       :      Any=0.25    ,      UpperCAmelCase__       :      Union[str, Any]=8    ,      UpperCAmelCase__       :      Tuple=True    ,      UpperCAmelCase__       :      int=1_0_2_4    ,      UpperCAmelCase__       :      str=3_2    ,      UpperCAmelCase__       :      List[Any]="relu6"    ,      UpperCAmelCase__       :      Any=0.1    ,      UpperCAmelCase__       :      Dict=0.02    ,      UpperCAmelCase__       :      Optional[int]=True    ,      UpperCAmelCase__       :      Optional[Any]=True    ,      UpperCAmelCase__       :      List[Any]=1_0    ,      UpperCAmelCase__       :      Optional[Any]=None    ,      )				->  int:
        lowerCAmelCase     =			parent
        lowerCAmelCase     =			batch_size
        lowerCAmelCase     =			num_channels
        lowerCAmelCase     =			image_size
        lowerCAmelCase     =			depth_multiplier
        lowerCAmelCase     =			min_depth
        lowerCAmelCase     =			tf_padding
        lowerCAmelCase     =			int(last_hidden_size * depth_multiplier    )
        lowerCAmelCase     =			output_stride
        lowerCAmelCase     =			hidden_act
        lowerCAmelCase     =			classifier_dropout_prob
        lowerCAmelCase     =			use_labels
        lowerCAmelCase     =			is_training
        lowerCAmelCase     =			num_labels
        lowerCAmelCase     =			initializer_range
        lowerCAmelCase     =			scope





     def 							__UpperCAmelCase      ( self       :      List[str]    )				->  Dict:
        lowerCAmelCase     =			floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]    )

        lowerCAmelCase     =			None
        lowerCAmelCase     =			None
        if self.use_labels:
           lowerCAmelCase     =			ids_tensor([self.batch_size]    ,      self.num_labels    )
           lowerCAmelCase     =			ids_tensor([self.batch_size, self.image_size, self.image_size]    ,      self.num_labels    )

        lowerCAmelCase     =			self.get_config()

        return config, pixel_values, labels, pixel_labels





     def 							__UpperCAmelCase      ( self       :      int    )				->  int:
        return MobileNetVaConfig(
            num_channels=self.num_channels    ,      image_size=self.image_size    ,      depth_multiplier=self.depth_multiplier    ,      min_depth=self.min_depth    ,      tf_padding=self.tf_padding    ,      hidden_act=self.hidden_act    ,      classifier_dropout_prob=self.classifier_dropout_prob    ,      initializer_range=self.initializer_range    ,      )





     def 							__UpperCAmelCase      ( self       :      List[str]    ,      UpperCAmelCase__       :      List[Any]    ,      UpperCAmelCase__       :      Union[str, Any]    ,      UpperCAmelCase__       :      List[str]    ,      UpperCAmelCase__       :      Optional[Any]    )				->  Tuple:
        lowerCAmelCase     =			MobileNetVaModel(config=UpperCamelCase__    )
        model.to(UpperCamelCase__    )
        model.eval()
        lowerCAmelCase     =			model(UpperCamelCase__    )
        self.parent.assertEqual(
            result.last_hidden_state.shape    ,      (
                self.batch_size,
                self.last_hidden_size,
                self.image_size // self.output_stride,
                self.image_size // self.output_stride,
            )    ,      )





     def 							__UpperCAmelCase      ( self       :      Any    ,      UpperCAmelCase__       :      Any    ,      UpperCAmelCase__       :      Dict    ,      UpperCAmelCase__       :      Dict    ,      UpperCAmelCase__       :      Tuple    )				->  Dict:
        lowerCAmelCase     =			self.num_labels
        lowerCAmelCase     =			MobileNetVaForImageClassification(UpperCamelCase__    )
        model.to(UpperCamelCase__    )
        model.eval()
        lowerCAmelCase     =			model(UpperCamelCase__    ,      labels=UpperCamelCase__    )
        self.parent.assertEqual(result.logits.shape    ,      (self.batch_size, self.num_labels)    )





     def 							__UpperCAmelCase      ( self       :      Optional[int]    )				->  str:
        lowerCAmelCase     =			self.prepare_config_and_inputs()
        lowerCAmelCase     ,  lowerCAmelCase     ,  lowerCAmelCase     ,  lowerCAmelCase     =			config_and_inputs
        lowerCAmelCase     =			{'pixel_values': pixel_values}
        return config, inputs_dict




@require_torch
class 		UpperCAmelCase_      (  _A       ,	_A       ,	unittest.TestCase		):
     lowerCamelCase				:	Optional[Any]		=     (MobileNetVaModel, MobileNetVaForImageClassification) if is_torch_available() else ()
     lowerCamelCase				:	int		=     (
         {'''feature-extraction''': MobileNetVaModel, '''image-classification''': MobileNetVaForImageClassification}
         if is_torch_available()
         else {}
     )

     lowerCamelCase				:	Tuple		=     False
     lowerCamelCase				:	List[str]		=     False
     lowerCamelCase				:	List[Any]		=     False
     lowerCamelCase				:	int		=     False





     def 							__UpperCAmelCase      ( self       :      List[str]    )				->  List[Any]:
        lowerCAmelCase     =			MobileNetVaModelTester(self    )
        lowerCAmelCase     =			MobileNetVaConfigTester(self    ,      config_class=UpperCamelCase__    ,      has_text_modality=UpperCamelCase__    )





     def 							__UpperCAmelCase      ( self       :      str    )				->  str:
        self.config_tester.run_common_tests()





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





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





     @unittest.skip(reason='MobileNetV1 does not output attentions'    )
     def 							__UpperCAmelCase      ( self       :      Union[str, Any]    )				->  Tuple:
        pass





     def 							__UpperCAmelCase      ( self       :      Any    )				->  Optional[int]:
        lowerCAmelCase     ,  lowerCAmelCase     =			self.model_tester.prepare_config_and_inputs_for_common()

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

           lowerCAmelCase     =			['pixel_values']
           self.assertListEqual(arg_names[:1]    ,      UpperCamelCase__    )





     def 							__UpperCAmelCase      ( self       :      List[Any]    )				->  int:
        lowerCAmelCase     =			self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*UpperCamelCase__    )





     def 							__UpperCAmelCase      ( self       :      Optional[Any]    )				->  Optional[int]:






        def check_hidden_states_output(UpperCAmelCase__       :      Dict    ,      UpperCAmelCase__       :      int    ,      UpperCAmelCase__       :      Dict    ):
           lowerCAmelCase     =			model_class(UpperCamelCase__    )
           model.to(UpperCamelCase__    )
           model.eval()

           with torch.no_grad():
              lowerCAmelCase     =			model(**self._prepare_for_class(UpperCamelCase__    ,      UpperCamelCase__    )    )

           lowerCAmelCase     =			outputs.hidden_states

           lowerCAmelCase     =			2_6
           self.assertEqual(len(UpperCamelCase__    )    ,      UpperCamelCase__    )

        lowerCAmelCase     ,  lowerCAmelCase     =			self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
           lowerCAmelCase     =			True
           check_hidden_states_output(UpperCamelCase__    ,      UpperCamelCase__    ,      UpperCamelCase__    )

           # check that output_hidden_states also work using config
           del inputs_dict["output_hidden_states"]
           lowerCAmelCase     =			True

           check_hidden_states_output(UpperCamelCase__    ,      UpperCamelCase__    ,      UpperCamelCase__    )





     def 							__UpperCAmelCase      ( self       :      Optional[Any]    )				->  List[Any]:
        lowerCAmelCase     =			self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_image_classification(*UpperCamelCase__    )





     @slow
     def 							__UpperCAmelCase      ( self       :      Optional[int]    )				->  Optional[int]:






        for model_name in MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
           lowerCAmelCase     =			MobileNetVaModel.from_pretrained(UpperCamelCase__    )
           self.assertIsNotNone(UpperCamelCase__    )





def 	a_					( ):
   lowerCAmelCase     =			Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'				)
   return image




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





     @cached_property
     def 							__UpperCAmelCase      ( self       :      int    )				->  str:
        return (
            MobileNetVaImageProcessor.from_pretrained('google/mobilenet_v1_1.0_224'    ) if is_vision_available() else None
        )





     @slow
     def 							__UpperCAmelCase      ( self       :      Optional[int]    )				->  Optional[Any]:
        lowerCAmelCase     =			MobileNetVaForImageClassification.from_pretrained('google/mobilenet_v1_1.0_224'    ).to(UpperCamelCase__    )

        lowerCAmelCase     =			self.default_image_processor
        lowerCAmelCase     =			prepare_img()
        lowerCAmelCase     =			image_processor(images=UpperCamelCase__    ,      return_tensors='pt'    ).to(UpperCamelCase__    )

        # forward pass
        with torch.no_grad():
           lowerCAmelCase     =			model(**UpperCamelCase__    )

        # verify the logits
        lowerCAmelCase     =			torch.Size((1, 1_0_0_1)    )
        self.assertEqual(outputs.logits.shape    ,      UpperCamelCase__    )

        lowerCAmelCase     =			torch.tensor([-4.1_739, -1.1_233, 3.1_205]    ).to(UpperCamelCase__    )

        self.assertTrue(torch.allclose(outputs.logits[0, :3]    ,      UpperCamelCase__    ,      atol=1E-4    )    )







import unittest

from transformers import (
    MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING,
    TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING,
    TextaTextGenerationPipeline,
    pipeline,
)
from transformers.testing_utils import is_pipeline_test, require_tf, require_torch
from transformers.utils import is_torch_available

from .test_pipelines_common import ANY


if is_torch_available():
    import torch




@is_pipeline_test
class        UpperCAmelCase_			( unittest.TestCase     ):


  '''simple docstring'''







  a__           =		MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING
  a__           =		TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING
  def 							_lowercase							( self			: str			,							UpperCamelCase__			: Optional[int]			,							UpperCamelCase__			: int			,							UpperCamelCase__			: int    )			->	Tuple:







    """simple docstring"""






    __magic_name__				     =       TextaTextGenerationPipeline(model=UpperCamelCase__			,							tokenizer=UpperCamelCase__    )
    return generator, ["Something to write", "Something else"]
  def 							_lowercase							( self			: Any			,							UpperCamelCase__			: Tuple			,							UpperCamelCase__			: List[str]    )			->	Optional[Any]:







    """simple docstring"""






    __magic_name__				     =       generator("""Something there"""    )
    self.assertEqual(UpperCamelCase__			,							[{"""generated_text""": ANY(UpperCamelCase__    )}]    )
    # These are encoder decoder, they don't just append to incoming string
    self.assertFalse(outputs[0]["""generated_text"""].startswith("""Something there"""    )    )

    __magic_name__				     =       generator(["""This is great !""", """Something else"""]			,							num_return_sequences=2			,							do_sample=UpperCamelCase__    )
    self.assertEqual(
        UpperCamelCase__			,							[
            [{"""generated_text""": ANY(UpperCamelCase__    )}, {"""generated_text""": ANY(UpperCamelCase__    )}],
            [{"""generated_text""": ANY(UpperCamelCase__    )}, {"""generated_text""": ANY(UpperCamelCase__    )}],
        ]			,							)

    __magic_name__				     =       generator(
        ["""This is great !""", """Something else"""]			,							num_return_sequences=2			,							batch_size=2			,							do_sample=UpperCamelCase__    )
    self.assertEqual(
        UpperCamelCase__			,							[
            [{"""generated_text""": ANY(UpperCamelCase__    )}, {"""generated_text""": ANY(UpperCamelCase__    )}],
            [{"""generated_text""": ANY(UpperCamelCase__    )}, {"""generated_text""": ANY(UpperCamelCase__    )}],
        ]			,							)

    with self.assertRaises(UpperCamelCase__    ):
      generator(4    )
  @require_torch
  def 							_lowercase							( self			: Optional[int]    )			->	Union[str, Any]:







    """simple docstring"""






    __magic_name__				     =       pipeline("""text2text-generation"""			,							model="""patrickvonplaten/t5-tiny-random"""			,							framework="""pt"""    )
    # do_sample=False necessary for reproducibility
    __magic_name__				     =       generator("""Something there"""			,							do_sample=UpperCamelCase__    )
    self.assertEqual(UpperCamelCase__			,							[{"""generated_text""": """"""}]    )

    __magic_name__				     =       3
    __magic_name__				     =       generator(
        """Something there"""			,							num_return_sequences=UpperCamelCase__			,							num_beams=UpperCamelCase__			,							)
    __magic_name__				     =       [
        {"""generated_text""": """Beide Beide Beide Beide Beide Beide Beide Beide Beide"""},
        {"""generated_text""": """Beide Beide Beide Beide Beide Beide Beide Beide"""},
        {"""generated_text""": """"""},
    ]
    self.assertEqual(UpperCamelCase__			,							UpperCamelCase__    )

    __magic_name__				     =       generator("""This is a test"""			,							do_sample=UpperCamelCase__			,							num_return_sequences=2			,							return_tensors=UpperCamelCase__    )
    self.assertEqual(
        UpperCamelCase__			,							[
            {"""generated_token_ids""": ANY(torch.Tensor    )},
            {"""generated_token_ids""": ANY(torch.Tensor    )},
        ]			,							)
    __magic_name__				     =       generator.model.config.eos_token_id
    __magic_name__				     =       """<pad>"""
    __magic_name__				     =       generator(
        ["""This is a test""", """This is a second test"""]			,							do_sample=UpperCamelCase__			,							num_return_sequences=2			,							batch_size=2			,							return_tensors=UpperCamelCase__			,							)
    self.assertEqual(
        UpperCamelCase__			,							[
            [
                {"""generated_token_ids""": ANY(torch.Tensor    )},
                {"""generated_token_ids""": ANY(torch.Tensor    )},
            ],
            [
                {"""generated_token_ids""": ANY(torch.Tensor    )},
                {"""generated_token_ids""": ANY(torch.Tensor    )},
            ],
        ]			,							)





  @require_tf
  def 							_lowercase							( self			: int    )			->	str:







    """simple docstring"""






    __magic_name__				     =       pipeline("""text2text-generation"""			,							model="""patrickvonplaten/t5-tiny-random"""			,							framework="""tf"""    )
    # do_sample=False necessary for reproducibility
    __magic_name__				     =       generator("""Something there"""			,							do_sample=UpperCamelCase__    )
    self.assertEqual(UpperCamelCase__			,							[{"""generated_text""": """"""}]    )

