


import collections
import tempfile
import unittest

import numpy as np

from transformers.testing_utils import (
    is_pt_flax_cross_test,
    require_flax,
    require_torch,
    require_vision,
    slow,
    torch_device,
)
from transformers.utils import is_flax_available, is_torch_available, is_vision_available

from ...test_modeling_flax_common import floats_tensor, ids_tensor, random_attention_mask
from ..bert.test_modeling_flax_bert import FlaxBertModelTester
from ..clip.test_modeling_flax_clip import FlaxCLIPVisionModelTester
from ..vit.test_modeling_flax_vit import FlaxViTModelTester


if is_flax_available():
 from transformers import (
     FlaxBertModel,
     FlaxCLIPVisionModel,
     FlaxVisionTextDualEncoderModel,
     FlaxViTModel,
     VisionTextDualEncoderConfig,
     VisionTextDualEncoderProcessor,
 )
 from transformers.modeling_flax_pytorch_utils import (
     convert_pytorch_state_dict_to_flax,
     load_flax_weights_in_pytorch_model,
 )


if is_torch_available():
 import torch

 from transformers import VisionTextDualEncoderModel

if is_vision_available():
 from PIL import Image





def 	_lowerCAmelCase       (    _lowerCAmelCase )						->	str:


      '''simple docstring'''






      if isinstance(_lowerCAmelCase      ,	collections.abc.Iterable ):
            return x
      return (x, x)






@require_flax
class     UpperCamelCase:


     def 							SCREAMING_SNAKE_CASE_  (						self	:		Tuple     ,    SCREAMING_SNAKE_CASE	:		List[Any]     ,    SCREAMING_SNAKE_CASE	:		Tuple						)			->	Tuple:




           '''simple docstring'''

           pass


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




           '''simple docstring'''

           pass


     def 							SCREAMING_SNAKE_CASE_  (						self	:		str						)			->	int:




           '''simple docstring'''

           pass


     def 							SCREAMING_SNAKE_CASE_  (						self	:		Union[str, Any]     ,    SCREAMING_SNAKE_CASE	:		np.ndarray     ,    SCREAMING_SNAKE_CASE	:		np.ndarray     ,    SCREAMING_SNAKE_CASE	:		float						)			->	List[str]:




           '''simple docstring'''

           __snake_case				=		np.abs((a - b)						).max()
           self.assertLessEqual(SCREAMING_SNAKE_CASE     ,    SCREAMING_SNAKE_CASE     ,    f'''Difference between torch and flax is {diff} (>= {tol}).'''						)


     def 							SCREAMING_SNAKE_CASE_  (						self	:		Dict     ,    SCREAMING_SNAKE_CASE	:		Tuple     ,    SCREAMING_SNAKE_CASE	:		Any     ,    SCREAMING_SNAKE_CASE	:		Any     ,    SCREAMING_SNAKE_CASE	:		List[str]     ,    SCREAMING_SNAKE_CASE	:		Tuple=None     ,    **SCREAMING_SNAKE_CASE	:		Any						)			->	Union[str, Any]:




           '''simple docstring'''

           __snake_case				=		VisionTextDualEncoderConfig.from_vision_text_configs(SCREAMING_SNAKE_CASE     ,    SCREAMING_SNAKE_CASE						)

           __snake_case				=		FlaxVisionTextDualEncoderModel(SCREAMING_SNAKE_CASE						)

           __snake_case				=		model(input_ids=SCREAMING_SNAKE_CASE     ,    pixel_values=SCREAMING_SNAKE_CASE     ,    attention_mask=SCREAMING_SNAKE_CASE						)

           self.assertEqual(output["text_embeds"].shape     ,    (input_ids.shape[0], config.projection_dim)						)
           self.assertEqual(output["image_embeds"].shape     ,    (pixel_values.shape[0], config.projection_dim)						)


     def 							SCREAMING_SNAKE_CASE_  (						self	:		str     ,    SCREAMING_SNAKE_CASE	:		List[Any]     ,    SCREAMING_SNAKE_CASE	:		Optional[Any]     ,    SCREAMING_SNAKE_CASE	:		Optional[int]     ,    SCREAMING_SNAKE_CASE	:		Dict     ,    SCREAMING_SNAKE_CASE	:		str=None     ,    **SCREAMING_SNAKE_CASE	:		Any						)			->	Any:




           '''simple docstring'''

           __snake_case		,					__snake_case				=		self.get_vision_text_model(SCREAMING_SNAKE_CASE     ,    SCREAMING_SNAKE_CASE						)
           __snake_case				=		{"vision_model": vision_model, "text_model": text_model}
           __snake_case				=		FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**SCREAMING_SNAKE_CASE						)

           __snake_case				=		model(input_ids=SCREAMING_SNAKE_CASE     ,    pixel_values=SCREAMING_SNAKE_CASE     ,    attention_mask=SCREAMING_SNAKE_CASE						)

           self.assertEqual(output["text_embeds"].shape     ,    (input_ids.shape[0], model.config.projection_dim)						)
           self.assertEqual(output["image_embeds"].shape     ,    (pixel_values.shape[0], model.config.projection_dim)						)


     def 							SCREAMING_SNAKE_CASE_  (						self	:		List[Any]     ,    SCREAMING_SNAKE_CASE	:		Dict     ,    SCREAMING_SNAKE_CASE	:		Optional[Any]     ,    SCREAMING_SNAKE_CASE	:		int     ,    SCREAMING_SNAKE_CASE	:		str     ,    SCREAMING_SNAKE_CASE	:		Optional[int]=None     ,    **SCREAMING_SNAKE_CASE	:		Any						)			->	Optional[Any]:




           '''simple docstring'''

           __snake_case		,					__snake_case				=		self.get_vision_text_model(SCREAMING_SNAKE_CASE     ,    SCREAMING_SNAKE_CASE						)
           __snake_case				=		{"vision_model": vision_model, "text_model": text_model}
           __snake_case				=		FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**SCREAMING_SNAKE_CASE						)

           __snake_case				=		model(input_ids=SCREAMING_SNAKE_CASE     ,    pixel_values=SCREAMING_SNAKE_CASE     ,    attention_mask=SCREAMING_SNAKE_CASE						)
           __snake_case				=		output[0]

           with tempfile.TemporaryDirectory() as tmpdirname:
                 model.save_pretrained(SCREAMING_SNAKE_CASE						)
                 __snake_case				=		FlaxVisionTextDualEncoderModel.from_pretrained(SCREAMING_SNAKE_CASE						)

                 __snake_case				=		model(input_ids=SCREAMING_SNAKE_CASE     ,    pixel_values=SCREAMING_SNAKE_CASE     ,    attention_mask=SCREAMING_SNAKE_CASE						)
                 __snake_case				=		after_output[0]
                 __snake_case				=		np.amax(np.abs(out_a - out_a						)						)
                 self.assertLessEqual(SCREAMING_SNAKE_CASE     ,    1e-3						)


     def 							SCREAMING_SNAKE_CASE_  (						self	:		Optional[int]     ,    SCREAMING_SNAKE_CASE	:		Optional[int]     ,    SCREAMING_SNAKE_CASE	:		List[Any]     ,    SCREAMING_SNAKE_CASE	:		Optional[Any]     ,    SCREAMING_SNAKE_CASE	:		Tuple     ,    SCREAMING_SNAKE_CASE	:		Optional[int]=None     ,    **SCREAMING_SNAKE_CASE	:		Dict						)			->	Tuple:




           '''simple docstring'''

           __snake_case		,					__snake_case				=		self.get_vision_text_model(SCREAMING_SNAKE_CASE     ,    SCREAMING_SNAKE_CASE						)
           __snake_case				=		{"vision_model": vision_model, "text_model": text_model}
           __snake_case				=		FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**SCREAMING_SNAKE_CASE						)

           __snake_case				=		model(
               input_ids=SCREAMING_SNAKE_CASE     ,    pixel_values=SCREAMING_SNAKE_CASE     ,    attention_mask=SCREAMING_SNAKE_CASE     ,    output_attentions=SCREAMING_SNAKE_CASE						)

           __snake_case				=		output.vision_model_output.attentions
           self.assertEqual(len(SCREAMING_SNAKE_CASE						)     ,    vision_config.num_hidden_layers						)

           # in ViT, the seq_len equals the number of patches + 1 (we add 1 for the [CLS] token)
           __snake_case				=		to_atuple(vision_model.config.image_size						)
           __snake_case				=		to_atuple(vision_model.config.patch_size						)
           __snake_case				=		(image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
           __snake_case				=		num_patches + 1
           self.assertEqual(vision_attentions[0].shape[-3:]     ,    (vision_config.num_attention_heads, seq_len, seq_len)						)

           __snake_case				=		output.text_model_output.attentions
           self.assertEqual(len(SCREAMING_SNAKE_CASE						)     ,    text_config.num_hidden_layers						)

           self.assertEqual(
               text_attentions[0].shape[-3:]     ,    (text_config.num_attention_heads, input_ids.shape[-1], input_ids.shape[-1])     ,    )


     def 							SCREAMING_SNAKE_CASE_  (						self	:		Optional[int]     ,    SCREAMING_SNAKE_CASE	:		Any     ,    SCREAMING_SNAKE_CASE	:		Optional[Any]     ,    SCREAMING_SNAKE_CASE	:		Optional[int]						)			->	Tuple:




           '''simple docstring'''

           pt_model.to(SCREAMING_SNAKE_CASE						)
           pt_model.eval()

           # prepare inputs
           __snake_case				=		inputs_dict
           __snake_case				=		{k: torch.tensor(v.tolist()						) for k, v in flax_inputs.items()}

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

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

           # PT -> Flax
           with tempfile.TemporaryDirectory() as tmpdirname:
                 pt_model.save_pretrained(SCREAMING_SNAKE_CASE						)
                 __snake_case				=		FlaxVisionTextDualEncoderModel.from_pretrained(SCREAMING_SNAKE_CASE     ,    from_pt=SCREAMING_SNAKE_CASE						)

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

           # Flax -> PT
           with tempfile.TemporaryDirectory() as tmpdirname:
                 fx_model.save_pretrained(SCREAMING_SNAKE_CASE						)
                 __snake_case				=		VisionTextDualEncoderModel.from_pretrained(SCREAMING_SNAKE_CASE     ,    from_flax=SCREAMING_SNAKE_CASE						)

           pt_model_loaded.to(SCREAMING_SNAKE_CASE						)
           pt_model_loaded.eval()

           with torch.no_grad():
                 __snake_case				=		pt_model_loaded(**SCREAMING_SNAKE_CASE						).to_tuple()

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


     def 							SCREAMING_SNAKE_CASE_  (						self	:		Optional[int]     ,    SCREAMING_SNAKE_CASE	:		str     ,    SCREAMING_SNAKE_CASE	:		Optional[Any]     ,    SCREAMING_SNAKE_CASE	:		Dict						)			->	Tuple:




           '''simple docstring'''

           __snake_case				=		VisionTextDualEncoderConfig.from_vision_text_configs(SCREAMING_SNAKE_CASE     ,    SCREAMING_SNAKE_CASE						)

           __snake_case				=		VisionTextDualEncoderModel(SCREAMING_SNAKE_CASE						)
           __snake_case				=		FlaxVisionTextDualEncoderModel(SCREAMING_SNAKE_CASE						)

           __snake_case				=		convert_pytorch_state_dict_to_flax(pt_model.state_dict()     ,    SCREAMING_SNAKE_CASE						)
           __snake_case				=		fx_state

           self.check_pt_flax_equivalence(SCREAMING_SNAKE_CASE     ,    SCREAMING_SNAKE_CASE     ,    SCREAMING_SNAKE_CASE						)


     def 							SCREAMING_SNAKE_CASE_  (						self	:		Optional[int]     ,    SCREAMING_SNAKE_CASE	:		List[str]     ,    SCREAMING_SNAKE_CASE	:		Any     ,    SCREAMING_SNAKE_CASE	:		Dict						)			->	int:




           '''simple docstring'''

           __snake_case				=		VisionTextDualEncoderConfig.from_vision_text_configs(SCREAMING_SNAKE_CASE     ,    SCREAMING_SNAKE_CASE						)

           __snake_case				=		VisionTextDualEncoderModel(SCREAMING_SNAKE_CASE						)
           __snake_case				=		FlaxVisionTextDualEncoderModel(SCREAMING_SNAKE_CASE						)

           __snake_case				=		load_flax_weights_in_pytorch_model(SCREAMING_SNAKE_CASE     ,    fx_model.params						)

           self.check_pt_flax_equivalence(SCREAMING_SNAKE_CASE     ,    SCREAMING_SNAKE_CASE     ,    SCREAMING_SNAKE_CASE						)


     def 							SCREAMING_SNAKE_CASE_  (						self	:		Optional[Any]						)			->	Any:




           '''simple docstring'''

           __snake_case				=		self.prepare_config_and_inputs()
           self.check_model_from_pretrained_configs(**SCREAMING_SNAKE_CASE						)


     def 							SCREAMING_SNAKE_CASE_  (						self	:		Any						)			->	List[str]:




           '''simple docstring'''

           __snake_case				=		self.prepare_config_and_inputs()
           self.check_vision_text_dual_encoder_from_pretrained(**SCREAMING_SNAKE_CASE						)


     def 							SCREAMING_SNAKE_CASE_  (						self	:		Optional[int]						)			->	List[str]:




           '''simple docstring'''

           __snake_case				=		self.prepare_config_and_inputs()
           self.check_save_load(**SCREAMING_SNAKE_CASE						)


     def 							SCREAMING_SNAKE_CASE_  (						self	:		Tuple						)			->	Optional[int]:




           '''simple docstring'''

           __snake_case				=		self.prepare_config_and_inputs()
           self.check_vision_text_output_attention(**SCREAMING_SNAKE_CASE						)


     @is_pt_flax_cross_test
     def 							SCREAMING_SNAKE_CASE_  (						self	:		Dict						)			->	Any:




           '''simple docstring'''

           __snake_case				=		self.prepare_config_and_inputs()
           __snake_case				=		config_inputs_dict.pop("vision_config"						)
           __snake_case				=		config_inputs_dict.pop("text_config"						)

           __snake_case				=		config_inputs_dict

           self.check_equivalence_pt_to_flax(SCREAMING_SNAKE_CASE     ,    SCREAMING_SNAKE_CASE     ,    SCREAMING_SNAKE_CASE						)
           self.check_equivalence_flax_to_pt(SCREAMING_SNAKE_CASE     ,    SCREAMING_SNAKE_CASE     ,    SCREAMING_SNAKE_CASE						)






     @slow
     def 							SCREAMING_SNAKE_CASE_  (						self	:		List[str]						)			->	List[Any]:




           '''simple docstring'''

           __snake_case		,					__snake_case				=		self.get_pretrained_model_and_inputs()

           __snake_case				=		model_a(**SCREAMING_SNAKE_CASE						)
           __snake_case				=		outputs[0]

           with tempfile.TemporaryDirectory() as tmp_dirname:
                 model_a.save_pretrained(SCREAMING_SNAKE_CASE						)
                 __snake_case				=		FlaxVisionTextDualEncoderModel.from_pretrained(SCREAMING_SNAKE_CASE						)

                 __snake_case				=		model_a(**SCREAMING_SNAKE_CASE						)
                 __snake_case				=		after_outputs[0]
                 __snake_case				=		np.amax(np.abs(out_a - out_a						)						)
                 self.assertLessEqual(SCREAMING_SNAKE_CASE     ,    1e-5						)






@require_flax
class     UpperCamelCase(  _a     ,							unittest.TestCase   ):


     def 							SCREAMING_SNAKE_CASE_  (						self	:		List[Any]						)			->	List[str]:




           '''simple docstring'''

           __snake_case				=		FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(
               "hf-internal-testing/tiny-random-vit"     ,    "hf-internal-testing/tiny-bert"     ,    vision_from_pt=SCREAMING_SNAKE_CASE     ,    text_from_pt=SCREAMING_SNAKE_CASE     ,    )
           __snake_case				=		1_3
           __snake_case				=		floats_tensor(
               [
                   batch_size,
                   model.config.vision_config.num_channels,
                   model.config.vision_config.image_size,
                   model.config.vision_config.image_size,
               ]						)
           __snake_case				=		ids_tensor([batch_size, 4]     ,    model.config.text_config.vocab_size						)
           __snake_case				=		random_attention_mask([batch_size, 4]						)
           __snake_case				=		{"pixel_values": pixel_values, "input_ids": input_ids, "attention_mask": attention_mask}

           return model, inputs


     def 							SCREAMING_SNAKE_CASE_  (						self	:		Optional[int]     ,    SCREAMING_SNAKE_CASE	:		str     ,    SCREAMING_SNAKE_CASE	:		Any						)			->	Optional[Any]:




           '''simple docstring'''

           __snake_case				=		FlaxViTModel(SCREAMING_SNAKE_CASE						)
           __snake_case				=		FlaxBertModel(SCREAMING_SNAKE_CASE						)
           return vision_model, text_model






     def 							SCREAMING_SNAKE_CASE_  (						self	:		int						)			->	Tuple:




           '''simple docstring'''

           __snake_case				=		FlaxViTModelTester(self						)
           __snake_case				=		FlaxBertModelTester(self						)
           __snake_case				=		vit_model_tester.prepare_config_and_inputs()
           __snake_case				=		bert_model_tester.prepare_config_and_inputs()

           __snake_case		,					__snake_case				=		vision_config_and_inputs

           __snake_case		,					__snake_case		,					__snake_case		,					__snake_case				=		text_config_and_inputs

           # make sure that cross attention layers are added
           return {
               "text_config": text_config,
               "vision_config": vision_config,
               "pixel_values": pixel_values,
               "attention_mask": attention_mask,
               "input_ids": input_ids,
               "token_type_ids": token_type_ids,
           }






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


     def 							SCREAMING_SNAKE_CASE_  (						self	:		List[Any]						)			->	Optional[Any]:




           '''simple docstring'''

           __snake_case				=		FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(
               "hf-internal-testing/tiny-random-clip"     ,    "hf-internal-testing/tiny-bert"     ,    vision_from_pt=SCREAMING_SNAKE_CASE     ,    text_from_pt=SCREAMING_SNAKE_CASE     ,    )
           __snake_case				=		1_3
           __snake_case				=		floats_tensor(
               [
                   batch_size,
                   model.config.vision_config.num_channels,
                   model.config.vision_config.image_size,
                   model.config.vision_config.image_size,
               ]						)
           __snake_case				=		ids_tensor([batch_size, 4]     ,    model.config.text_config.vocab_size						)
           __snake_case				=		random_attention_mask([batch_size, 4]						)
           __snake_case				=		{"pixel_values": pixel_values, "input_ids": input_ids, "attention_mask": attention_mask}

           return model, inputs


     def 							SCREAMING_SNAKE_CASE_  (						self	:		List[Any]     ,    SCREAMING_SNAKE_CASE	:		int     ,    SCREAMING_SNAKE_CASE	:		List[str]						)			->	str:




           '''simple docstring'''

           __snake_case				=		FlaxCLIPVisionModel(SCREAMING_SNAKE_CASE						)
           __snake_case				=		FlaxBertModel(SCREAMING_SNAKE_CASE						)
           return vision_model, text_model






     def 							SCREAMING_SNAKE_CASE_  (						self	:		Optional[Any]						)			->	Optional[Any]:




           '''simple docstring'''

           __snake_case				=		FlaxCLIPVisionModelTester(self						)
           __snake_case				=		FlaxBertModelTester(self						)
           __snake_case				=		clip_model_tester.prepare_config_and_inputs()
           __snake_case				=		bert_model_tester.prepare_config_and_inputs()

           __snake_case		,					__snake_case				=		vision_config_and_inputs

           __snake_case		,					__snake_case		,					__snake_case		,					__snake_case				=		text_config_and_inputs

           # make sure that cross attention layers are added
           return {
               "text_config": text_config,
               "vision_config": vision_config,
               "pixel_values": pixel_values,
               "attention_mask": attention_mask,
               "input_ids": input_ids,
               "token_type_ids": token_type_ids,
           }






@require_flax
@require_vision
class     UpperCamelCase(  unittest.TestCase   ):


     @slow
     def 							SCREAMING_SNAKE_CASE_  (						self	:		List[Any]						)			->	Any:




           '''simple docstring'''

           __snake_case				=		FlaxVisionTextDualEncoderModel.from_pretrained("clip-italian/clip-italian"     ,    logit_scale_init_value=1.0						)
           __snake_case				=		VisionTextDualEncoderProcessor.from_pretrained("clip-italian/clip-italian"						)

           __snake_case				=		Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"						)
           __snake_case				=		processor(
               text=["una foto di un gatto", "una foto di un cane"]     ,    images=SCREAMING_SNAKE_CASE     ,    padding=SCREAMING_SNAKE_CASE     ,    return_tensors="np"						)

           __snake_case				=		model(**SCREAMING_SNAKE_CASE						)

           # verify the logits
           self.assertEqual(outputs.logits_per_image.shape     ,    (inputs.pixel_values.shape[0], inputs.input_ids.shape[0])						)
           self.assertEqual(
               outputs.logits_per_text.shape     ,    (inputs.input_ids.shape[0], inputs.pixel_values.shape[0])     ,    )

           __snake_case				=		np.array([[1.2284727, 0.3104122]]						)

           self.assertTrue(np.allclose(outputs.logits_per_image     ,    SCREAMING_SNAKE_CASE     ,    atol=1e-3						)						)









from collections import OrderedDict
from typing import Any, Mapping, Optional

from ... import PreTrainedTokenizer
from ...configuration_utils import PretrainedConfig
from ...file_utils import TensorType, is_torch_available
from ...onnx import OnnxConfig, OnnxConfigWithPast, OnnxSeqaSeqConfigWithPast
from ...onnx.utils import compute_effective_axis_dimension
from ...utils import logging


A							:					Tuple     						=     logging.get_logger(__name__)

A							:					int     						=     {
    'facebook/blenderbot_small-90M': 'https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/config.json',
    # See all BlenderbotSmall models at https://huggingface.co/models?filter=blenderbot_small
}






class     UpperCamelCase(  _a   ):
					snake_case_		:				str										=	"""blenderbot-small"""
					snake_case_		:				List[Any]										=	["""past_key_values"""]
					snake_case_		:				Any										=	{"""num_attention_heads""": """encoder_attention_heads""", """hidden_size""": """d_model"""}


					def __init__(						self	:		Optional[Any]     ,    SCREAMING_SNAKE_CASE	:		Optional[Any]=5_0_2_6_5     ,    SCREAMING_SNAKE_CASE	:		Optional[int]=5_1_2     ,    SCREAMING_SNAKE_CASE	:		Any=8     ,    SCREAMING_SNAKE_CASE	:		int=2_0_4_8     ,    SCREAMING_SNAKE_CASE	:		Any=1_6     ,    SCREAMING_SNAKE_CASE	:		Tuple=8     ,    SCREAMING_SNAKE_CASE	:		List[Any]=2_0_4_8     ,    SCREAMING_SNAKE_CASE	:		Optional[int]=1_6     ,    SCREAMING_SNAKE_CASE	:		Optional[Any]=0.0     ,    SCREAMING_SNAKE_CASE	:		str=0.0     ,    SCREAMING_SNAKE_CASE	:		Optional[int]=True     ,    SCREAMING_SNAKE_CASE	:		int=True     ,    SCREAMING_SNAKE_CASE	:		Optional[Any]="gelu"     ,    SCREAMING_SNAKE_CASE	:		Dict=5_1_2     ,    SCREAMING_SNAKE_CASE	:		Any=0.1     ,    SCREAMING_SNAKE_CASE	:		Dict=0.0     ,    SCREAMING_SNAKE_CASE	:		Any=0.0     ,    SCREAMING_SNAKE_CASE	:		int=0.02     ,    SCREAMING_SNAKE_CASE	:		List[Any]=1     ,    SCREAMING_SNAKE_CASE	:		int=False     ,    SCREAMING_SNAKE_CASE	:		Union[str, Any]=0     ,    SCREAMING_SNAKE_CASE	:		str=1     ,    SCREAMING_SNAKE_CASE	:		Optional[int]=2     ,    SCREAMING_SNAKE_CASE	:		Any=2     ,    **SCREAMING_SNAKE_CASE	:		Dict     ,    )			->	Optional[int]:




											'''simple docstring'''

											__snake_case				=		vocab_size
											__snake_case				=		max_position_embeddings
											__snake_case				=		d_model
											__snake_case				=		encoder_ffn_dim
											__snake_case				=		encoder_layers
											__snake_case				=		encoder_attention_heads
											__snake_case				=		decoder_ffn_dim
											__snake_case				=		decoder_layers
											__snake_case				=		decoder_attention_heads
											__snake_case				=		dropout
											__snake_case				=		attention_dropout
											__snake_case				=		activation_dropout
											__snake_case				=		activation_function
											__snake_case				=		init_std
											__snake_case				=		encoder_layerdrop
											__snake_case				=		decoder_layerdrop
											__snake_case				=		use_cache
											__snake_case				=		encoder_layers
											__snake_case				=		scale_embedding  # scale factor will be sqrt(d_model) if True

											super().__init__(
											    pad_token_id=SCREAMING_SNAKE_CASE     ,    bos_token_id=SCREAMING_SNAKE_CASE     ,    eos_token_id=SCREAMING_SNAKE_CASE     ,    is_encoder_decoder=SCREAMING_SNAKE_CASE     ,    decoder_start_token_id=SCREAMING_SNAKE_CASE     ,    forced_eos_token_id=SCREAMING_SNAKE_CASE     ,    **SCREAMING_SNAKE_CASE     ,    )






class     UpperCamelCase(  _a   ):


					@property
					def 							SCREAMING_SNAKE_CASE_  (						self	:		Optional[int]						)			->	Mapping[str, Mapping[int, str]]:




											'''simple docstring'''

											if self.task in ["default", "seq2seq-lm"]:
																	__snake_case				=		OrderedDict(
																	    [
																	        ("input_ids", {0: "batch", 1: "encoder_sequence"}),
																	        ("attention_mask", {0: "batch", 1: "encoder_sequence"}),
																	    ]						)

																	if self.use_past:
																							__snake_case				=		{0: "batch"}
																							__snake_case				=		{0: "batch", 1: "past_decoder_sequence + sequence"}
																	else:
																							__snake_case				=		{0: "batch", 1: "decoder_sequence"}
																							__snake_case				=		{0: "batch", 1: "decoder_sequence"}

																	if self.use_past:
																							self.fill_with_past_key_values_(SCREAMING_SNAKE_CASE     ,    direction="inputs"						)
											elif self.task == "causal-lm":
																	# TODO: figure this case out.
																	__snake_case				=		OrderedDict(
																	    [
																	        ("input_ids", {0: "batch", 1: "encoder_sequence"}),
																	        ("attention_mask", {0: "batch", 1: "encoder_sequence"}),
																	    ]						)
																	if self.use_past:
																							__snake_case		,					__snake_case				=		self.num_layers
																							for i in range(SCREAMING_SNAKE_CASE						):
																													__snake_case				=		{0: "batch", 2: "past_sequence + sequence"}
																													__snake_case				=		{0: "batch", 2: "past_sequence + sequence"}
											else:
																	__snake_case				=		OrderedDict(
																	    [
																	        ("input_ids", {0: "batch", 1: "encoder_sequence"}),
																	        ("attention_mask", {0: "batch", 1: "encoder_sequence"}),
																	        ("decoder_input_ids", {0: "batch", 1: "decoder_sequence"}),
																	        ("decoder_attention_mask", {0: "batch", 1: "decoder_sequence"}),
																	    ]						)

											return common_inputs


					@property
					def 							SCREAMING_SNAKE_CASE_  (						self	:		str						)			->	Mapping[str, Mapping[int, str]]:




											'''simple docstring'''

											if self.task in ["default", "seq2seq-lm"]:
																	__snake_case				=		super().outputs
											else:
																	__snake_case				=		super(SCREAMING_SNAKE_CASE     ,    self						).outputs
																	if self.use_past:
																							__snake_case		,					__snake_case				=		self.num_layers
																							for i in range(SCREAMING_SNAKE_CASE						):
																													__snake_case				=		{0: "batch", 2: "past_sequence + sequence"}
																													__snake_case				=		{0: "batch", 2: "past_sequence + sequence"}
											return common_outputs


					def 							SCREAMING_SNAKE_CASE_  (						self	:		List[Any]     ,    SCREAMING_SNAKE_CASE	:		PreTrainedTokenizer     ,    SCREAMING_SNAKE_CASE	:		int = -1     ,    SCREAMING_SNAKE_CASE	:		int = -1     ,    SCREAMING_SNAKE_CASE	:		bool = False     ,    SCREAMING_SNAKE_CASE	:		Optional[TensorType] = None     ,    )			->	Mapping[str, Any]:




											'''simple docstring'''

											__snake_case				=		self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
											    SCREAMING_SNAKE_CASE     ,    SCREAMING_SNAKE_CASE     ,    SCREAMING_SNAKE_CASE     ,    SCREAMING_SNAKE_CASE     ,    SCREAMING_SNAKE_CASE						)

											# Generate decoder inputs
											__snake_case				=		seq_length if not self.use_past else 1
											__snake_case				=		self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
											    SCREAMING_SNAKE_CASE     ,    SCREAMING_SNAKE_CASE     ,    SCREAMING_SNAKE_CASE     ,    SCREAMING_SNAKE_CASE     ,    SCREAMING_SNAKE_CASE						)
											__snake_case				=		{f'''decoder_{name}''': tensor for name, tensor in decoder_inputs.items()}
											__snake_case				=		dict(**SCREAMING_SNAKE_CASE     ,    **SCREAMING_SNAKE_CASE						)

											if self.use_past:
																	if not is_torch_available():
																							raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed."						)
																	else:
																							import torch
																	__snake_case		,					__snake_case				=		common_inputs["input_ids"].shape
																	__snake_case				=		common_inputs["decoder_input_ids"].shape[1]
																	__snake_case		,					__snake_case				=		self.num_attention_heads
																	__snake_case				=		(
																	    batch,
																	    num_encoder_attention_heads,
																	    encoder_seq_length,
																	    self._config.hidden_size // num_encoder_attention_heads,
																	)
																	__snake_case				=		decoder_seq_length + 3
																	__snake_case				=		(
																	    batch,
																	    num_decoder_attention_heads,
																	    decoder_past_length,
																	    self._config.hidden_size // num_decoder_attention_heads,
																	)

																	__snake_case				=		torch.cat(
																	    [common_inputs["decoder_attention_mask"], torch.ones(SCREAMING_SNAKE_CASE     ,    SCREAMING_SNAKE_CASE						)]     ,    dim=1						)

																	__snake_case				=		[]
																	# If the number of encoder and decoder layers are present in the model configuration, both are considered
																	__snake_case		,					__snake_case				=		self.num_layers
																	__snake_case				=		min(SCREAMING_SNAKE_CASE     ,    SCREAMING_SNAKE_CASE						)
																	__snake_case				=		max(SCREAMING_SNAKE_CASE     ,    SCREAMING_SNAKE_CASE						) - min_num_layers
																	__snake_case				=		"encoder" if num_encoder_layers > num_decoder_layers else "decoder"

																	for _ in range(SCREAMING_SNAKE_CASE						):
																							common_inputs["past_key_values"].append(
																							    (
																							        torch.zeros(SCREAMING_SNAKE_CASE						),
																							        torch.zeros(SCREAMING_SNAKE_CASE						),
																							        torch.zeros(SCREAMING_SNAKE_CASE						),
																							        torch.zeros(SCREAMING_SNAKE_CASE						),
																							    )						)
																	# TODO: test this.
																	__snake_case				=		encoder_shape if remaining_side_name == "encoder" else decoder_shape
																	for _ in range(SCREAMING_SNAKE_CASE     ,    SCREAMING_SNAKE_CASE						):
																							common_inputs["past_key_values"].append((torch.zeros(SCREAMING_SNAKE_CASE						), torch.zeros(SCREAMING_SNAKE_CASE						))						)
											return common_inputs


					def 							SCREAMING_SNAKE_CASE_  (						self	:		Union[str, Any]     ,    SCREAMING_SNAKE_CASE	:		PreTrainedTokenizer     ,    SCREAMING_SNAKE_CASE	:		int = -1     ,    SCREAMING_SNAKE_CASE	:		int = -1     ,    SCREAMING_SNAKE_CASE	:		bool = False     ,    SCREAMING_SNAKE_CASE	:		Optional[TensorType] = None     ,    )			->	Mapping[str, Any]:




											'''simple docstring'''

											__snake_case				=		self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
											    SCREAMING_SNAKE_CASE     ,    SCREAMING_SNAKE_CASE     ,    SCREAMING_SNAKE_CASE     ,    SCREAMING_SNAKE_CASE     ,    SCREAMING_SNAKE_CASE						)

											if self.use_past:
																	if not is_torch_available():
																							raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed."						)
																	else:
																							import torch
																	__snake_case		,					__snake_case				=		common_inputs["input_ids"].shape
																	# Not using the same length for past_key_values
																	__snake_case				=		seqlen + 2
																	__snake_case		,					__snake_case				=		self.num_layers
																	__snake_case		,					__snake_case				=		self.num_attention_heads
																	__snake_case				=		(
																	    batch,
																	    num_encoder_attention_heads,
																	    past_key_values_length,
																	    self._config.hidden_size // num_encoder_attention_heads,
																	)

																	__snake_case				=		common_inputs["attention_mask"].dtype
																	__snake_case				=		torch.cat(
																	    [common_inputs["attention_mask"], torch.ones(SCREAMING_SNAKE_CASE     ,    SCREAMING_SNAKE_CASE     ,    dtype=SCREAMING_SNAKE_CASE						)]     ,    dim=1						)
																	__snake_case				=		[
																	    (torch.zeros(SCREAMING_SNAKE_CASE						), torch.zeros(SCREAMING_SNAKE_CASE						)) for _ in range(SCREAMING_SNAKE_CASE						)
																	]
											return common_inputs


					def 							SCREAMING_SNAKE_CASE_  (						self	:		Dict     ,    SCREAMING_SNAKE_CASE	:		PreTrainedTokenizer     ,    SCREAMING_SNAKE_CASE	:		int = -1     ,    SCREAMING_SNAKE_CASE	:		int = -1     ,    SCREAMING_SNAKE_CASE	:		bool = False     ,    SCREAMING_SNAKE_CASE	:		Optional[TensorType] = None     ,    )			->	Mapping[str, Any]:




											'''simple docstring'''

											__snake_case				=		compute_effective_axis_dimension(
											    SCREAMING_SNAKE_CASE     ,    fixed_dimension=OnnxConfig.default_fixed_batch     ,    num_token_to_add=0						)

											# If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX
											__snake_case				=		tokenizer.num_special_tokens_to_add(SCREAMING_SNAKE_CASE						)
											__snake_case				=		compute_effective_axis_dimension(
											    SCREAMING_SNAKE_CASE     ,    fixed_dimension=OnnxConfig.default_fixed_sequence     ,    num_token_to_add=SCREAMING_SNAKE_CASE						)

											# Generate dummy inputs according to compute batch and sequence
											__snake_case				=		[" ".join([tokenizer.unk_token]						) * seq_length] * batch_size
											__snake_case				=		dict(tokenizer(SCREAMING_SNAKE_CASE     ,    return_tensors=SCREAMING_SNAKE_CASE						)						)
											return common_inputs


					def 							SCREAMING_SNAKE_CASE_  (						self	:		str     ,    SCREAMING_SNAKE_CASE	:		PreTrainedTokenizer     ,    SCREAMING_SNAKE_CASE	:		int = -1     ,    SCREAMING_SNAKE_CASE	:		int = -1     ,    SCREAMING_SNAKE_CASE	:		bool = False     ,    SCREAMING_SNAKE_CASE	:		Optional[TensorType] = None     ,    )			->	Mapping[str, Any]:




											'''simple docstring'''

											if self.task in ["default", "seq2seq-lm"]:
																	__snake_case				=		self._generate_dummy_inputs_for_default_and_seqaseq_lm(
																	    SCREAMING_SNAKE_CASE     ,    batch_size=SCREAMING_SNAKE_CASE     ,    seq_length=SCREAMING_SNAKE_CASE     ,    is_pair=SCREAMING_SNAKE_CASE     ,    framework=SCREAMING_SNAKE_CASE						)

											elif self.task == "causal-lm":
																	__snake_case				=		self._generate_dummy_inputs_for_causal_lm(
																	    SCREAMING_SNAKE_CASE     ,    batch_size=SCREAMING_SNAKE_CASE     ,    seq_length=SCREAMING_SNAKE_CASE     ,    is_pair=SCREAMING_SNAKE_CASE     ,    framework=SCREAMING_SNAKE_CASE						)
											else:
																	__snake_case				=		self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
																	    SCREAMING_SNAKE_CASE     ,    batch_size=SCREAMING_SNAKE_CASE     ,    seq_length=SCREAMING_SNAKE_CASE     ,    is_pair=SCREAMING_SNAKE_CASE     ,    framework=SCREAMING_SNAKE_CASE						)

											return common_inputs






					def 							SCREAMING_SNAKE_CASE_  (						self	:		int     ,    SCREAMING_SNAKE_CASE	:		Any     ,    SCREAMING_SNAKE_CASE	:		int     ,    SCREAMING_SNAKE_CASE	:		List[Any]     ,    SCREAMING_SNAKE_CASE	:		int						)			->	Union[str, Any]:




											'''simple docstring'''

											if self.task in ["default", "seq2seq-lm"]:
																	__snake_case				=		super()._flatten_past_key_values_(SCREAMING_SNAKE_CASE     ,    SCREAMING_SNAKE_CASE     ,    SCREAMING_SNAKE_CASE     ,    SCREAMING_SNAKE_CASE						)
											else:
																	__snake_case				=		super(SCREAMING_SNAKE_CASE     ,    self						)._flatten_past_key_values_(
																	    SCREAMING_SNAKE_CASE     ,    SCREAMING_SNAKE_CASE     ,    SCREAMING_SNAKE_CASE     ,    SCREAMING_SNAKE_CASE						)





