
import argparse
import json
from pathlib import Path

import requests
import torch
from huggingface_hub import cached_download, hf_hub_download, hf_hub_url
from PIL import Image

from transformers import DetaConfig, DetaForObjectDetection, DetaImageProcessor
from transformers.utils import logging


logging.set_verbosity_info()
__SCREAMING_SNAKE_CASE     :				Optional[int]             =       logging.get_logger(__name__)
def       UpperCAmelCase__							(    ):


					'''simple docstring'''

					lowerCAmelCase						:   List[Any]							=       DetaConfig(
					    num_queries=9_00							,					encoder_ffn_dim=20_48							,					decoder_ffn_dim=20_48							,					num_feature_levels=5							,					assign_first_stage=__magic_name__							,					with_box_refine=__magic_name__							,					two_stage=__magic_name__							,					)

					# set labels
					lowerCAmelCase						:   Tuple							=       91
					lowerCAmelCase						:   Tuple							=       '''huggingface/label-files'''
					lowerCAmelCase						:   int							=       '''coco-detection-id2label.json'''
					lowerCAmelCase						:   List[Any]							=       json.load(open(cached_download(hf_hub_url(__magic_name__							,					__magic_name__							,					repo_type='''dataset'''					)					)							,					'''r'''					)					)
					lowerCAmelCase						:   List[Any]							=       {int(__magic_name__					): v for k, v in idalabel.items()}
					lowerCAmelCase						:   int							=       idalabel
					lowerCAmelCase						:   Optional[Any]							=       {v: k for k, v in idalabel.items()}

					return config
def       UpperCAmelCase__							(    __magic_name__  :       str					):


					'''simple docstring'''

					lowerCAmelCase						:   List[str]							=       []

					# stem
					# fmt: off
					rename_keys.append(('''backbone.0.body.conv1.weight''', '''model.backbone.model.embedder.embedder.convolution.weight''')					)
					rename_keys.append(('''backbone.0.body.bn1.weight''', '''model.backbone.model.embedder.embedder.normalization.weight''')					)
					rename_keys.append(('''backbone.0.body.bn1.bias''', '''model.backbone.model.embedder.embedder.normalization.bias''')					)
					rename_keys.append(('''backbone.0.body.bn1.running_mean''', '''model.backbone.model.embedder.embedder.normalization.running_mean''')					)
					rename_keys.append(('''backbone.0.body.bn1.running_var''', '''model.backbone.model.embedder.embedder.normalization.running_var''')					)
					# stages
					for stage_idx in range(len(config.backbone_config.depths					)					):
										for layer_idx in range(config.backbone_config.depths[stage_idx]					):
															# shortcut
															if layer_idx == 0:
																				rename_keys.append(
																				    (
																				        f'''backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.0.weight''',
																				        f'''model.backbone.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.convolution.weight''',
																				    )					)
																				rename_keys.append(
																				    (
																				        f'''backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.weight''',
																				        f'''model.backbone.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.weight''',
																				    )					)
																				rename_keys.append(
																				    (
																				        f'''backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.bias''',
																				        f'''model.backbone.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.bias''',
																				    )					)
																				rename_keys.append(
																				    (
																				        f'''backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.running_mean''',
																				        f'''model.backbone.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.running_mean''',
																				    )					)
																				rename_keys.append(
																				    (
																				        f'''backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.running_var''',
																				        f'''model.backbone.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.running_var''',
																				    )					)
															# 3 convs
															for i in range(3					):
																				rename_keys.append(
																				    (
																				        f'''backbone.0.body.layer{stage_idx + 1}.{layer_idx}.conv{i+1}.weight''',
																				        f'''model.backbone.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.convolution.weight''',
																				    )					)
																				rename_keys.append(
																				    (
																				        f'''backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.weight''',
																				        f'''model.backbone.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.weight''',
																				    )					)
																				rename_keys.append(
																				    (
																				        f'''backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.bias''',
																				        f'''model.backbone.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.bias''',
																				    )					)
																				rename_keys.append(
																				    (
																				        f'''backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.running_mean''',
																				        f'''model.backbone.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.running_mean''',
																				    )					)
																				rename_keys.append(
																				    (
																				        f'''backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.running_var''',
																				        f'''model.backbone.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.running_var''',
																				    )					)
    # transformer encoder
					for i in range(config.encoder_layers					):
										rename_keys.append((f'''transformer.encoder.layers.{i}.self_attn.sampling_offsets.weight''', f'''model.encoder.layers.{i}.self_attn.sampling_offsets.weight''')					)
										rename_keys.append((f'''transformer.encoder.layers.{i}.self_attn.sampling_offsets.bias''', f'''model.encoder.layers.{i}.self_attn.sampling_offsets.bias''')					)
										rename_keys.append((f'''transformer.encoder.layers.{i}.self_attn.attention_weights.weight''', f'''model.encoder.layers.{i}.self_attn.attention_weights.weight''')					)
										rename_keys.append((f'''transformer.encoder.layers.{i}.self_attn.attention_weights.bias''', f'''model.encoder.layers.{i}.self_attn.attention_weights.bias''')					)
										rename_keys.append((f'''transformer.encoder.layers.{i}.self_attn.value_proj.weight''', f'''model.encoder.layers.{i}.self_attn.value_proj.weight''')					)
										rename_keys.append((f'''transformer.encoder.layers.{i}.self_attn.value_proj.bias''', f'''model.encoder.layers.{i}.self_attn.value_proj.bias''')					)
										rename_keys.append((f'''transformer.encoder.layers.{i}.self_attn.output_proj.weight''', f'''model.encoder.layers.{i}.self_attn.output_proj.weight''')					)
										rename_keys.append((f'''transformer.encoder.layers.{i}.self_attn.output_proj.bias''', f'''model.encoder.layers.{i}.self_attn.output_proj.bias''')					)
										rename_keys.append((f'''transformer.encoder.layers.{i}.norm1.weight''', f'''model.encoder.layers.{i}.self_attn_layer_norm.weight''')					)
										rename_keys.append((f'''transformer.encoder.layers.{i}.norm1.bias''', f'''model.encoder.layers.{i}.self_attn_layer_norm.bias''')					)
										rename_keys.append((f'''transformer.encoder.layers.{i}.linear1.weight''', f'''model.encoder.layers.{i}.fc1.weight''')					)
										rename_keys.append((f'''transformer.encoder.layers.{i}.linear1.bias''', f'''model.encoder.layers.{i}.fc1.bias''')					)
										rename_keys.append((f'''transformer.encoder.layers.{i}.linear2.weight''', f'''model.encoder.layers.{i}.fc2.weight''')					)
										rename_keys.append((f'''transformer.encoder.layers.{i}.linear2.bias''', f'''model.encoder.layers.{i}.fc2.bias''')					)
										rename_keys.append((f'''transformer.encoder.layers.{i}.norm2.weight''', f'''model.encoder.layers.{i}.final_layer_norm.weight''')					)
										rename_keys.append((f'''transformer.encoder.layers.{i}.norm2.bias''', f'''model.encoder.layers.{i}.final_layer_norm.bias''')					)

					# transformer decoder
					for i in range(config.decoder_layers					):
										rename_keys.append((f'''transformer.decoder.layers.{i}.cross_attn.sampling_offsets.weight''', f'''model.decoder.layers.{i}.encoder_attn.sampling_offsets.weight''')					)
										rename_keys.append((f'''transformer.decoder.layers.{i}.cross_attn.sampling_offsets.bias''', f'''model.decoder.layers.{i}.encoder_attn.sampling_offsets.bias''')					)
										rename_keys.append((f'''transformer.decoder.layers.{i}.cross_attn.attention_weights.weight''', f'''model.decoder.layers.{i}.encoder_attn.attention_weights.weight''')					)
										rename_keys.append((f'''transformer.decoder.layers.{i}.cross_attn.attention_weights.bias''', f'''model.decoder.layers.{i}.encoder_attn.attention_weights.bias''')					)
										rename_keys.append((f'''transformer.decoder.layers.{i}.cross_attn.value_proj.weight''', f'''model.decoder.layers.{i}.encoder_attn.value_proj.weight''')					)
										rename_keys.append((f'''transformer.decoder.layers.{i}.cross_attn.value_proj.bias''', f'''model.decoder.layers.{i}.encoder_attn.value_proj.bias''')					)
										rename_keys.append((f'''transformer.decoder.layers.{i}.cross_attn.output_proj.weight''', f'''model.decoder.layers.{i}.encoder_attn.output_proj.weight''')					)
										rename_keys.append((f'''transformer.decoder.layers.{i}.cross_attn.output_proj.bias''', f'''model.decoder.layers.{i}.encoder_attn.output_proj.bias''')					)
										rename_keys.append((f'''transformer.decoder.layers.{i}.norm1.weight''', f'''model.decoder.layers.{i}.encoder_attn_layer_norm.weight''')					)
										rename_keys.append((f'''transformer.decoder.layers.{i}.norm1.bias''', f'''model.decoder.layers.{i}.encoder_attn_layer_norm.bias''')					)
										rename_keys.append((f'''transformer.decoder.layers.{i}.self_attn.out_proj.weight''', f'''model.decoder.layers.{i}.self_attn.out_proj.weight''')					)
										rename_keys.append((f'''transformer.decoder.layers.{i}.self_attn.out_proj.bias''', f'''model.decoder.layers.{i}.self_attn.out_proj.bias''')					)
										rename_keys.append((f'''transformer.decoder.layers.{i}.norm2.weight''', f'''model.decoder.layers.{i}.self_attn_layer_norm.weight''')					)
										rename_keys.append((f'''transformer.decoder.layers.{i}.norm2.bias''', f'''model.decoder.layers.{i}.self_attn_layer_norm.bias''')					)
										rename_keys.append((f'''transformer.decoder.layers.{i}.linear1.weight''', f'''model.decoder.layers.{i}.fc1.weight''')					)
										rename_keys.append((f'''transformer.decoder.layers.{i}.linear1.bias''', f'''model.decoder.layers.{i}.fc1.bias''')					)
										rename_keys.append((f'''transformer.decoder.layers.{i}.linear2.weight''', f'''model.decoder.layers.{i}.fc2.weight''')					)
										rename_keys.append((f'''transformer.decoder.layers.{i}.linear2.bias''', f'''model.decoder.layers.{i}.fc2.bias''')					)
										rename_keys.append((f'''transformer.decoder.layers.{i}.norm3.weight''', f'''model.decoder.layers.{i}.final_layer_norm.weight''')					)
										rename_keys.append((f'''transformer.decoder.layers.{i}.norm3.bias''', f'''model.decoder.layers.{i}.final_layer_norm.bias''')					)

					# fmt: on

					return rename_keys
def       UpperCAmelCase__							(    __magic_name__  :       List[str]							,					__magic_name__  :       List[str]							,					__magic_name__  :       Optional[int]					):


					'''simple docstring'''

					lowerCAmelCase						:   Dict							=       dct.pop(__magic_name__					)
					lowerCAmelCase						:   Union[str, Any]							=       val
def       UpperCAmelCase__							(    __magic_name__  :       List[Any]							,					__magic_name__  :       int					):


					'''simple docstring'''

					lowerCAmelCase						:   List[str]							=       config.d_model
					for i in range(config.decoder_layers					):
										# read in weights + bias of input projection layer of self-attention
										lowerCAmelCase						:   Any							=       state_dict.pop(f'''transformer.decoder.layers.{i}.self_attn.in_proj_weight'''					)
										lowerCAmelCase						:   Dict							=       state_dict.pop(f'''transformer.decoder.layers.{i}.self_attn.in_proj_bias'''					)
										# next, add query, keys and values (in that order) to the state dict
										lowerCAmelCase						:   Tuple							=       in_proj_weight[:hidden_size, :]
										lowerCAmelCase						:   Any							=       in_proj_bias[:hidden_size]
										lowerCAmelCase						:   Dict							=       in_proj_weight[
										    hidden_size : hidden_size * 2, :
										]
										lowerCAmelCase						:   Union[str, Any]							=       in_proj_bias[hidden_size : hidden_size * 2]
										lowerCAmelCase						:   Dict							=       in_proj_weight[-hidden_size:, :]
										lowerCAmelCase						:   Dict							=       in_proj_bias[-hidden_size:]
def       UpperCAmelCase__							(    ):


					'''simple docstring'''

					lowerCAmelCase						:   List[Any]							=       '''http://images.cocodataset.org/val2017/000000039769.jpg'''
					lowerCAmelCase						:   Optional[int]							=       Image.open(requests.get(__magic_name__							,					stream=__magic_name__					).raw					)

					return im
@torch.no_grad()
def       UpperCAmelCase__							(    __magic_name__  :       int							,					__magic_name__  :       int							,					__magic_name__  :       int					):


					'''simple docstring'''

					lowerCAmelCase						:   Tuple							=       get_deta_config()

					# load original state dict
					if model_name == "deta-resnet-50":
										lowerCAmelCase						:   Any							=       '''adet_checkpoint0011.pth'''
					elif model_name == "deta-resnet-50-24-epochs":
										lowerCAmelCase						:   List[Any]							=       '''adet_2x_checkpoint0023.pth'''
					else:
										raise ValueError(f'''Model name {model_name} not supported'''					)
					lowerCAmelCase						:   List[Any]							=       hf_hub_download(repo_id='''nielsr/deta-checkpoints'''							,					filename=__magic_name__					)
					lowerCAmelCase						:   str							=       torch.load(__magic_name__							,					map_location='''cpu'''					)['''model''']

					# rename keys
					lowerCAmelCase						:   str							=       create_rename_keys(__magic_name__					)
					for src, dest in rename_keys:
										rename_key(__magic_name__							,					__magic_name__							,					__magic_name__					)
					read_in_decoder_q_k_v(__magic_name__							,					__magic_name__					)

					# fix some prefixes
					for key in state_dict.copy().keys():
										if "transformer.decoder.class_embed" in key or "transformer.decoder.bbox_embed" in key:
															lowerCAmelCase						:   str							=       state_dict.pop(__magic_name__					)
															lowerCAmelCase						:   Any							=       val
										if "input_proj" in key:
															lowerCAmelCase						:   Optional[Any]							=       state_dict.pop(__magic_name__					)
															lowerCAmelCase						:   Tuple							=       val
										if "level_embed" in key or "pos_trans" in key or "pix_trans" in key or "enc_output" in key:
															lowerCAmelCase						:   int							=       state_dict.pop(__magic_name__					)
															lowerCAmelCase						:   List[Any]							=       val

    # finally, create HuggingFace model and load state dict
					lowerCAmelCase						:   Optional[int]							=       DetaForObjectDetection(__magic_name__					)
					model.load_state_dict(__magic_name__					)
					model.eval()

					lowerCAmelCase						:   List[str]							=       '''cuda''' if torch.cuda.is_available() else '''cpu'''
					model.to(__magic_name__					)

					# load image processor
					lowerCAmelCase						:   Union[str, Any]							=       DetaImageProcessor(format='''coco_detection'''					)

					# verify our conversion on image
					lowerCAmelCase						:   List[Any]							=       prepare_img()
					lowerCAmelCase						:   str							=       processor(images=__magic_name__							,					return_tensors='''pt'''					)
					lowerCAmelCase						:   Optional[Any]							=       encoding['''pixel_values''']
					lowerCAmelCase						:   Dict							=       model(pixel_values.to(__magic_name__					)					)

					# verify logits
					if model_name == "deta-resnet-50":
										lowerCAmelCase						:   List[str]							=       torch.tensor(
										    [[-7.3978, -2.5406, -4.1668], [-8.2684, -3.9933, -3.8096], [-7.0515, -3.7973, -5.8516]]					)
										lowerCAmelCase						:   Optional[int]							=       torch.tensor([[0.5043, 0.4973, 0.9998], [0.2542, 0.5489, 0.4748], [0.5490, 0.2765, 0.0570]]					)
					elif model_name == "deta-resnet-50-24-epochs":
										lowerCAmelCase						:   List[Any]							=       torch.tensor(
										    [[-7.1688, -2.4857, -4.8669], [-7.8630, -3.8154, -4.2674], [-7.2730, -4.1865, -5.5323]]					)
										lowerCAmelCase						:   Any							=       torch.tensor([[0.5021, 0.4971, 0.9994], [0.2546, 0.5486, 0.4731], [0.1686, 0.1986, 0.2142]]					)

					assert torch.allclose(outputs.logits[0, :3, :3]							,					expected_logits.to(__magic_name__					)							,					atol=1e-4					)
					assert torch.allclose(outputs.pred_boxes[0, :3, :3]							,					expected_boxes.to(__magic_name__					)							,					atol=1e-4					)
					print('''Everything ok!'''					)

					if pytorch_dump_folder_path:
										# Save model and processor
										logger.info(f'''Saving PyTorch model and processor to {pytorch_dump_folder_path}...'''					)
										Path(__magic_name__					).mkdir(exist_ok=__magic_name__					)
										model.save_pretrained(__magic_name__					)
										processor.save_pretrained(__magic_name__					)

					# Push to hub
					if push_to_hub:
										print('''Pushing model and processor to hub...'''					)
										model.push_to_hub(f'''jozhang97/{model_name}'''					)
										processor.push_to_hub(f'''jozhang97/{model_name}'''					)


if __name__ == "__main__":
		__SCREAMING_SNAKE_CASE     :				Union[str, Any]             =       argparse.ArgumentParser()

		parser.add_argument(
		    '--model_name',
		    type=str,
		    default='deta-resnet-50',
		    choices=['deta-resnet-50', 'deta-resnet-50-24-epochs'],
		    help='Name of the model you\'d like to convert.',
		)
		parser.add_argument(
		    '--pytorch_dump_folder_path',
		    default=None,
		    type=str,
		    help='Path to the folder to output PyTorch model.',
		)
		parser.add_argument(
		    '--push_to_hub', action='store_true', help='Whether or not to push the converted model to the 🤗 hub.'
		)
		__SCREAMING_SNAKE_CASE     :				Optional[Any]             =       parser.parse_args()
		convert_deta_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)


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

from ... import PreTrainedTokenizer, TensorType, is_torch_available
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfigWithPast, PatchingSpec
from ...utils import logging


__SCREAMING_SNAKE_CASE     :				Optional[Any]             =       logging.get_logger(__name__)

__SCREAMING_SNAKE_CASE     :				int             =       {
    'gpt2': 'https://huggingface.co/gpt2/resolve/main/config.json',
    'gpt2-medium': 'https://huggingface.co/gpt2-medium/resolve/main/config.json',
    'gpt2-large': 'https://huggingface.co/gpt2-large/resolve/main/config.json',
    'gpt2-xl': 'https://huggingface.co/gpt2-xl/resolve/main/config.json',
    'distilgpt2': 'https://huggingface.co/distilgpt2/resolve/main/config.json',
}


class 						__magic_name__				(  snake_case      ):
		_lowerCAmelCase						=		"gpt2"
		_lowerCAmelCase						=		["past_key_values"]
		_lowerCAmelCase						=		{
		    "hidden_size": "n_embd",
		    "max_position_embeddings": "n_positions",
		    "num_attention_heads": "n_head",
		    "num_hidden_layers": "n_layer",
		}





		def __init__(							self      :		Union[str, Any]  ,					lowerCamelCase__      :		Tuple=5_0_2_5_7  ,					lowerCamelCase__      :		str=1_0_2_4  ,					lowerCamelCase__      :		Union[str, Any]=7_6_8  ,					lowerCamelCase__      :		Tuple=1_2  ,					lowerCamelCase__      :		Tuple=1_2  ,					lowerCamelCase__      :		List[str]=None  ,					lowerCamelCase__      :		Tuple="gelu_new"  ,					lowerCamelCase__      :		List[str]=0.1  ,					lowerCamelCase__      :		str=0.1  ,					lowerCamelCase__      :		List[str]=0.1  ,					lowerCamelCase__      :		Dict=1E-5  ,					lowerCamelCase__      :		Optional[Any]=0.0_2  ,					lowerCamelCase__      :		Tuple="cls_index"  ,					lowerCamelCase__      :		str=True  ,					lowerCamelCase__      :		Optional[int]=None  ,					lowerCamelCase__      :		int=True  ,					lowerCamelCase__      :		Tuple=0.1  ,					lowerCamelCase__      :		List[str]=True  ,					lowerCamelCase__      :		Dict=True  ,					lowerCamelCase__      :		Tuple=5_0_2_5_6  ,					lowerCamelCase__      :		Optional[int]=5_0_2_5_6  ,					lowerCamelCase__      :		Dict=False  ,					lowerCamelCase__      :		Tuple=False  ,					**lowerCamelCase__      :		List[str]  ,					):
							lowerCAmelCase						:   List[str]							=       vocab_size
							lowerCAmelCase						:   Dict							=       n_positions
							lowerCAmelCase						:   int							=       n_embd
							lowerCAmelCase						:   Union[str, Any]							=       n_layer
							lowerCAmelCase						:   List[str]							=       n_head
							lowerCAmelCase						:   str							=       n_inner
							lowerCAmelCase						:   Tuple							=       activation_function
							lowerCAmelCase						:   List[Any]							=       resid_pdrop
							lowerCAmelCase						:   Any							=       embd_pdrop
							lowerCAmelCase						:   int							=       attn_pdrop
							lowerCAmelCase						:   Dict							=       layer_norm_epsilon
							lowerCAmelCase						:   List[str]							=       initializer_range
							lowerCAmelCase						:   List[Any]							=       summary_type
							lowerCAmelCase						:   int							=       summary_use_proj
							lowerCAmelCase						:   List[str]							=       summary_activation
							lowerCAmelCase						:   List[str]							=       summary_first_dropout
							lowerCAmelCase						:   Optional[int]							=       summary_proj_to_labels
							lowerCAmelCase						:   Optional[int]							=       scale_attn_weights
							lowerCAmelCase						:   List[str]							=       use_cache
							lowerCAmelCase						:   List[Any]							=       scale_attn_by_inverse_layer_idx
							lowerCAmelCase						:   int							=       reorder_and_upcast_attn

							lowerCAmelCase						:   List[Any]							=       bos_token_id
							lowerCAmelCase						:   Optional[int]							=       eos_token_id

							super().__init__(bos_token_id=lowerCamelCase__  ,					eos_token_id=lowerCamelCase__  ,					**lowerCamelCase__			)



class 						__magic_name__				(  snake_case      ):





		def __init__(							self      :		str  ,					lowerCamelCase__      :		PretrainedConfig  ,					lowerCamelCase__      :		str = "default"  ,					lowerCamelCase__      :		List[PatchingSpec] = None  ,					lowerCamelCase__      :		bool = False  ,					):
							super().__init__(lowerCamelCase__  ,					task=lowerCamelCase__  ,					patching_specs=lowerCamelCase__  ,					use_past=lowerCamelCase__			)
							if not getattr(self._config  ,					'''pad_token_id'''  ,					lowerCamelCase__			):
												# TODO: how to do that better?
												lowerCAmelCase						:   str							=       0





		@property
		def  _A							(							self      :		Optional[Any]			):
							lowerCAmelCase						:   List[Any]							=       OrderedDict({'''input_ids''': {0: '''batch''', 1: '''sequence'''}}			)
							if self.use_past:
												self.fill_with_past_key_values_(lowerCamelCase__  ,					direction='''inputs'''			)
												lowerCAmelCase						:   str							=       {0: '''batch''', 1: '''past_sequence + sequence'''}
							else:
												lowerCAmelCase						:   int							=       {0: '''batch''', 1: '''sequence'''}

							return common_inputs





		@property
		def  _A							(							self      :		Optional[int]			):
							return self._config.n_layer





		@property
		def  _A							(							self      :		List[str]			):
							return self._config.n_head





		def  _A							(							self      :		List[str]  ,					lowerCamelCase__      :		PreTrainedTokenizer  ,					lowerCamelCase__      :		int = -1  ,					lowerCamelCase__      :		int = -1  ,					lowerCamelCase__      :		bool = False  ,					lowerCamelCase__      :		Optional[TensorType] = None  ,					):
							lowerCAmelCase						:   Union[str, Any]							=       super(lowerCamelCase__  ,					self			).generate_dummy_inputs(
							    lowerCamelCase__  ,					batch_size=lowerCamelCase__  ,					seq_length=lowerCamelCase__  ,					is_pair=lowerCamelCase__  ,					framework=lowerCamelCase__			)

							# We need to order the input in the way they appears in the forward()
							lowerCAmelCase						:   Tuple							=       OrderedDict({'''input_ids''': common_inputs['''input_ids''']}			)

							# Need to add the past_keys
							if self.use_past:
												if not is_torch_available():
																	raise ValueError('''Cannot generate dummy past_keys inputs without PyTorch installed.'''			)
												else:
																	import torch

																	lowerCAmelCase		,							lowerCAmelCase						:   Any							=       common_inputs['''input_ids'''].shape
																	# Not using the same length for past_key_values
																	lowerCAmelCase						:   Optional[int]							=       seqlen + 2
																	lowerCAmelCase						:   Any							=       (
																	    batch,
																	    self.num_attention_heads,
																	    past_key_values_length,
																	    self._config.hidden_size // self.num_attention_heads,
																	)
																	lowerCAmelCase						:   Any							=       [
																	    (torch.zeros(lowerCamelCase__			), torch.zeros(lowerCamelCase__			)) for _ in range(self.num_layers			)
																	]

							lowerCAmelCase						:   List[str]							=       common_inputs['''attention_mask''']
							if self.use_past:
												lowerCAmelCase						:   Optional[Any]							=       ordered_inputs['''attention_mask'''].dtype
												lowerCAmelCase						:   Optional[Any]							=       torch.cat(
												    [ordered_inputs['''attention_mask'''], torch.ones(lowerCamelCase__  ,					lowerCamelCase__  ,					dtype=lowerCamelCase__			)]  ,					dim=1			)

							return ordered_inputs





		@property
		def  _A							(							self      :		Union[str, Any]			):
							return 1_3
