





"""simple docstring"""
import copy
from typing import TYPE_CHECKING, Any, Mapping, Optional, OrderedDict

from packaging import version

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
from ..auto.configuration_auto import AutoConfig


if TYPE_CHECKING:
  from ... import PreTrainedTokenizerBase, TensorType

lowerCamelCase_								=		logging.get_logger(__name__)






class 					_SCREAMING_SNAKE_CASE(   UpperCAmelCase_  ):
       SCREAMING_SNAKE_CASE_   :      Tuple							=  '''vision-encoder-decoder'''
       SCREAMING_SNAKE_CASE_   :      Union[str, Any]							=  True




       def __init__(						self		,**SCREAMING_SNAKE_CASE__							)			->      Any:





             """simple docstring"""






             super().__init__(**lowerCAmelCase__							)
             if "encoder" not in kwargs or "decoder" not in kwargs:
                   raise ValueError(
                       f'''A configuraton of type {self.model_type} cannot be instantiated because '''
                       f'''not both `encoder` and `decoder` sub-configurations are passed, but only {kwargs}'''							)

             __SCREAMING_SNAKE_CASE   :Tuple						=  kwargs.pop('''encoder'''							)
             __SCREAMING_SNAKE_CASE   :List[str]						=  encoder_config.pop('''model_type'''							)
             __SCREAMING_SNAKE_CASE   :Union[str, Any]						=  kwargs.pop('''decoder'''							)
             __SCREAMING_SNAKE_CASE   :Any						=  decoder_config.pop('''model_type'''							)

             __SCREAMING_SNAKE_CASE   :Optional[Any]						=  AutoConfig.for_model(lowerCAmelCase__		,**lowerCAmelCase__							)
             __SCREAMING_SNAKE_CASE   :List[Any]						=  AutoConfig.for_model(lowerCAmelCase__		,**lowerCAmelCase__							)
             __SCREAMING_SNAKE_CASE   :List[Any]						=  True




       @classmethod
       def     _UpperCamelCase     (						cls		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,**SCREAMING_SNAKE_CASE__							)			->      List[Any]:





             """simple docstring"""






             logger.info('''Setting `config.is_decoder=True` and `config.add_cross_attention=True` for decoder_config'''							)
             __SCREAMING_SNAKE_CASE   :int						=  True
             __SCREAMING_SNAKE_CASE   :List[Any]						=  True

             return cls(encoder=encoder_config.to_dict()		,decoder=decoder_config.to_dict()		,**lowerCAmelCase__							)




       def     _UpperCamelCase     (						self							)			->      Optional[int]:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE   :Tuple						=  copy.deepcopy(self.__dict__							)
             __SCREAMING_SNAKE_CASE   :List[str]						=  self.encoder.to_dict()
             __SCREAMING_SNAKE_CASE   :Tuple						=  self.decoder.to_dict()
             __SCREAMING_SNAKE_CASE   :List[Any]						=  self.__class__.model_type
             return output






class 					_SCREAMING_SNAKE_CASE(   UpperCAmelCase_  ):
       SCREAMING_SNAKE_CASE_   :      int							=  version.parse('''1.11'''  )




       @property
       def     _UpperCamelCase     (						self							)			->      str:





             """simple docstring"""






             return OrderedDict(
                 [
                     ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}),
                 ]							)




       @property
       def     _UpperCamelCase     (						self							)			->      Any:





             """simple docstring"""






             return 1E-4




       @property
       def     _UpperCamelCase     (						self							)			->      List[Any]:





             """simple docstring"""






             return OrderedDict({'''last_hidden_state''': {0: '''batch''', 1: '''encoder_sequence'''}}							)






class 					_SCREAMING_SNAKE_CASE(   UpperCAmelCase_  ):




       @property
       def     _UpperCamelCase     (						self							)			->      Optional[int]:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE   :Tuple						=  OrderedDict()
             __SCREAMING_SNAKE_CASE   :Optional[Any]						=  {0: "batch", 1: "past_decoder_sequence + sequence"}
             __SCREAMING_SNAKE_CASE   :List[str]						=  {0: "batch", 1: "past_decoder_sequence + sequence"}
             __SCREAMING_SNAKE_CASE   :Union[str, Any]						=  {0: "batch", 1: "encoder_sequence"}

             return common_inputs




       def     _UpperCamelCase     (						self		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__ = -1		,SCREAMING_SNAKE_CASE__ = -1		,SCREAMING_SNAKE_CASE__ = False		,SCREAMING_SNAKE_CASE__ = None		,)			->      str:





             """simple docstring"""






             import torch

             __SCREAMING_SNAKE_CASE   :int						=  OrderedDict()

             __SCREAMING_SNAKE_CASE   :str						=  super().generate_dummy_inputs(
                 lowerCAmelCase__		,batch_size=lowerCAmelCase__		,seq_length=lowerCAmelCase__		,is_pair=lowerCAmelCase__		,framework=lowerCAmelCase__							)

             __SCREAMING_SNAKE_CASE   :Tuple						=  dummy_input["input_ids"].shape
             __SCREAMING_SNAKE_CASE   :List[Any]						=  (batch, encoder_sequence, self._config.encoder_hidden_size)
             __SCREAMING_SNAKE_CASE   :Any						=  dummy_input.pop('''input_ids'''							)
             __SCREAMING_SNAKE_CASE   :int						=  dummy_input.pop('''attention_mask'''							)
             __SCREAMING_SNAKE_CASE   :Union[str, Any]						=  torch.zeros(lowerCAmelCase__							)

             return common_inputs






class 					_SCREAMING_SNAKE_CASE(   UpperCAmelCase_  ):




       @property
       def     _UpperCamelCase     (						self							)			->      Any:





             """simple docstring"""






             pass




       def     _UpperCamelCase     (						self		,SCREAMING_SNAKE_CASE__							)			->      List[str]:





             """simple docstring"""






             return VisionEncoderDecoderEncoderOnnxConfig(lowerCAmelCase__							)




       def     _UpperCamelCase     (						self		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__ = "default"							)			->      Tuple:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE   :Optional[int]						=  encoder_config.hidden_size
             return VisionEncoderDecoderDecoderOnnxConfig(lowerCAmelCase__		,lowerCAmelCase__							)


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   __lowercase				( unittest.TestCase	):




			"""simple docstring"""







			_UpperCAmelCase   :							List[Any]										=     MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING
			_UpperCAmelCase   :							str										=     TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING



			def        _SCREAMING_SNAKE_CASE			( self  :     Any   ,						lowerCAmelCase__  :     List[str]   ,						lowerCAmelCase__  :     List[str]   ,						lowerCAmelCase__  :     Dict):
									SCREAMING_SNAKE_CASE_: Any  		=       TextaTextGenerationPipeline(model=lowerCAmelCase__   ,						tokenizer=lowerCAmelCase__)
									return generator, ["Something to write", "Something else"]



			def        _SCREAMING_SNAKE_CASE			( self  :     str   ,						lowerCAmelCase__  :     Dict   ,						lowerCAmelCase__  :     Any):
									SCREAMING_SNAKE_CASE_: List[Any]  		=       generator("Something there")
									self.assertEqual(lowerCAmelCase__   ,						[{"generated_text": ANY(lowerCAmelCase__)}])
									# These are encoder decoder, they don't just append to incoming string
									self.assertFalse(outputs[0]["generated_text"].startswith("Something there"))

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

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

									with self.assertRaises(lowerCAmelCase__):
															generator(4)



			@require_torch
			def        _SCREAMING_SNAKE_CASE			( self  :     Tuple):
									SCREAMING_SNAKE_CASE_: Optional[int]  		=       pipeline("text2text-generation"   ,						model="patrickvonplaten/t5-tiny-random"   ,						framework="pt")
									# do_sample=False necessary for reproducibility
									SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       generator("Something there"   ,						do_sample=lowerCAmelCase__)
									self.assertEqual(lowerCAmelCase__   ,						[{"generated_text": ""}])

									SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       3
									SCREAMING_SNAKE_CASE_: Any  		=       generator(
									    "Something there"   ,						num_return_sequences=lowerCAmelCase__   ,						num_beams=lowerCAmelCase__   ,						)
									SCREAMING_SNAKE_CASE_: Any  		=       [
									    {"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(lowerCAmelCase__   ,						lowerCAmelCase__)

									SCREAMING_SNAKE_CASE_: int  		=       generator("This is a test"   ,						do_sample=lowerCAmelCase__   ,						num_return_sequences=2   ,						return_tensors=lowerCAmelCase__)
									self.assertEqual(
									    lowerCAmelCase__   ,						[
									        {"generated_token_ids": ANY(torch.Tensor)},
									        {"generated_token_ids": ANY(torch.Tensor)},
									    ]   ,						)
									SCREAMING_SNAKE_CASE_: str  		=       generator.model.config.eos_token_id
									SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       "<pad>"
									SCREAMING_SNAKE_CASE_: Tuple  		=       generator(
									    ["This is a test", "This is a second test"]   ,						do_sample=lowerCAmelCase__   ,						num_return_sequences=2   ,						batch_size=2   ,						return_tensors=lowerCAmelCase__   ,						)
									self.assertEqual(
									    lowerCAmelCase__   ,						[
									        [
									            {"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        _SCREAMING_SNAKE_CASE			( self  :     Union[str, Any]):
									SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       pipeline("text2text-generation"   ,						model="patrickvonplaten/t5-tiny-random"   ,						framework="tf")
									# do_sample=False necessary for reproducibility
									SCREAMING_SNAKE_CASE_: List[Any]  		=       generator("Something there"   ,						do_sample=lowerCAmelCase__)
									self.assertEqual(lowerCAmelCase__   ,						[{"generated_text": ""}])






