






"""simple docstring"""





import argparse
import json
from pathlib import Path

import requests
import torch
from huggingface_hub import hf_hub_download
from PIL import Image

from transformers import DetrConfig, DetrForObjectDetection, DetrForSegmentation, DetrImageProcessor, ResNetConfig
from transformers.utils import logging


logging.set_verbosity_info()
_UpperCamelCase     :		Union[str, Any]											=					logging.get_logger(__name__)





def        a_  (   _lowerCAmelCase						:				Optional[Any]  ):





       '''simple docstring'''

       if "resnet-50" in model_name:
              lowercase__    :	str     					=			ResNetConfig.from_pretrained('microsoft/resnet-50'  )
       elif "resnet-101" in model_name:
              lowercase__    :	str     					=			ResNetConfig.from_pretrained('microsoft/resnet-101'  )
       else:
              raise ValueError('Model name should include either resnet50 or resnet101'  )

       lowercase__    :	int     					=			DetrConfig(use_timm_backbone=_lowercase     ,				backbone_config=_lowercase  )

       # set label attributes
       lowercase__    :	Dict     					=			'''panoptic''' in model_name
       if is_panoptic:
              lowercase__    :	str     					=			250
       else:
              lowercase__    :	Any     					=			91
              lowercase__    :	Optional[int]     					=			'''huggingface/label-files'''
              lowercase__    :	Dict     					=			'''coco-detection-id2label.json'''
              lowercase__    :	Tuple     					=			json.load(open(hf_hub_download(_lowercase     ,				_lowercase     ,				repo_type='dataset'  )     ,				'r'  )  )
              lowercase__    :	int     					=			{int(_lowercase  ): v for k, v in idalabel.items()}
              lowercase__    :	str     					=			idalabel
              lowercase__    :	Optional[int]     					=			{v: k for k, v in idalabel.items()}

       return config, is_panoptic





def        a_  (   _lowerCAmelCase						:				str  ):





       '''simple docstring'''

       lowercase__    :	List[Any]     					=			[]

       # stem
       # fmt: off
       rename_keys.append(('backbone.0.body.conv1.weight', 'backbone.conv_encoder.model.embedder.embedder.convolution.weight')  )
       rename_keys.append(('backbone.0.body.bn1.weight', 'backbone.conv_encoder.model.embedder.embedder.normalization.weight')  )
       rename_keys.append(('backbone.0.body.bn1.bias', 'backbone.conv_encoder.model.embedder.embedder.normalization.bias')  )
       rename_keys.append(('backbone.0.body.bn1.running_mean', 'backbone.conv_encoder.model.embedder.embedder.normalization.running_mean')  )
       rename_keys.append(('backbone.0.body.bn1.running_var', 'backbone.conv_encoder.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"""backbone.conv_encoder.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"""backbone.conv_encoder.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"""backbone.conv_encoder.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"""backbone.conv_encoder.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"""backbone.conv_encoder.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"""backbone.conv_encoder.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"""backbone.conv_encoder.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"""backbone.conv_encoder.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"""backbone.conv_encoder.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"""backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.running_var""",
                                )  )
    # fmt: on

       for i in range(config.encoder_layers  ):
              # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms
              rename_keys.append(
                  (
                      f"""transformer.encoder.layers.{i}.self_attn.out_proj.weight""",
                      f"""encoder.layers.{i}.self_attn.out_proj.weight""",
                  )  )
              rename_keys.append(
                  (f"""transformer.encoder.layers.{i}.self_attn.out_proj.bias""", f"""encoder.layers.{i}.self_attn.out_proj.bias""")  )
              rename_keys.append((f"""transformer.encoder.layers.{i}.linear1.weight""", f"""encoder.layers.{i}.fc1.weight""")  )
              rename_keys.append((f"""transformer.encoder.layers.{i}.linear1.bias""", f"""encoder.layers.{i}.fc1.bias""")  )
              rename_keys.append((f"""transformer.encoder.layers.{i}.linear2.weight""", f"""encoder.layers.{i}.fc2.weight""")  )
              rename_keys.append((f"""transformer.encoder.layers.{i}.linear2.bias""", f"""encoder.layers.{i}.fc2.bias""")  )
              rename_keys.append(
                  (f"""transformer.encoder.layers.{i}.norm1.weight""", f"""encoder.layers.{i}.self_attn_layer_norm.weight""")  )
              rename_keys.append(
                  (f"""transformer.encoder.layers.{i}.norm1.bias""", f"""encoder.layers.{i}.self_attn_layer_norm.bias""")  )
              rename_keys.append(
                  (f"""transformer.encoder.layers.{i}.norm2.weight""", f"""encoder.layers.{i}.final_layer_norm.weight""")  )
              rename_keys.append((f"""transformer.encoder.layers.{i}.norm2.bias""", f"""encoder.layers.{i}.final_layer_norm.bias""")  )
              # decoder layers: 2 times output projection, 2 feedforward neural networks and 3 layernorms
              rename_keys.append(
                  (
                      f"""transformer.decoder.layers.{i}.self_attn.out_proj.weight""",
                      f"""decoder.layers.{i}.self_attn.out_proj.weight""",
                  )  )
              rename_keys.append(
                  (f"""transformer.decoder.layers.{i}.self_attn.out_proj.bias""", f"""decoder.layers.{i}.self_attn.out_proj.bias""")  )
              rename_keys.append(
                  (
                      f"""transformer.decoder.layers.{i}.multihead_attn.out_proj.weight""",
                      f"""decoder.layers.{i}.encoder_attn.out_proj.weight""",
                  )  )
              rename_keys.append(
                  (
                      f"""transformer.decoder.layers.{i}.multihead_attn.out_proj.bias""",
                      f"""decoder.layers.{i}.encoder_attn.out_proj.bias""",
                  )  )
              rename_keys.append((f"""transformer.decoder.layers.{i}.linear1.weight""", f"""decoder.layers.{i}.fc1.weight""")  )
              rename_keys.append((f"""transformer.decoder.layers.{i}.linear1.bias""", f"""decoder.layers.{i}.fc1.bias""")  )
              rename_keys.append((f"""transformer.decoder.layers.{i}.linear2.weight""", f"""decoder.layers.{i}.fc2.weight""")  )
              rename_keys.append((f"""transformer.decoder.layers.{i}.linear2.bias""", f"""decoder.layers.{i}.fc2.bias""")  )
              rename_keys.append(
                  (f"""transformer.decoder.layers.{i}.norm1.weight""", f"""decoder.layers.{i}.self_attn_layer_norm.weight""")  )
              rename_keys.append(
                  (f"""transformer.decoder.layers.{i}.norm1.bias""", f"""decoder.layers.{i}.self_attn_layer_norm.bias""")  )
              rename_keys.append(
                  (f"""transformer.decoder.layers.{i}.norm2.weight""", f"""decoder.layers.{i}.encoder_attn_layer_norm.weight""")  )
              rename_keys.append(
                  (f"""transformer.decoder.layers.{i}.norm2.bias""", f"""decoder.layers.{i}.encoder_attn_layer_norm.bias""")  )
              rename_keys.append(
                  (f"""transformer.decoder.layers.{i}.norm3.weight""", f"""decoder.layers.{i}.final_layer_norm.weight""")  )
              rename_keys.append((f"""transformer.decoder.layers.{i}.norm3.bias""", f"""decoder.layers.{i}.final_layer_norm.bias""")  )

       # convolutional projection + query embeddings + layernorm of decoder + class and bounding box heads
       rename_keys.extend(
           [
               ('input_proj.weight', 'input_projection.weight'),
               ('input_proj.bias', 'input_projection.bias'),
               ('query_embed.weight', 'query_position_embeddings.weight'),
               ('transformer.decoder.norm.weight', 'decoder.layernorm.weight'),
               ('transformer.decoder.norm.bias', 'decoder.layernorm.bias'),
               ('class_embed.weight', 'class_labels_classifier.weight'),
               ('class_embed.bias', 'class_labels_classifier.bias'),
               ('bbox_embed.layers.0.weight', 'bbox_predictor.layers.0.weight'),
               ('bbox_embed.layers.0.bias', 'bbox_predictor.layers.0.bias'),
               ('bbox_embed.layers.1.weight', 'bbox_predictor.layers.1.weight'),
               ('bbox_embed.layers.1.bias', 'bbox_predictor.layers.1.bias'),
               ('bbox_embed.layers.2.weight', 'bbox_predictor.layers.2.weight'),
               ('bbox_embed.layers.2.bias', 'bbox_predictor.layers.2.bias'),
           ]  )

       return rename_keys





def        a_  (   _lowerCAmelCase						:				Union[str, Any]     ,				_lowerCAmelCase						:				List[Any]     ,				_lowerCAmelCase						:				int  ):





       '''simple docstring'''

       lowercase__    :	int     					=			state_dict.pop(_lowercase  )
       lowercase__    :	List[str]     					=			val





def        a_  (   _lowerCAmelCase						:				Tuple     ,				_lowerCAmelCase						:				str=False  ):





       '''simple docstring'''

       lowercase__    :	Tuple     					=			''''''
       if is_panoptic:
              lowercase__    :	List[Any]     					=			'''detr.'''

       # first: transformer encoder
       for i in range(6  ):
              # read in weights + bias of input projection layer (in PyTorch's MultiHeadAttention, this is a single matrix + bias)
              lowercase__    :	int     					=			state_dict.pop(f"""{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_weight"""  )
              lowercase__    :	List[str]     					=			state_dict.pop(f"""{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_bias"""  )
              # next, add query, keys and values (in that order) to the state dict
              lowercase__    :	Any     					=			in_proj_weight[:256, :]
              lowercase__    :	int     					=			in_proj_bias[:256]
              lowercase__    :	Any     					=			in_proj_weight[256:512, :]
              lowercase__    :	Union[str, Any]     					=			in_proj_bias[256:512]
              lowercase__    :	int     					=			in_proj_weight[-256:, :]
              lowercase__    :	int     					=			in_proj_bias[-256:]
       # next: transformer decoder (which is a bit more complex because it also includes cross-attention)
       for i in range(6  ):
              # read in weights + bias of input projection layer of self-attention
              lowercase__    :	Optional[int]     					=			state_dict.pop(f"""{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_weight"""  )
              lowercase__    :	str     					=			state_dict.pop(f"""{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_bias"""  )
              # next, add query, keys and values (in that order) to the state dict
              lowercase__    :	Optional[int]     					=			in_proj_weight[:256, :]
              lowercase__    :	Tuple     					=			in_proj_bias[:256]
              lowercase__    :	Union[str, Any]     					=			in_proj_weight[256:512, :]
              lowercase__    :	int     					=			in_proj_bias[256:512]
              lowercase__    :	List[str]     					=			in_proj_weight[-256:, :]
              lowercase__    :	Optional[Any]     					=			in_proj_bias[-256:]
              # read in weights + bias of input projection layer of cross-attention
              lowercase__    :	Dict     					=			state_dict.pop(
                  f"""{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_weight"""  )
              lowercase__    :	Any     					=			state_dict.pop(f"""{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_bias"""  )
              # next, add query, keys and values (in that order) of cross-attention to the state dict
              lowercase__    :	Union[str, Any]     					=			in_proj_weight_cross_attn[:256, :]
              lowercase__    :	int     					=			in_proj_bias_cross_attn[:256]
              lowercase__    :	Tuple     					=			in_proj_weight_cross_attn[256:512, :]
              lowercase__    :	List[Any]     					=			in_proj_bias_cross_attn[256:512]
              lowercase__    :	Union[str, Any]     					=			in_proj_weight_cross_attn[-256:, :]
              lowercase__    :	Any     					=			in_proj_bias_cross_attn[-256:]





def        a_  (   ):





       '''simple docstring'''

       lowercase__    :	Tuple     					=			'''http://images.cocodataset.org/val2017/000000039769.jpg'''
       lowercase__    :	Dict     					=			Image.open(requests.get(_lowercase     ,				stream=_lowercase  ).raw  )

       return im





@torch.no_grad()
def        a_  (   _lowerCAmelCase						:				Optional[int]     ,				_lowerCAmelCase						:				Optional[int]=None     ,				_lowerCAmelCase						:				Optional[int]=False  ):





       '''simple docstring'''

       lowercase__    :	str     					=			get_detr_config(_lowercase  )

       # load original model from torch hub
       lowercase__    :	Optional[int]     					=			{
           '''detr-resnet-50''': '''detr_resnet50''',
           '''detr-resnet-101''': '''detr_resnet101''',
       }
       logger.info(f"""Converting model {model_name}..."""  )
       lowercase__    :	str     					=			torch.hub.load('facebookresearch/detr'     ,				model_name_to_original_name[model_name]     ,				pretrained=_lowercase  ).eval()
       lowercase__    :	int     					=			detr.state_dict()
       # rename keys
       for src, dest in create_rename_keys(_lowercase  ):
              if is_panoptic:
                     lowercase__    :	List[str]     					=			'''detr.''' + src
              rename_key(_lowercase     ,				_lowercase     ,				_lowercase  )
       # query, key and value matrices need special treatment
       read_in_q_k_v(_lowercase     ,				is_panoptic=_lowercase  )
       # important: we need to prepend a prefix to each of the base model keys as the head models use different attributes for them
       lowercase__    :	Optional[Any]     					=			'''detr.model.''' if is_panoptic else '''model.'''
       for key in state_dict.copy().keys():
              if is_panoptic:
                     if (
                         key.startswith('detr'  )
                         and not key.startswith('class_labels_classifier'  )
                         and not key.startswith('bbox_predictor'  )
                     ):
                            lowercase__    :	str     					=			state_dict.pop(_lowercase  )
                            lowercase__    :	Any     					=			val
                     elif "class_labels_classifier" in key or "bbox_predictor" in key:
                            lowercase__    :	Optional[Any]     					=			state_dict.pop(_lowercase  )
                            lowercase__    :	Optional[int]     					=			val
                     elif key.startswith('bbox_attention'  ) or key.startswith('mask_head'  ):
                            continue
                     else:
                            lowercase__    :	Optional[Any]     					=			state_dict.pop(_lowercase  )
                            lowercase__    :	Union[str, Any]     					=			val
              else:
                     if not key.startswith('class_labels_classifier'  ) and not key.startswith('bbox_predictor'  ):
                            lowercase__    :	Optional[Any]     					=			state_dict.pop(_lowercase  )
                            lowercase__    :	List[str]     					=			val

    # finally, create HuggingFace model and load state dict
       lowercase__    :	List[str]     					=			DetrForSegmentation(_lowercase  ) if is_panoptic else DetrForObjectDetection(_lowercase  )
       model.load_state_dict(_lowercase  )
       model.eval()

       # verify our conversion on an image
       lowercase__    :	List[Any]     					=			'''coco_panoptic''' if is_panoptic else '''coco_detection'''
       lowercase__    :	List[str]     					=			DetrImageProcessor(format=_lowercase  )

       lowercase__    :	List[str]     					=			processor(images=prepare_img()     ,				return_tensors='pt'  )
       lowercase__    :	Optional[int]     					=			encoding['''pixel_values''']

       lowercase__    :	List[str]     					=			detr(_lowercase  )
       lowercase__    :	List[Any]     					=			model(_lowercase  )

       assert torch.allclose(outputs.logits     ,				original_outputs['pred_logits']     ,				atol=1E-3  )
       assert torch.allclose(outputs.pred_boxes     ,				original_outputs['pred_boxes']     ,				atol=1E-3  )
       if is_panoptic:
              assert torch.allclose(outputs.pred_masks     ,				original_outputs['pred_masks']     ,				atol=1E-4  )
       print('Looks ok!'  )

       if pytorch_dump_folder_path is not None:
              # Save model and image processor
              logger.info(f"""Saving PyTorch model and image processor to {pytorch_dump_folder_path}..."""  )
              Path(_lowercase  ).mkdir(exist_ok=_lowercase  )
              model.save_pretrained(_lowercase  )
              processor.save_pretrained(_lowercase  )

       if push_to_hub:
              # Upload model and image processor to the hub
              logger.info('Uploading PyTorch model and image processor to the hub...'  )
              model.push_to_hub(f"""nielsr/{model_name}"""  )
              processor.push_to_hub(f"""nielsr/{model_name}"""  )


if __name__ == "__main__":
       _UpperCamelCase     :		List[Any]											=					argparse.ArgumentParser()

       parser.add_argument(
           "--model_name",
           default="detr-resnet-50",
           type=str,
           choices=["detr-resnet-50", "detr-resnet-101"],
           help="Name of the DETR 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 to push the model to the hub or not.")
       _UpperCamelCase     :		List[str]											=					parser.parse_args()
       convert_detr_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)


"""simple docstring"""





import os
import tempfile
import unittest

from transformers import DistilBertConfig, is_torch_available
from transformers.testing_utils import require_torch, require_torch_gpu, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
       import torch

       from transformers import (
           DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
           DistilBertForMaskedLM,
           DistilBertForMultipleChoice,
           DistilBertForQuestionAnswering,
           DistilBertForSequenceClassification,
           DistilBertForTokenClassification,
           DistilBertModel,
       )


class   UpperCAmelCase_			(					_a):


      def __init__(     self	,    a	,    a=1_3	,    a=7	,    a=True	,    a=True	,    a=False	,    a=True	,    a=9_9	,    a=3_2	,    a=5	,    a=4	,    a=3_7	,    a="gelu"	,    a=0.1	,    a=0.1	,    a=5_1_2	,    a=1_6	,    a=2	,    a=0.02	,    a=3	,    a=4	,    a=None	,    ) ->      Any:
             lowercase__    :	Tuple     					=			parent
             lowercase__    :	List[Any]     					=			batch_size
             lowercase__    :	List[Any]     					=			seq_length
             lowercase__    :	List[Any]     					=			is_training
             lowercase__    :	Optional[Any]     					=			use_input_mask
             lowercase__    :	Optional[int]     					=			use_token_type_ids
             lowercase__    :	int     					=			use_labels
             lowercase__    :	Tuple     					=			vocab_size
             lowercase__    :	int     					=			hidden_size
             lowercase__    :	Any     					=			num_hidden_layers
             lowercase__    :	List[str]     					=			num_attention_heads
             lowercase__    :	Optional[Any]     					=			intermediate_size
             lowercase__    :	Optional[Any]     					=			hidden_act
             lowercase__    :	List[str]     					=			hidden_dropout_prob
             lowercase__    :	List[Any]     					=			attention_probs_dropout_prob
             lowercase__    :	List[Any]     					=			max_position_embeddings
             lowercase__    :	List[str]     					=			type_vocab_size
             lowercase__    :	Tuple     					=			type_sequence_label_size
             lowercase__    :	List[Any]     					=			initializer_range
             lowercase__    :	str     					=			num_labels
             lowercase__    :	Tuple     					=			num_choices
             lowercase__    :	str     					=			scope


      def 	_UpperCAmelCase (     self							) ->      Any:
             lowercase__    :	List[Any]     					=			ids_tensor([self.batch_size, self.seq_length]	,    self.vocab_size							)

             lowercase__    :	str     					=			None
             if self.use_input_mask:
                    lowercase__    :	Any     					=			random_attention_mask([self.batch_size, self.seq_length]							)

             lowercase__    :	Dict     					=			None
             lowercase__    :	Optional[Any]     					=			None
             lowercase__    :	int     					=			None
             if self.use_labels:
                    lowercase__    :	Union[str, Any]     					=			ids_tensor([self.batch_size]	,    self.type_sequence_label_size							)
                    lowercase__    :	List[Any]     					=			ids_tensor([self.batch_size, self.seq_length]	,    self.num_labels							)
                    lowercase__    :	Dict     					=			ids_tensor([self.batch_size]	,    self.num_choices							)

             lowercase__    :	List[Any]     					=			self.get_config()

             return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels


      def 	_UpperCAmelCase (     self							) ->      Optional[int]:
             return DistilBertConfig(
                 vocab_size=self.vocab_size	,    dim=self.hidden_size	,    n_layers=self.num_hidden_layers	,    n_heads=self.num_attention_heads	,    hidden_dim=self.intermediate_size	,    hidden_act=self.hidden_act	,    dropout=self.hidden_dropout_prob	,    attention_dropout=self.attention_probs_dropout_prob	,    max_position_embeddings=self.max_position_embeddings	,    initializer_range=self.initializer_range	,    )


      def 	_UpperCAmelCase (     self	,    a	,    a	,    a	,    a	,    a	,    a							) ->      Dict:
             lowercase__    :	Tuple     					=			DistilBertModel(config=a							)
             model.to(a							)
             model.eval()
             lowercase__    :	Any     					=			model(a	,    a							)
             lowercase__    :	str     					=			model(a							)
             self.parent.assertEqual(result.last_hidden_state.shape	,    (self.batch_size, self.seq_length, self.hidden_size)							)


      def 	_UpperCAmelCase (     self	,    a	,    a	,    a	,    a	,    a	,    a							) ->      Dict:
             lowercase__    :	Optional[int]     					=			DistilBertForMaskedLM(config=a							)
             model.to(a							)
             model.eval()
             lowercase__    :	Union[str, Any]     					=			model(a	,    attention_mask=a	,    labels=a							)
             self.parent.assertEqual(result.logits.shape	,    (self.batch_size, self.seq_length, self.vocab_size)							)


      def 	_UpperCAmelCase (     self	,    a	,    a	,    a	,    a	,    a	,    a							) ->      int:
             lowercase__    :	Tuple     					=			DistilBertForQuestionAnswering(config=a							)
             model.to(a							)
             model.eval()
             lowercase__    :	Tuple     					=			model(
                 a	,    attention_mask=a	,    start_positions=a	,    end_positions=a							)
             self.parent.assertEqual(result.start_logits.shape	,    (self.batch_size, self.seq_length)							)
             self.parent.assertEqual(result.end_logits.shape	,    (self.batch_size, self.seq_length)							)


      def 	_UpperCAmelCase (     self	,    a	,    a	,    a	,    a	,    a	,    a							) ->      List[str]:
             lowercase__    :	int     					=			self.num_labels
             lowercase__    :	Dict     					=			DistilBertForSequenceClassification(a							)
             model.to(a							)
             model.eval()
             lowercase__    :	Optional[Any]     					=			model(a	,    attention_mask=a	,    labels=a							)
             self.parent.assertEqual(result.logits.shape	,    (self.batch_size, self.num_labels)							)


      def 	_UpperCAmelCase (     self	,    a	,    a	,    a	,    a	,    a	,    a							) ->      Any:
             lowercase__    :	Any     					=			self.num_labels
             lowercase__    :	List[str]     					=			DistilBertForTokenClassification(config=a							)
             model.to(a							)
             model.eval()

             lowercase__    :	Any     					=			model(a	,    attention_mask=a	,    labels=a							)
             self.parent.assertEqual(result.logits.shape	,    (self.batch_size, self.seq_length, self.num_labels)							)


      def 	_UpperCAmelCase (     self	,    a	,    a	,    a	,    a	,    a	,    a							) ->      Tuple:
             lowercase__    :	List[Any]     					=			self.num_choices
             lowercase__    :	Any     					=			DistilBertForMultipleChoice(config=a							)
             model.to(a							)
             model.eval()
             lowercase__    :	str     					=			input_ids.unsqueeze(1							).expand(-1	,    self.num_choices	,    -1							).contiguous()
             lowercase__    :	Optional[int]     					=			input_mask.unsqueeze(1							).expand(-1	,    self.num_choices	,    -1							).contiguous()
             lowercase__    :	int     					=			model(
                 a	,    attention_mask=a	,    labels=a	,    )
             self.parent.assertEqual(result.logits.shape	,    (self.batch_size, self.num_choices)							)


      def 	_UpperCAmelCase (     self							) ->      str:
             lowercase__    :	Union[str, Any]     					=			self.prepare_config_and_inputs()
             ((lowercase__)					,   (lowercase__)					,   (lowercase__)					,   (lowercase__)					,   (lowercase__)					,   (lowercase__))    :	List[str]     					=			config_and_inputs
             lowercase__    :	Optional[Any]     					=			{'input_ids': input_ids, 'attention_mask': input_mask}
             return config, inputs_dict





@require_torch
class   UpperCAmelCase_			(					_a				,							_a				,							unittest.TestCase):
      lowerCamelCase__	:					List[str]										=						(
          (
              DistilBertModel,
              DistilBertForMaskedLM,
              DistilBertForMultipleChoice,
              DistilBertForQuestionAnswering,
              DistilBertForSequenceClassification,
              DistilBertForTokenClassification,
          )
          if is_torch_available()
          else None
      )
      lowerCamelCase__	:					str										=						(
          {
              "feature-extraction": DistilBertModel,
              "fill-mask": DistilBertForMaskedLM,
              "question-answering": DistilBertForQuestionAnswering,
              "text-classification": DistilBertForSequenceClassification,
              "token-classification": DistilBertForTokenClassification,
              "zero-shot": DistilBertForSequenceClassification,
          }
          if is_torch_available()
          else {}
      )
      lowerCamelCase__	:					Optional[int]										=						True
      lowerCamelCase__	:					Any										=						True
      lowerCamelCase__	:					List[Any]										=						True
      lowerCamelCase__	:					Optional[Any]										=						True


      def 	_UpperCAmelCase (     self							) ->      Union[str, Any]:
             lowercase__    :	str     					=			DistilBertModelTester(self							)
             lowercase__    :	int     					=			ConfigTester(self	,    config_class=a	,    dim=3_7							)


      def 	_UpperCAmelCase (     self							) ->      Dict:
             self.config_tester.run_common_tests()


      def 	_UpperCAmelCase (     self							) ->      Optional[Any]:
             lowercase__    :	int     					=			self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_distilbert_model(*a							)


      def 	_UpperCAmelCase (     self							) ->      Any:
             lowercase__    :	int     					=			self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_distilbert_for_masked_lm(*a							)


      def 	_UpperCAmelCase (     self							) ->      Optional[int]:
             lowercase__    :	str     					=			self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_distilbert_for_question_answering(*a							)


      def 	_UpperCAmelCase (     self							) ->      int:
             lowercase__    :	List[str]     					=			self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_distilbert_for_sequence_classification(*a							)


      def 	_UpperCAmelCase (     self							) ->      List[str]:
             lowercase__    :	Dict     					=			self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_distilbert_for_token_classification(*a							)


      def 	_UpperCAmelCase (     self							) ->      str:
             lowercase__    :	Any     					=			self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_distilbert_for_multiple_choice(*a							)


      @slow
      def 	_UpperCAmelCase (     self							) ->      str:
             for model_name in DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                    lowercase__    :	str     					=			DistilBertModel.from_pretrained(a							)
                    self.assertIsNotNone(a							)


      @slow
      @require_torch_gpu
      def 	_UpperCAmelCase (     self							) ->      Any:
             lowercase__					,   lowercase__    :	Dict     					=			self.model_tester.prepare_config_and_inputs_for_common()
             for model_class in self.all_model_classes:
                    # BertForMultipleChoice behaves incorrectly in JIT environments.
                    if model_class == DistilBertForMultipleChoice:
                           return

                    lowercase__    :	Optional[int]     					=			True
                    lowercase__    :	Union[str, Any]     					=			model_class(config=a							)

                    lowercase__    :	int     					=			self._prepare_for_class(a	,    a							)
                    lowercase__    :	Tuple     					=			torch.jit.trace(
                        a	,    (inputs_dict['input_ids'].to('cpu'							), inputs_dict['attention_mask'].to('cpu'							))							)

                    with tempfile.TemporaryDirectory() as tmp:
                           torch.jit.save(a	,    os.path.join(a	,    'traced_model.pt'							)							)
                           lowercase__    :	Optional[int]     					=			torch.jit.load(os.path.join(a	,    'traced_model.pt'							)	,    map_location=a							)
                           loaded(inputs_dict['input_ids'].to(a							)	,    inputs_dict['attention_mask'].to(a							)							)





@require_torch
class   UpperCAmelCase_			(					unittest.TestCase):


      @slow
      def 	_UpperCAmelCase (     self							) ->      List[str]:
             lowercase__    :	int     					=			DistilBertModel.from_pretrained('distilbert-base-uncased'							)
             lowercase__    :	Union[str, Any]     					=			torch.tensor([[0, 3_4_5, 2_3_2, 3_2_8, 7_4_0, 1_4_0, 1_6_9_5, 6_9, 6_0_7_8, 1_5_8_8, 2]]							)
             lowercase__    :	Optional[Any]     					=			torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]							)
             with torch.no_grad():
                    lowercase__    :	Optional[Any]     					=			model(a	,    attention_mask=a							)[0]
             lowercase__    :	Tuple     					=			torch.Size((1, 1_1, 7_6_8)							)
             self.assertEqual(output.shape	,    a							)
             lowercase__    :	List[Any]     					=			torch.tensor(
                 [[[-0.1_639, 0.3_299, 0.1_648], [-0.1_746, 0.3_289, 0.1_710], [-0.1_884, 0.3_357, 0.1_810]]]							)

             self.assertTrue(torch.allclose(output[:, 1:4, 1:4]	,    a	,    atol=1e-4							)							)

