




'''simple docstring'''
import colorsys
import io

import cva
import matplotlib as mpl
import matplotlib.colors as mplc
import matplotlib.figure as mplfigure
import numpy as np
import torch
from matplotlib.backends.backend_agg import FigureCanvasAgg

from utils import img_tensorize


A				: Optional[Any]					      =			1_000






class 			SCREAMING_SNAKE_CASE:

       def __init__(       self   ,						lowerCamelCase__   ,						lowerCamelCase__=1.2   ,						lowerCamelCase__="g"   ,						lowerCamelCase__=0.5   ,						lowerCamelCase__="-"   ,						lowerCamelCase__="test_out.jpg"   ,						lowerCamelCase__=True   ,						lowerCamelCase__=False   ,						lowerCamelCase__=None   ,						lowerCamelCase__=None   ,						lowerCamelCase__=0.7   ,						)       ->   Tuple:

           """simple docstring"""



           if isinstance(__UpperCAmelCase   ,						torch.Tensor	):
               __lowercase     							=		img.numpy().astype("""np.uint8"""	)
           if isinstance(__UpperCAmelCase   ,						__UpperCAmelCase	):
               __lowercase     							=		img_tensorize(__UpperCAmelCase	)
           assert isinstance(__UpperCAmelCase   ,						np.ndarray	)

           __lowercase							,__lowercase     							=		img.shape[1], img.shape[0]
           __lowercase     							=		mplfigure.Figure(frameon=__UpperCAmelCase	)
           __lowercase     							=		fig.get_dpi()
           __lowercase     							=		(width * scale + 1E-2) / dpi
           __lowercase     							=		(height * scale + 1E-2) / dpi
           fig.set_size_inches(__UpperCAmelCase   ,						__UpperCAmelCase	)
           __lowercase     							=		fig.add_axes([0.0, 0.0, 1.0, 1.0]	)
           ax.axis("""off"""	)
           ax.set_xlim(0.0   ,						__UpperCAmelCase	)
           ax.set_ylim(__UpperCAmelCase	)

           __lowercase     							=		saveas
           __lowercase     							=		rgb
           __lowercase     							=		pynb
           __lowercase     							=		img
           __lowercase     							=		edgecolor
           __lowercase     							=		0.5
           __lowercase     							=		linestyle
           __lowercase     							=		int(np.sqrt(min(__UpperCAmelCase   ,						__UpperCAmelCase	)	) * scale // 3	)
           __lowercase     							=		width
           __lowercase     							=		height
           __lowercase     							=		scale
           __lowercase     							=		fig
           __lowercase     							=		ax
           __lowercase     							=		pad
           __lowercase     							=		idaobj
           __lowercase     							=		idaattr
           __lowercase     							=		FigureCanvasAgg(__UpperCAmelCase	)

       def        snake_case__     (       self   ,						lowerCamelCase__   ,						lowerCamelCase__=None	)       ->   str:

           """simple docstring"""



           if color is None:
               __lowercase     							=		self.edgecolor
           ((__lowercase)							,(__lowercase)							,(__lowercase)							,(__lowercase))     							=		box
           __lowercase     							=		xa - xa
           __lowercase     							=		ya - ya
           self.ax.add_patch(
               mpl.patches.Rectangle(
                   (xa, ya)   ,						__UpperCAmelCase   ,						__UpperCAmelCase   ,						fill=__UpperCAmelCase   ,						edgecolor=__UpperCAmelCase   ,						linewidth=self.font_size // 3   ,						alpha=self.alpha   ,						linestyle=self.linestyle   ,						)	)

       def        snake_case__     (       self   ,						lowerCamelCase__   ,						lowerCamelCase__=None   ,						lowerCamelCase__=None   ,						lowerCamelCase__=None   ,						lowerCamelCase__=None	)       ->   Optional[Any]:

           """simple docstring"""



           if len(boxes.shape	) > 2:
               __lowercase     							=		boxes[0]
           if len(obj_ids.shape	) > 1:
               __lowercase     							=		obj_ids[0]
           if len(obj_scores.shape	) > 1:
               __lowercase     							=		obj_scores[0]
           if len(attr_ids.shape	) > 1:
               __lowercase     							=		attr_ids[0]
           if len(attr_scores.shape	) > 1:
               __lowercase     							=		attr_scores[0]
           if isinstance(__UpperCAmelCase   ,						torch.Tensor	):
               __lowercase     							=		boxes.numpy()
           if isinstance(__UpperCAmelCase   ,						__UpperCAmelCase	):
               __lowercase     							=		np.array(__UpperCAmelCase	)
           assert isinstance(__UpperCAmelCase   ,						np.ndarray	)
           __lowercase     							=		np.prod(boxes[:, 2:] - boxes[:, :2]   ,						axis=1	)
           __lowercase     							=		np.argsort(-areas	).tolist()
           __lowercase     							=		boxes[sorted_idxs] if boxes is not None else None
           __lowercase     							=		obj_ids[sorted_idxs] if obj_ids is not None else None
           __lowercase     							=		obj_scores[sorted_idxs] if obj_scores is not None else None
           __lowercase     							=		attr_ids[sorted_idxs] if attr_ids is not None else None
           __lowercase     							=		attr_scores[sorted_idxs] if attr_scores is not None else None

           __lowercase     							=		[self._random_color(maximum=1	) for _ in range(len(__UpperCAmelCase	)	)]
           __lowercase     							=		[assigned_colors[idx] for idx in sorted_idxs]
           if obj_ids is not None:
               __lowercase     							=		self._create_text_labels_attr(__UpperCAmelCase   ,						__UpperCAmelCase   ,						__UpperCAmelCase   ,						__UpperCAmelCase	)
               for i in range(len(__UpperCAmelCase	)	):
                   __lowercase     							=		assigned_colors[i]
                   self.add_box(boxes[i]   ,						__UpperCAmelCase	)
                   self.draw_labels(labels[i]   ,						boxes[i]   ,						__UpperCAmelCase	)

       def        snake_case__     (       self   ,						lowerCamelCase__   ,						lowerCamelCase__   ,						lowerCamelCase__	)       ->   Any:

           """simple docstring"""



           __lowercase							,__lowercase							,__lowercase							,__lowercase     							=		box
           __lowercase     							=		(xa, ya)
           __lowercase     							=		(ya - ya) * (xa - xa)
           __lowercase     							=		_SMALL_OBJ * self.scale
           if instance_area < small or ya - ya < 40 * self.scale:
               if ya >= self.height - 5:
                   __lowercase     							=		(xa, ya)
               else:
                   __lowercase     							=		(xa, ya)

           __lowercase     							=		(ya - ya) / np.sqrt(self.height * self.width	)
           __lowercase     							=		self._change_color_brightness(__UpperCAmelCase   ,						brightness_factor=0.7	)
           __lowercase     							=		np.clip((height_ratio - 0.02) / 0.08 + 1   ,						1.2   ,						2	)
           font_size *= 0.75 * self.font_size

           self.draw_text(
               text=__UpperCAmelCase   ,						position=__UpperCAmelCase   ,						color=__UpperCAmelCase   ,						)

       def        snake_case__     (       self   ,						lowerCamelCase__   ,						lowerCamelCase__   ,						lowerCamelCase__="g"   ,						lowerCamelCase__="left"   ,						)       ->   Any:

           """simple docstring"""



           __lowercase     							=		0
           __lowercase     							=		self.font_size
           __lowercase     							=		np.maximum(list(mplc.to_rgb(__UpperCAmelCase	)	)   ,						0.2	)
           __lowercase     							=		max(0.8   ,						np.max(__UpperCAmelCase	)	)
           __lowercase     							=		{
               """facecolor""": """black""",
               """alpha""": self.alpha,
               """pad""": self.pad,
               """edgecolor""": """none""",
           }
           __lowercase							,__lowercase     							=		position
           self.ax.text(
               __UpperCAmelCase   ,						__UpperCAmelCase   ,						__UpperCAmelCase   ,						size=font_size * self.scale   ,						family="""sans-serif"""   ,						bbox=__UpperCAmelCase   ,						verticalalignment="""top"""   ,						horizontalalignment=__UpperCAmelCase   ,						color=__UpperCAmelCase   ,						zorder=10   ,						rotation=__UpperCAmelCase   ,						)

       def        snake_case__     (       self   ,						lowerCamelCase__=None	)       ->   List[Any]:

           """simple docstring"""



           if saveas is None:
               __lowercase     							=		self.saveas
           if saveas.lower().endswith(""".jpg"""	) or saveas.lower().endswith(""".png"""	):
               cva.imwrite(
                   __UpperCAmelCase   ,						self._get_buffer()[:, :, ::-1]   ,						)
           else:
               self.fig.savefig(__UpperCAmelCase	)

       def        snake_case__     (       self   ,						lowerCamelCase__   ,						lowerCamelCase__   ,						lowerCamelCase__   ,						lowerCamelCase__	)       ->   Tuple:

           """simple docstring"""



           __lowercase     							=		[self.idaobj[i] for i in classes]
           __lowercase     							=		[self.idaattr[i] for i in attr_classes]
           __lowercase     							=		[
               F'{label} {score:.2f} {attr} {attr_score:.2f}'
               for label, score, attr, attr_score in zip(__UpperCAmelCase   ,						__UpperCAmelCase   ,						__UpperCAmelCase   ,						__UpperCAmelCase	)
           ]
           return labels

       def        snake_case__     (       self   ,						lowerCamelCase__   ,						lowerCamelCase__	)       ->   Dict:

           """simple docstring"""



           __lowercase     							=		[self.idaobj[i] for i in classes]
           if scores is not None:
               if labels is None:
                   __lowercase     							=		["""{:.0f}%""".format(s * 100	) for s in scores]
               else:
                   __lowercase     							=		["""{} {:.0f}%""".format(__UpperCAmelCase   ,						s * 100	) for li, s in zip(__UpperCAmelCase   ,						__UpperCAmelCase	)]
           return labels

       def        snake_case__     (       self   ,						lowerCamelCase__=255	)       ->   List[str]:

           """simple docstring"""



           __lowercase     							=		np.random.randint(0   ,						len(_COLORS	)	)
           __lowercase     							=		_COLORS[idx] * maximum
           if not self.rgb:
               __lowercase     							=		ret[::-1]
           return ret

       def        snake_case__     (       self	)       ->   int:

           """simple docstring"""



           if not self.pynb:
               __lowercase							,__lowercase     							=		self.canvas.print_to_buffer()
               if (width, height) != (self.width, self.height):
                   __lowercase     							=		cva.resize(self.img   ,						(width, height)	)
               else:
                   __lowercase     							=		self.img
           else:
               __lowercase     							=		io.BytesIO()  # works for cairo backend
               self.canvas.print_rgba(__UpperCAmelCase	)
               __lowercase							,__lowercase     							=		self.width, self.height
               __lowercase     							=		buf.getvalue()
               __lowercase     							=		self.img

           __lowercase     							=		np.frombuffer(__UpperCAmelCase   ,						dtype="""uint8"""	)
           __lowercase     							=		buffer.reshape(__UpperCAmelCase   ,						__UpperCAmelCase   ,						4	)
           __lowercase							,__lowercase     							=		np.split(__UpperCAmelCase   ,						[3]   ,						axis=2	)

           try:
               import numexpr as ne  # fuse them with numexpr

               __lowercase     							=		ne.evaluate("""img * (1 - alpha / 255.0) + rgb * (alpha / 255.0)"""	)
           except ImportError:
               __lowercase     							=		alpha.astype("""float32"""	) / 255.0
               __lowercase     							=		img * (1 - alpha) + rgb * alpha

           return visualized_image.astype("""uint8"""	)




       def        snake_case__     (       self   ,						lowerCamelCase__   ,						lowerCamelCase__	)       ->   Optional[int]:

           """simple docstring"""



           assert brightness_factor >= -1.0 and brightness_factor <= 1.0
           __lowercase     							=		mplc.to_rgb(__UpperCAmelCase	)
           __lowercase     							=		colorsys.rgb_to_hls(*mplc.to_rgb(__UpperCAmelCase	)	)
           __lowercase     							=		polygon_color[1] + (brightness_factor * polygon_color[1])
           __lowercase     							=		0.0 if modified_lightness < 0.0 else modified_lightness
           __lowercase     							=		1.0 if modified_lightness > 1.0 else modified_lightness
           __lowercase     							=		colorsys.hls_to_rgb(polygon_color[0]   ,						__UpperCAmelCase   ,						polygon_color[2]	)
           return modified_color

A				: int					      =			(
    np.array(
        [
            0.0_00,
            0.4_47,
            0.7_41,
            0.8_50,
            0.3_25,
            0.0_98,
            0.9_29,
            0.6_94,
            0.1_25,
            0.4_94,
            0.1_84,
            0.5_56,
            0.4_66,
            0.6_74,
            0.1_88,
            0.3_01,
            0.7_45,
            0.9_33,
            0.6_35,
            0.0_78,
            0.1_84,
            0.3_00,
            0.3_00,
            0.3_00,
            0.6_00,
            0.6_00,
            0.6_00,
            1.0_00,
            0.0_00,
            0.0_00,
            1.0_00,
            0.5_00,
            0.0_00,
            0.7_49,
            0.7_49,
            0.0_00,
            0.0_00,
            1.0_00,
            0.0_00,
            0.0_00,
            0.0_00,
            1.0_00,
            0.6_67,
            0.0_00,
            1.0_00,
            0.3_33,
            0.3_33,
            0.0_00,
            0.3_33,
            0.6_67,
            0.0_00,
            0.3_33,
            1.0_00,
            0.0_00,
            0.6_67,
            0.3_33,
            0.0_00,
            0.6_67,
            0.6_67,
            0.0_00,
            0.6_67,
            1.0_00,
            0.0_00,
            1.0_00,
            0.3_33,
            0.0_00,
            1.0_00,
            0.6_67,
            0.0_00,
            1.0_00,
            1.0_00,
            0.0_00,
            0.0_00,
            0.3_33,
            0.5_00,
            0.0_00,
            0.6_67,
            0.5_00,
            0.0_00,
            1.0_00,
            0.5_00,
            0.3_33,
            0.0_00,
            0.5_00,
            0.3_33,
            0.3_33,
            0.5_00,
            0.3_33,
            0.6_67,
            0.5_00,
            0.3_33,
            1.0_00,
            0.5_00,
            0.6_67,
            0.0_00,
            0.5_00,
            0.6_67,
            0.3_33,
            0.5_00,
            0.6_67,
            0.6_67,
            0.5_00,
            0.6_67,
            1.0_00,
            0.5_00,
            1.0_00,
            0.0_00,
            0.5_00,
            1.0_00,
            0.3_33,
            0.5_00,
            1.0_00,
            0.6_67,
            0.5_00,
            1.0_00,
            1.0_00,
            0.5_00,
            0.0_00,
            0.3_33,
            1.0_00,
            0.0_00,
            0.6_67,
            1.0_00,
            0.0_00,
            1.0_00,
            1.0_00,
            0.3_33,
            0.0_00,
            1.0_00,
            0.3_33,
            0.3_33,
            1.0_00,
            0.3_33,
            0.6_67,
            1.0_00,
            0.3_33,
            1.0_00,
            1.0_00,
            0.6_67,
            0.0_00,
            1.0_00,
            0.6_67,
            0.3_33,
            1.0_00,
            0.6_67,
            0.6_67,
            1.0_00,
            0.6_67,
            1.0_00,
            1.0_00,
            1.0_00,
            0.0_00,
            1.0_00,
            1.0_00,
            0.3_33,
            1.0_00,
            1.0_00,
            0.6_67,
            1.0_00,
            0.3_33,
            0.0_00,
            0.0_00,
            0.5_00,
            0.0_00,
            0.0_00,
            0.6_67,
            0.0_00,
            0.0_00,
            0.8_33,
            0.0_00,
            0.0_00,
            1.0_00,
            0.0_00,
            0.0_00,
            0.0_00,
            0.1_67,
            0.0_00,
            0.0_00,
            0.3_33,
            0.0_00,
            0.0_00,
            0.5_00,
            0.0_00,
            0.0_00,
            0.6_67,
            0.0_00,
            0.0_00,
            0.8_33,
            0.0_00,
            0.0_00,
            1.0_00,
            0.0_00,
            0.0_00,
            0.0_00,
            0.1_67,
            0.0_00,
            0.0_00,
            0.3_33,
            0.0_00,
            0.0_00,
            0.5_00,
            0.0_00,
            0.0_00,
            0.6_67,
            0.0_00,
            0.0_00,
            0.8_33,
            0.0_00,
            0.0_00,
            1.0_00,
            0.0_00,
            0.0_00,
            0.0_00,
            0.1_43,
            0.1_43,
            0.1_43,
            0.8_57,
            0.8_57,
            0.8_57,
            1.0_00,
            1.0_00,
            1.0_00,
        ]
    )
    .astype(np.floataa)
    .reshape(-1, 3)
)





"""simple docstring"""




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


__lowerCamelCase									=	logging.get_logger(__name__)

__lowerCamelCase									=	{
    "facebook/blenderbot-3B": "https://huggingface.co/facebook/blenderbot-3B/resolve/main/config.json",
    # See all Blenderbot models at https://huggingface.co/models?filter=blenderbot
}
class      UpperCamelCase__(      __A			):
						lowerCAmelCase__	:    List[str]    				=		'blenderbot'
						lowerCAmelCase__	:    Union[str, Any]    				=		['past_key_values']
						lowerCAmelCase__	:    Optional[Any]    				=		{'num_attention_heads': 'encoder_attention_heads', 'hidden_size': 'd_model'}





						def __init__(							self		,__UpperCAmelCase=80_08		,__UpperCAmelCase=1_28		,__UpperCAmelCase=2		,__UpperCAmelCase=1_02_40		,__UpperCAmelCase=32		,__UpperCAmelCase=24		,__UpperCAmelCase=1_02_40		,__UpperCAmelCase=32		,__UpperCAmelCase=0.0		,__UpperCAmelCase=0.0		,__UpperCAmelCase=True		,__UpperCAmelCase=True		,__UpperCAmelCase="gelu"		,__UpperCAmelCase=25_60		,__UpperCAmelCase=0.1		,__UpperCAmelCase=0.0		,__UpperCAmelCase=0.0		,__UpperCAmelCase=0.0_2		,__UpperCAmelCase=1		,__UpperCAmelCase=False		,__UpperCAmelCase=0		,__UpperCAmelCase=1		,__UpperCAmelCase=2		,__UpperCAmelCase=3		,__UpperCAmelCase=2		,**__UpperCAmelCase		,)       ->					Any:
													A__						  =				vocab_size
													A__						  =				max_position_embeddings
													A__						  =				d_model
													A__						  =				encoder_ffn_dim
													A__						  =				encoder_layers
													A__						  =				encoder_attention_heads
													A__						  =				decoder_ffn_dim
													A__						  =				decoder_layers
													A__						  =				decoder_attention_heads
													A__						  =				dropout
													A__						  =				attention_dropout
													A__						  =				activation_dropout
													A__						  =				activation_function
													A__						  =				init_std
													A__						  =				encoder_layerdrop
													A__						  =				decoder_layerdrop
													A__						  =				use_cache
													A__						  =				encoder_layers
													A__						  =				scale_embedding  # scale factor will be sqrt(d_model) if True

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






class      UpperCamelCase__(      __A			):





						@property
						def 					snake_case__						(							self  )       ->					Mapping[str, Mapping[int, str]]:
													if self.task in ["default", "seq2seq-lm"]:
																				A__						  =				OrderedDict(
																				    [
																				        ('input_ids', {0: 'batch', 1: 'encoder_sequence'}),
																				        ('attention_mask', {0: 'batch', 1: 'encoder_sequence'}),
																				    ]  )
																				if self.use_past:
																											A__						  =				{0: 'batch'}
																											A__						  =				{0: 'batch', 1: 'past_decoder_sequence + sequence'}
																				else:
																											A__						  =				{0: 'batch', 1: 'decoder_sequence'}
																											A__						  =				{0: 'batch', 1: 'decoder_sequence'}
																				if self.use_past:
																											self.fill_with_past_key_values_(__UpperCAmelCase		,direction='inputs'  )
													elif self.task == "causal-lm":
																				A__						  =				OrderedDict(
																				    [
																				        ('input_ids', {0: 'batch', 1: 'encoder_sequence'}),
																				        ('attention_mask', {0: 'batch', 1: 'encoder_sequence'}),
																				    ]  )
																				if self.use_past:
																											A__  ,	A__						  =				self.num_layers
																											for i in range(__UpperCAmelCase  ):
																																		A__						  =				{0: 'batch', 2: 'past_sequence + sequence'}
																																		A__						  =				{0: 'batch', 2: 'past_sequence + sequence'}
													else:
																				A__						  =				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
						# Copied from transformers.models.bart.configuration_bart.BartOnnxConfig.outputs
						def 					snake_case__						(							self  )       ->					Mapping[str, Mapping[int, str]]:
													if self.task in ["default", "seq2seq-lm"]:
																				A__						  =				super().outputs
													else:
																				A__						  =				super(__UpperCAmelCase		,self  ).outputs
																				if self.use_past:
																											A__  ,	A__						  =				self.num_layers
																											for i in range(__UpperCAmelCase  ):
																																		A__						  =				{0: 'batch', 2: 'past_sequence + sequence'}
																																		A__						  =				{0: 'batch', 2: 'past_sequence + sequence'}
													return common_outputs





						def 					snake_case__						(							self		,__UpperCAmelCase		,__UpperCAmelCase = -1		,__UpperCAmelCase = -1		,__UpperCAmelCase = False		,__UpperCAmelCase = None		,)       ->					Mapping[str, Any]:
													A__						  =				self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
													    __UpperCAmelCase		,__UpperCAmelCase		,__UpperCAmelCase		,__UpperCAmelCase		,__UpperCAmelCase  )
													# Generate decoder inputs
													A__						  =				seq_length if not self.use_past else 1
													A__						  =				self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
													    __UpperCAmelCase		,__UpperCAmelCase		,__UpperCAmelCase		,__UpperCAmelCase		,__UpperCAmelCase  )
													A__						  =				{f'''decoder_{name}''': tensor for name, tensor in decoder_inputs.items()}
													A__						  =				dict(**__UpperCAmelCase		,**__UpperCAmelCase  )

													if self.use_past:
																				if not is_torch_available():
																											raise ValueError('Cannot generate dummy past_keys inputs without PyTorch installed.'  )
																				else:
																											import torch
																				A__  ,	A__						  =				common_inputs['input_ids'].shape
																				A__						  =				common_inputs['decoder_input_ids'].shape[1]
																				A__  ,	A__						  =				self.num_attention_heads
																				A__						  =				(
																				    batch,
																				    num_encoder_attention_heads,
																				    encoder_seq_length,
																				    self._config.hidden_size // num_encoder_attention_heads,
																				)
																				A__						  =				decoder_seq_length
																				A__						  =				(
																				    batch,
																				    num_decoder_attention_heads,
																				    decoder_past_length,
																				    self._config.hidden_size // num_decoder_attention_heads,
																				)
																				A__						  =				torch.cat(
																				    [common_inputs['decoder_attention_mask'], torch.ones(__UpperCAmelCase		,__UpperCAmelCase  )]		,dim=1  )
																				A__						  =				[]
																				A__  ,	A__						  =				self.num_layers

																				for _ in range(__UpperCAmelCase  ):
																											common_inputs["past_key_values"].append(
																											    (
																											        torch.zeros(__UpperCAmelCase  ),
																											        torch.zeros(__UpperCAmelCase  ),
																											        torch.zeros(__UpperCAmelCase  ),
																											        torch.zeros(__UpperCAmelCase  ),
																											    )  )
													return common_inputs





						def 					snake_case__						(							self		,__UpperCAmelCase		,__UpperCAmelCase = -1		,__UpperCAmelCase = -1		,__UpperCAmelCase = False		,__UpperCAmelCase = None		,)       ->					Mapping[str, Any]:
													A__						  =				self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
													    __UpperCAmelCase		,__UpperCAmelCase		,__UpperCAmelCase		,__UpperCAmelCase		,__UpperCAmelCase  )

													if self.use_past:
																				if not is_torch_available():
																											raise ValueError('Cannot generate dummy past_keys inputs without PyTorch installed.'  )
																				else:
																											import torch
																				A__  ,	A__						  =				common_inputs['input_ids'].shape
																				A__						  =				seqlen
																				A__  ,	A__						  =				self.num_layers
																				A__  ,	A__						  =				self.num_attention_heads
																				A__						  =				(
																				    batch,
																				    num_encoder_attention_heads,
																				    past_key_values_length,
																				    self._config.hidden_size // num_encoder_attention_heads,
																				)
																				A__						  =				common_inputs['attention_mask'].dtype
																				A__						  =				torch.cat(
																				    [common_inputs['attention_mask'], torch.ones(__UpperCAmelCase		,__UpperCAmelCase		,dtype=__UpperCAmelCase  )]		,dim=1  )
																				A__						  =				[
																				    (torch.zeros(__UpperCAmelCase  ), torch.zeros(__UpperCAmelCase  )) for _ in range(__UpperCAmelCase  )
																				]
													return common_inputs





						def 					snake_case__						(							self		,__UpperCAmelCase		,__UpperCAmelCase = -1		,__UpperCAmelCase = -1		,__UpperCAmelCase = False		,__UpperCAmelCase = None		,)       ->					Mapping[str, Any]:
													# Copied from OnnxConfig.generate_dummy_inputs
													# Did not use super(OnnxConfigWithPast, self).generate_dummy_inputs for code clarity.
													# If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX
													A__						  =				compute_effective_axis_dimension(
													    __UpperCAmelCase		,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
													A__						  =				tokenizer.num_special_tokens_to_add(__UpperCAmelCase  )
													A__						  =				compute_effective_axis_dimension(
													    __UpperCAmelCase		,fixed_dimension=OnnxConfig.default_fixed_sequence		,num_token_to_add=__UpperCAmelCase  )

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





						def 					snake_case__						(							self		,__UpperCAmelCase		,__UpperCAmelCase = -1		,__UpperCAmelCase = -1		,__UpperCAmelCase = False		,__UpperCAmelCase = None		,)       ->					Mapping[str, Any]:
													if self.task in ["default", "seq2seq-lm"]:
																				A__						  =				self._generate_dummy_inputs_for_default_and_seqaseq_lm(
																				    __UpperCAmelCase		,batch_size=__UpperCAmelCase		,seq_length=__UpperCAmelCase		,is_pair=__UpperCAmelCase		,framework=__UpperCAmelCase  )

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

													return common_inputs





						def 					snake_case__						(							self		,__UpperCAmelCase		,__UpperCAmelCase		,__UpperCAmelCase		,__UpperCAmelCase  )       ->					Tuple:
													if self.task in ["default", "seq2seq-lm"]:
																				A__						  =				super()._flatten_past_key_values_(__UpperCAmelCase		,__UpperCAmelCase		,__UpperCAmelCase		,__UpperCAmelCase  )
													else:
																				A__						  =				super(__UpperCAmelCase		,self  )._flatten_past_key_values_(
																				    __UpperCAmelCase		,__UpperCAmelCase		,__UpperCAmelCase		,__UpperCAmelCase  )





						def 					snake_case__						(							self		,__UpperCAmelCase		,__UpperCAmelCase  )       ->					int:
													if direction not in ["inputs", "outputs"]:
																				raise ValueError(f'''direction must either be "inputs" or "outputs", but {direction} was given'''  )

													A__						  =				'past_key_values' if direction == 'inputs' else 'present'
													A__  ,	A__						  =				self.num_layers

													A__						  =				'past_encoder_sequence'
													A__						  =				'past_decoder_sequence' if direction == 'inputs' else 'past_decoder_sequence + sequence'

													for i in range(__UpperCAmelCase  ):
																				A__						  =				{0: 'batch', 2: decoder_sequence}
																				A__						  =				{0: 'batch', 2: decoder_sequence}
																				A__						  =				{0: 'batch', 2: encoder_sequence}
																				A__						  =				{0: 'batch', 2: encoder_sequence}





