






'''simple docstring'''



import argparse
import json
from dataclasses import dataclass, field
from functools import partial
from pathlib import Path
from typing import Callable, Dict, List, Tuple

import timm
import torch
import torch.nn as nn
from classy_vision.models.regnet import RegNet, RegNetParams, RegNetYaagf, RegNetYaagf, RegNetYaaagf
from huggingface_hub import cached_download, hf_hub_url
from torch import Tensor
from vissl.models.model_helpers import get_trunk_forward_outputs

from transformers import AutoImageProcessor, RegNetConfig, RegNetForImageClassification, RegNetModel
from transformers.utils import logging


logging.set_verbosity_info()
SCREAMING_SNAKE_CASE						=	logging.get_logger()
@dataclass
class UpperCAmelCase_					:




      """simple docstring"""




      UpperCamelCase_								=			42
      UpperCamelCase_								=			field(default_factory=__A				)
      UpperCamelCase_								=			field(default_factory=__A				)






      def 				A__      ( self			:		Any     ,      UpperCAmelCase			:		Optional[int]     ,      UpperCAmelCase			:		Tensor     ,      UpperCAmelCase			:		Tensor		)  ->  Optional[Any]:


       '''simple docstring'''

       lowercase					:   Any				  =len(list(m.modules()		)		) == 1 or isinstance(UpperCAmelCase     ,      nn.Convad		) or isinstance(UpperCAmelCase     ,      nn.BatchNormad		)
       if has_not_submodules:
        self.traced.append(UpperCAmelCase		)






      def __call__( self			:		Tuple     ,      UpperCAmelCase			:		Tensor		)  ->  int:


       '''simple docstring'''

       for m in self.module.modules():
        self.handles.append(m.register_forward_hook(self._forward_hook		)		)
       self.module(UpperCAmelCase		)
       [x.remove() for x in self.handles]
       return self






      @property
      def 				A__      ( self			:		Dict		)  ->  Optional[Any]:


       '''simple docstring'''

       return list(filter(lambda UpperCAmelCase		: len(list(x.state_dict().keys()		)		) > 0     ,      self.traced		)		)





@dataclass
class UpperCAmelCase_					:




      """simple docstring"""




      UpperCamelCase_								=			42
      UpperCamelCase_								=			42
      UpperCamelCase_								=			1
      UpperCamelCase_								=			field(default_factory=__A				)
      UpperCamelCase_								=			field(default_factory=__A				)
      UpperCamelCase_								=			True






      def __call__( self			:		str     ,      UpperCAmelCase			:		Tensor		)  ->  List[Any]:


       '''simple docstring'''

       lowercase					:   str				  =Tracker(self.dest		)(UpperCAmelCase		).parametrized
       lowercase					:   Optional[int]				  =Tracker(self.src		)(UpperCAmelCase		).parametrized

       lowercase					:   Any				  =list(filter(lambda UpperCAmelCase		: type(UpperCAmelCase		) not in self.src_skip     ,      UpperCAmelCase		)		)
       lowercase					:   List[Any]				  =list(filter(lambda UpperCAmelCase		: type(UpperCAmelCase		) not in self.dest_skip     ,      UpperCAmelCase		)		)

       if len(UpperCAmelCase		) != len(UpperCAmelCase		) and self.raise_if_mismatch:
        raise Exception(
            f'Numbers of operations are different. Source module has {len(UpperCAmelCase		)} operations while'
            f' destination module has {len(UpperCAmelCase		)}.'		)

       for dest_m, src_m in zip(UpperCAmelCase     ,      UpperCAmelCase		):
        dest_m.load_state_dict(src_m.state_dict()		)
        if self.verbose == 1:
         print(f'Transfered from={src_m} to={dest_m}'		)





class UpperCAmelCase_					(    nn.Module				):




      """simple docstring"""




      def __init__( self			:		Optional[Any]     ,      UpperCAmelCase			:		nn.Module		)  ->  str:


       '''simple docstring'''

       super().__init__()

       lowercase					:   List[Tuple[str, nn.Module]]				  =[]
       # - get the stem
       feature_blocks.append(('''conv1''', model.stem)		)
       # - get all the feature blocks
       for k, v in model.trunk_output.named_children():
        assert k.startswith('''block'''		), f'Unexpected layer name {k}'
        lowercase					:   List[Any]				  =len(UpperCAmelCase		) + 1
        feature_blocks.append((f'res{block_index}', v)		)

       lowercase					:   List[Any]				  =nn.ModuleDict(UpperCAmelCase		)






      def 				A__      ( self			:		Tuple     ,      UpperCAmelCase			:		Tensor		)  ->  List[Any]:


       '''simple docstring'''

       return get_trunk_forward_outputs(
           UpperCAmelCase     ,      out_feat_keys=UpperCAmelCase     ,      feature_blocks=self._feature_blocks     ,      )





class UpperCAmelCase_					(    __A				):




      """simple docstring"""




      def 				A__      ( self			:		Union[str, Any]     ,      UpperCAmelCase			:		str		)  ->  str:


       '''simple docstring'''

       lowercase					:   Optional[int]				  =x.split('''-'''		)
       return x_split[0] + x_split[1] + "_" + "".join(x_split[2:]		)






      def __getitem__( self			:		Dict     ,      UpperCAmelCase			:		str		)  ->  Callable[[], Tuple[nn.Module, Dict]]:


       '''simple docstring'''

       if x not in self:
        lowercase					:   List[Any]				  =self.convert_name_to_timm(UpperCAmelCase		)
        lowercase					:   int				  =partial(lambda: (timm.create_model(UpperCAmelCase     ,      pretrained=UpperCAmelCase		).eval(), None)		)

       else:
        lowercase					:   Union[str, Any]				  =super().__getitem__(UpperCAmelCase		)

       return val





class UpperCAmelCase_					(    __A				):




      """simple docstring"""




      def __getitem__( self			:		List[str]     ,      UpperCAmelCase			:		str		)  ->  Callable[[], nn.Module]:


       '''simple docstring'''

       if "seer" in x and "in1k" not in x:
        lowercase					:   Tuple				  =RegNetModel
       else:
        lowercase					:   Any				  =RegNetForImageClassification
       return val





def 							lowercase_				(    __A :       int					,      __A :       List[Any]					,      __A :       List[Tuple[str, str]]			)       ->      List[Any]:



 """simple docstring"""




 for from_key, to_key in keys:
  lowercase					:   str				  =from_state_dict[from_key].clone()
  print(F'Copied key={from_key} to={to_key}'			)
 return to_state_dict


def 							lowercase_				(    __A :       str					,      __A :       Callable[[], nn.Module]					,      __A :       Callable[[], nn.Module]					,      __A :       RegNetConfig					,      __A :       Path					,      __A :       bool = True					,      )       ->      Dict:



 """simple docstring"""




 print(F'Converting {name}...'			)
 with torch.no_grad():
  lowercase  ,		lowercase					:   Optional[Any]				  =from_model_func()
  lowercase					:   str				  =our_model_func(__A			).eval()
  lowercase					:   str				  =ModuleTransfer(src=__A					,      dest=__A					,      raise_if_mismatch=__A			)
  lowercase					:   List[Any]				  =torch.randn((1, 3, 2_2_4, 2_2_4)			)
  module_transfer(__A			)

 if from_state_dict is not None:
  lowercase					:   Union[str, Any]				  =[]
  # for seer - in1k finetuned we have to manually copy the head
  if "seer" in name and "in1k" in name:
   lowercase					:   int				  =[('''0.clf.0.weight''', '''classifier.1.weight'''), ('''0.clf.0.bias''', '''classifier.1.bias''')]
  lowercase					:   str				  =manually_copy_vissl_head(__A					,      our_model.state_dict()					,      __A			)
  our_model.load_state_dict(__A			)

 lowercase					:   int				  =our_model(__A					,      output_hidden_states=__A			)
 lowercase					:   Dict				  =(
     our_outputs.logits if isinstance(__A					,      __A			) else our_outputs.last_hidden_state
 )

 lowercase					:   Optional[int]				  =from_model(__A			)
 lowercase					:   Union[str, Any]				  =from_output[-1] if type(__A			) is list else from_output

 # now since I don't want to use any config files, vissl seer model doesn't actually have an head, so let's just check the last hidden state
 if "seer" in name and "in1k" in name:
  lowercase					:   Union[str, Any]				  =our_outputs.hidden_states[-1]

 assert torch.allclose(__A					,      __A			), "The model logits don't match the original one."

 if push_to_hub:
  our_model.push_to_hub(
      repo_path_or_name=save_directory / name					,      commit_message='''Add model'''					,      use_temp_dir=__A					,      )

  lowercase					:   Optional[int]				  =2_2_4 if '''seer''' not in name else 3_8_4
  # we can use the convnext one
  lowercase					:   Tuple				  =AutoImageProcessor.from_pretrained('''facebook/convnext-base-224-22k-1k'''					,      size=__A			)
  image_processor.push_to_hub(
      repo_path_or_name=save_directory / name					,      commit_message='''Add image processor'''					,      use_temp_dir=__A					,      )

  print(F'Pushed {name}'			)


def 							lowercase_				(    __A :       Path					,      __A :       str = None					,      __A :       bool = True			)       ->      Optional[Any]:



 """simple docstring"""




 lowercase					:   str				  ='''imagenet-1k-id2label.json'''
 lowercase					:   int				  =1_0_0_0
 lowercase					:   str				  =(1, num_labels)

 lowercase					:   List[str]				  ='''huggingface/label-files'''
 lowercase					:   Optional[int]				  =num_labels
 lowercase					:   int				  =json.load(open(cached_download(hf_hub_url(__A					,      __A					,      repo_type='''dataset'''			)			)					,      '''r'''			)			)
 lowercase					:   List[Any]				  ={int(__A			): v for k, v in idalabel.items()}

 lowercase					:   Optional[Any]				  =idalabel
 lowercase					:   Optional[int]				  ={v: k for k, v in idalabel.items()}

 lowercase					:   Any				  =partial(__A					,      num_labels=__A					,      idalabel=__A					,      labelaid=__A			)

 lowercase					:   Optional[Any]				  ={
     '''regnet-x-002''': ImageNetPreTrainedConfig(
         depths=[1, 1, 4, 7]					,      hidden_sizes=[2_4, 5_6, 1_5_2, 3_6_8]					,      groups_width=8					,      layer_type='''x'''			),
     '''regnet-x-004''': ImageNetPreTrainedConfig(
         depths=[1, 2, 7, 1_2]					,      hidden_sizes=[3_2, 6_4, 1_6_0, 3_8_4]					,      groups_width=1_6					,      layer_type='''x'''			),
     '''regnet-x-006''': ImageNetPreTrainedConfig(
         depths=[1, 3, 5, 7]					,      hidden_sizes=[4_8, 9_6, 2_4_0, 5_2_8]					,      groups_width=2_4					,      layer_type='''x'''			),
     '''regnet-x-008''': ImageNetPreTrainedConfig(
         depths=[1, 3, 7, 5]					,      hidden_sizes=[6_4, 1_2_8, 2_8_8, 6_7_2]					,      groups_width=1_6					,      layer_type='''x'''			),
     '''regnet-x-016''': ImageNetPreTrainedConfig(
         depths=[2, 4, 1_0, 2]					,      hidden_sizes=[7_2, 1_6_8, 4_0_8, 9_1_2]					,      groups_width=2_4					,      layer_type='''x'''			),
     '''regnet-x-032''': ImageNetPreTrainedConfig(
         depths=[2, 6, 1_5, 2]					,      hidden_sizes=[9_6, 1_9_2, 4_3_2, 1_0_0_8]					,      groups_width=4_8					,      layer_type='''x'''			),
     '''regnet-x-040''': ImageNetPreTrainedConfig(
         depths=[2, 5, 1_4, 2]					,      hidden_sizes=[8_0, 2_4_0, 5_6_0, 1_3_6_0]					,      groups_width=4_0					,      layer_type='''x'''			),
     '''regnet-x-064''': ImageNetPreTrainedConfig(
         depths=[2, 4, 1_0, 1]					,      hidden_sizes=[1_6_8, 3_9_2, 7_8_4, 1_6_2_4]					,      groups_width=5_6					,      layer_type='''x'''			),
     '''regnet-x-080''': ImageNetPreTrainedConfig(
         depths=[2, 5, 1_5, 1]					,      hidden_sizes=[8_0, 2_4_0, 7_2_0, 1_9_2_0]					,      groups_width=1_2_0					,      layer_type='''x'''			),
     '''regnet-x-120''': ImageNetPreTrainedConfig(
         depths=[2, 5, 1_1, 1]					,      hidden_sizes=[2_2_4, 4_4_8, 8_9_6, 2_2_4_0]					,      groups_width=1_1_2					,      layer_type='''x'''			),
     '''regnet-x-160''': ImageNetPreTrainedConfig(
         depths=[2, 6, 1_3, 1]					,      hidden_sizes=[2_5_6, 5_1_2, 8_9_6, 2_0_4_8]					,      groups_width=1_2_8					,      layer_type='''x'''			),
     '''regnet-x-320''': ImageNetPreTrainedConfig(
         depths=[2, 7, 1_3, 1]					,      hidden_sizes=[3_3_6, 6_7_2, 1_3_4_4, 2_5_2_0]					,      groups_width=1_6_8					,      layer_type='''x'''			),
     # y variant
     '''regnet-y-002''': ImageNetPreTrainedConfig(depths=[1, 1, 4, 7]					,      hidden_sizes=[2_4, 5_6, 1_5_2, 3_6_8]					,      groups_width=8			),
     '''regnet-y-004''': ImageNetPreTrainedConfig(
         depths=[1, 3, 6, 6]					,      hidden_sizes=[4_8, 1_0_4, 2_0_8, 4_4_0]					,      groups_width=8			),
     '''regnet-y-006''': ImageNetPreTrainedConfig(
         depths=[1, 3, 7, 4]					,      hidden_sizes=[4_8, 1_1_2, 2_5_6, 6_0_8]					,      groups_width=1_6			),
     '''regnet-y-008''': ImageNetPreTrainedConfig(
         depths=[1, 3, 8, 2]					,      hidden_sizes=[6_4, 1_2_8, 3_2_0, 7_6_8]					,      groups_width=1_6			),
     '''regnet-y-016''': ImageNetPreTrainedConfig(
         depths=[2, 6, 1_7, 2]					,      hidden_sizes=[4_8, 1_2_0, 3_3_6, 8_8_8]					,      groups_width=2_4			),
     '''regnet-y-032''': ImageNetPreTrainedConfig(
         depths=[2, 5, 1_3, 1]					,      hidden_sizes=[7_2, 2_1_6, 5_7_6, 1_5_1_2]					,      groups_width=2_4			),
     '''regnet-y-040''': ImageNetPreTrainedConfig(
         depths=[2, 6, 1_2, 2]					,      hidden_sizes=[1_2_8, 1_9_2, 5_1_2, 1_0_8_8]					,      groups_width=6_4			),
     '''regnet-y-064''': ImageNetPreTrainedConfig(
         depths=[2, 7, 1_4, 2]					,      hidden_sizes=[1_4_4, 2_8_8, 5_7_6, 1_2_9_6]					,      groups_width=7_2			),
     '''regnet-y-080''': ImageNetPreTrainedConfig(
         depths=[2, 4, 1_0, 1]					,      hidden_sizes=[1_6_8, 4_4_8, 8_9_6, 2_0_1_6]					,      groups_width=5_6			),
     '''regnet-y-120''': ImageNetPreTrainedConfig(
         depths=[2, 5, 1_1, 1]					,      hidden_sizes=[2_2_4, 4_4_8, 8_9_6, 2_2_4_0]					,      groups_width=1_1_2			),
     '''regnet-y-160''': ImageNetPreTrainedConfig(
         depths=[2, 4, 1_1, 1]					,      hidden_sizes=[2_2_4, 4_4_8, 1_2_3_2, 3_0_2_4]					,      groups_width=1_1_2			),
     '''regnet-y-320''': ImageNetPreTrainedConfig(
         depths=[2, 5, 1_2, 1]					,      hidden_sizes=[2_3_2, 6_9_6, 1_3_9_2, 3_7_1_2]					,      groups_width=2_3_2			),
     # models created by SEER -> https://arxiv.org/abs/2202.08360
     '''regnet-y-320-seer''': RegNetConfig(depths=[2, 5, 1_2, 1]					,      hidden_sizes=[2_3_2, 6_9_6, 1_3_9_2, 3_7_1_2]					,      groups_width=2_3_2			),
     '''regnet-y-640-seer''': RegNetConfig(depths=[2, 5, 1_2, 1]					,      hidden_sizes=[3_2_8, 9_8_4, 1_9_6_8, 4_9_2_0]					,      groups_width=3_2_8			),
     '''regnet-y-1280-seer''': RegNetConfig(
         depths=[2, 7, 1_7, 1]					,      hidden_sizes=[5_2_8, 1_0_5_6, 2_9_0_4, 7_3_9_2]					,      groups_width=2_6_4			),
     '''regnet-y-2560-seer''': RegNetConfig(
         depths=[3, 7, 1_6, 1]					,      hidden_sizes=[6_4_0, 1_6_9_6, 2_5_4_4, 5_0_8_8]					,      groups_width=6_4_0			),
     '''regnet-y-10b-seer''': ImageNetPreTrainedConfig(
         depths=[2, 7, 1_7, 1]					,      hidden_sizes=[2_0_2_0, 4_0_4_0, 1_1_1_1_0, 2_8_2_8_0]					,      groups_width=1_0_1_0			),
     # finetuned on imagenet
     '''regnet-y-320-seer-in1k''': ImageNetPreTrainedConfig(
         depths=[2, 5, 1_2, 1]					,      hidden_sizes=[2_3_2, 6_9_6, 1_3_9_2, 3_7_1_2]					,      groups_width=2_3_2			),
     '''regnet-y-640-seer-in1k''': ImageNetPreTrainedConfig(
         depths=[2, 5, 1_2, 1]					,      hidden_sizes=[3_2_8, 9_8_4, 1_9_6_8, 4_9_2_0]					,      groups_width=3_2_8			),
     '''regnet-y-1280-seer-in1k''': ImageNetPreTrainedConfig(
         depths=[2, 7, 1_7, 1]					,      hidden_sizes=[5_2_8, 1_0_5_6, 2_9_0_4, 7_3_9_2]					,      groups_width=2_6_4			),
     '''regnet-y-2560-seer-in1k''': ImageNetPreTrainedConfig(
         depths=[3, 7, 1_6, 1]					,      hidden_sizes=[6_4_0, 1_6_9_6, 2_5_4_4, 5_0_8_8]					,      groups_width=6_4_0			),
     '''regnet-y-10b-seer-in1k''': ImageNetPreTrainedConfig(
         depths=[2, 7, 1_7, 1]					,      hidden_sizes=[2_0_2_0, 4_0_4_0, 1_1_1_1_0, 2_8_2_8_0]					,      groups_width=1_0_1_0			),
 }

 lowercase					:   List[Any]				  =NameToOurModelFuncMap()
 lowercase					:   Any				  =NameToFromModelFuncMap()
 # add seer weights logic

 def load_using_classy_vision(__A :       str					,      __A :       Callable[[], nn.Module]			) -> Tuple[nn.Module, Dict]:
  lowercase					:   Any				  =torch.hub.load_state_dict_from_url(__A					,      model_dir=str(__A			)					,      map_location='''cpu'''			)
  lowercase					:   Dict				  =model_func()
  # check if we have a head, if yes add it
  lowercase					:   int				  =files['''classy_state_dict''']['''base_model''']['''model''']
  lowercase					:   Union[str, Any]				  =model_state_dict['''trunk''']
  model.load_state_dict(__A			)
  return model.eval(), model_state_dict["heads"]

 # pretrained
 lowercase					:   Tuple				  =partial(
     __A					,      '''https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet32d/seer_regnet32gf_model_iteration244000.torch'''					,      lambda: FakeRegNetVisslWrapper(RegNetYaagf()			)					,      )

 lowercase					:   Optional[int]				  =partial(
     __A					,      '''https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet64/seer_regnet64gf_model_final_checkpoint_phase0.torch'''					,      lambda: FakeRegNetVisslWrapper(RegNetYaagf()			)					,      )

 lowercase					:   List[str]				  =partial(
     __A					,      '''https://dl.fbaipublicfiles.com/vissl/model_zoo/swav_ig1b_regnet128Gf_cnstant_bs32_node16_sinkhorn10_proto16k_syncBN64_warmup8k/model_final_checkpoint_phase0.torch'''					,      lambda: FakeRegNetVisslWrapper(RegNetYaaagf()			)					,      )

 lowercase					:   str				  =partial(
     __A					,      '''https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet10B/model_iteration124500_conso.torch'''					,      lambda: FakeRegNetVisslWrapper(
         RegNet(RegNetParams(depth=2_7					,      group_width=1_0_1_0					,      w_a=1_7_4_4					,      w_a=620.83					,      w_m=2.52			)			)			)					,      )

 # IN1K finetuned
 lowercase					:   Dict				  =partial(
     __A					,      '''https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet32_finetuned_in1k_model_final_checkpoint_phase78.torch'''					,      lambda: FakeRegNetVisslWrapper(RegNetYaagf()			)					,      )

 lowercase					:   Any				  =partial(
     __A					,      '''https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet64_finetuned_in1k_model_final_checkpoint_phase78.torch'''					,      lambda: FakeRegNetVisslWrapper(RegNetYaagf()			)					,      )

 lowercase					:   Dict				  =partial(
     __A					,      '''https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet128_finetuned_in1k_model_final_checkpoint_phase78.torch'''					,      lambda: FakeRegNetVisslWrapper(RegNetYaaagf()			)					,      )

 lowercase					:   Optional[int]				  =partial(
     __A					,      '''https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_10b_finetuned_in1k_model_phase28_conso.torch'''					,      lambda: FakeRegNetVisslWrapper(
         RegNet(RegNetParams(depth=2_7					,      group_width=1_0_1_0					,      w_a=1_7_4_4					,      w_a=620.83					,      w_m=2.52			)			)			)					,      )

 if model_name:
  convert_weight_and_push(
      __A					,      names_to_from_model_map[model_name]					,      names_to_ours_model_map[model_name]					,      names_to_config[model_name]					,      __A					,      __A					,      )
 else:
  for model_name, config in names_to_config.items():
   convert_weight_and_push(
       __A					,      names_to_from_model_map[model_name]					,      names_to_ours_model_map[model_name]					,      __A					,      __A					,      __A					,      )
 return config, expected_shape


if __name__ == "__main__":
      SCREAMING_SNAKE_CASE						=	argparse.ArgumentParser()
      # Required parameters
      parser.add_argument(
          '--model_name',
          default=None,
          type=str,
          help=(
              'The name of the model you wish to convert, it must be one of the supported regnet* architecture,'
              ' currently: regnetx-*, regnety-*. If `None`, all of them will the converted.'
          ),
      )
      parser.add_argument(
          '--pytorch_dump_folder_path',
          default=None,
          type=Path,
          required=True,
          help='Path to the output PyTorch model directory.',
      )
      parser.add_argument(
          '--push_to_hub',
          default=True,
          type=bool,
          required=False,
          help='If True, push model and image processor to the hub.',
      )

      SCREAMING_SNAKE_CASE						=	parser.parse_args()

      SCREAMING_SNAKE_CASE						=	args.pytorch_dump_folder_path
      pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True)
      convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)











'''simple docstring'''



from __future__ import annotations

import unittest

from transformers import DistilBertConfig, is_tf_available
from transformers.testing_utils import require_tf, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
      import tensorflow as tf

      from transformers.models.distilbert.modeling_tf_distilbert import (
          TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
          TFDistilBertForMaskedLM,
          TFDistilBertForMultipleChoice,
          TFDistilBertForQuestionAnswering,
          TFDistilBertForSequenceClassification,
          TFDistilBertForTokenClassification,
          TFDistilBertModel,
      )
class UpperCAmelCase_					:




      """simple docstring"""




      def __init__( self			:		Tuple     ,      UpperCAmelCase			:		List[str]     ,      )  ->  Union[str, Any]:


       '''simple docstring'''

       lowercase					:   int				  =parent
       lowercase					:   Any				  =13
       lowercase					:   Any				  =7
       lowercase					:   Optional[int]				  =True
       lowercase					:   Optional[int]				  =True
       lowercase					:   Tuple				  =False
       lowercase					:   Optional[Any]				  =True
       lowercase					:   Dict				  =99
       lowercase					:   Union[str, Any]				  =32
       lowercase					:   Union[str, Any]				  =2
       lowercase					:   Union[str, Any]				  =4
       lowercase					:   List[str]				  =37
       lowercase					:   str				  ='''gelu'''
       lowercase					:   Dict				  =0.1
       lowercase					:   List[Any]				  =0.1
       lowercase					:   List[str]				  =512
       lowercase					:   Optional[int]				  =16
       lowercase					:   Optional[Any]				  =2
       lowercase					:   List[str]				  =0.0_2
       lowercase					:   Any				  =3
       lowercase					:   Optional[Any]				  =4
       lowercase					:   int				  =None






      def 				A__      ( self			:		List[str]		)  ->  Dict:


       '''simple docstring'''

       lowercase					:   Tuple				  =ids_tensor([self.batch_size, self.seq_length]     ,      self.vocab_size		)

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

       lowercase					:   Union[str, Any]				  =None
       lowercase					:   Any				  =None
       lowercase					:   str				  =None
       if self.use_labels:
        lowercase					:   Union[str, Any]				  =ids_tensor([self.batch_size]     ,      self.type_sequence_label_size		)
        lowercase					:   Tuple				  =ids_tensor([self.batch_size, self.seq_length]     ,      self.num_labels		)
        lowercase					:   List[Any]				  =ids_tensor([self.batch_size]     ,      self.num_choices		)

       lowercase					:   Dict				  =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     ,      )

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






      def 				A__      ( self			:		Any     ,      UpperCAmelCase			:		Dict     ,      UpperCAmelCase			:		List[str]     ,      UpperCAmelCase			:		Any     ,      UpperCAmelCase			:		List[str]     ,      UpperCAmelCase			:		Dict     ,      UpperCAmelCase			:		Optional[Any]		)  ->  Union[str, Any]:


       '''simple docstring'''

       lowercase					:   int				  =TFDistilBertModel(config=UpperCAmelCase		)
       lowercase					:   int				  ={'''input_ids''': input_ids, '''attention_mask''': input_mask}

       lowercase					:   List[str]				  =model(UpperCAmelCase		)

       lowercase					:   str				  =[input_ids, input_mask]

       lowercase					:   Tuple				  =model(UpperCAmelCase		)

       self.parent.assertEqual(result.last_hidden_state.shape     ,      (self.batch_size, self.seq_length, self.hidden_size)		)






      def 				A__      ( self			:		List[Any]     ,      UpperCAmelCase			:		Any     ,      UpperCAmelCase			:		int     ,      UpperCAmelCase			:		Dict     ,      UpperCAmelCase			:		List[str]     ,      UpperCAmelCase			:		List[str]     ,      UpperCAmelCase			:		Optional[Any]		)  ->  Tuple:


       '''simple docstring'''

       lowercase					:   List[str]				  =TFDistilBertForMaskedLM(config=UpperCAmelCase		)
       lowercase					:   int				  ={'''input_ids''': input_ids, '''attention_mask''': input_mask}
       lowercase					:   Union[str, Any]				  =model(UpperCAmelCase		)
       self.parent.assertEqual(result.logits.shape     ,      (self.batch_size, self.seq_length, self.vocab_size)		)






      def 				A__      ( self			:		List[Any]     ,      UpperCAmelCase			:		int     ,      UpperCAmelCase			:		Union[str, Any]     ,      UpperCAmelCase			:		Union[str, Any]     ,      UpperCAmelCase			:		Union[str, Any]     ,      UpperCAmelCase			:		List[Any]     ,      UpperCAmelCase			:		Optional[int]		)  ->  Any:


       '''simple docstring'''

       lowercase					:   str				  =TFDistilBertForQuestionAnswering(config=UpperCAmelCase		)
       lowercase					:   int				  ={
           '''input_ids''': input_ids,
           '''attention_mask''': input_mask,
       }
       lowercase					:   List[str]				  =model(UpperCAmelCase		)
       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 				A__      ( self			:		str     ,      UpperCAmelCase			:		int     ,      UpperCAmelCase			:		List[str]     ,      UpperCAmelCase			:		List[Any]     ,      UpperCAmelCase			:		Tuple     ,      UpperCAmelCase			:		Optional[Any]     ,      UpperCAmelCase			:		Dict		)  ->  Optional[int]:


       '''simple docstring'''

       lowercase					:   Dict				  =self.num_labels
       lowercase					:   Optional[Any]				  =TFDistilBertForSequenceClassification(UpperCAmelCase		)
       lowercase					:   str				  ={'''input_ids''': input_ids, '''attention_mask''': input_mask}
       lowercase					:   Union[str, Any]				  =model(UpperCAmelCase		)
       self.parent.assertEqual(result.logits.shape     ,      (self.batch_size, self.num_labels)		)






      def 				A__      ( self			:		int     ,      UpperCAmelCase			:		str     ,      UpperCAmelCase			:		str     ,      UpperCAmelCase			:		Any     ,      UpperCAmelCase			:		str     ,      UpperCAmelCase			:		int     ,      UpperCAmelCase			:		Dict		)  ->  List[str]:


       '''simple docstring'''

       lowercase					:   List[Any]				  =self.num_choices
       lowercase					:   Optional[int]				  =TFDistilBertForMultipleChoice(UpperCAmelCase		)
       lowercase					:   Optional[Any]				  =tf.tile(tf.expand_dims(UpperCAmelCase     ,      1		)     ,      (1, self.num_choices, 1)		)
       lowercase					:   List[Any]				  =tf.tile(tf.expand_dims(UpperCAmelCase     ,      1		)     ,      (1, self.num_choices, 1)		)
       lowercase					:   Tuple				  ={
           '''input_ids''': multiple_choice_inputs_ids,
           '''attention_mask''': multiple_choice_input_mask,
       }
       lowercase					:   Tuple				  =model(UpperCAmelCase		)
       self.parent.assertEqual(result.logits.shape     ,      (self.batch_size, self.num_choices)		)






      def 				A__      ( self			:		List[Any]     ,      UpperCAmelCase			:		Optional[Any]     ,      UpperCAmelCase			:		Tuple     ,      UpperCAmelCase			:		Optional[Any]     ,      UpperCAmelCase			:		Dict     ,      UpperCAmelCase			:		List[Any]     ,      UpperCAmelCase			:		Union[str, Any]		)  ->  Dict:


       '''simple docstring'''

       lowercase					:   Dict				  =self.num_labels
       lowercase					:   Tuple				  =TFDistilBertForTokenClassification(UpperCAmelCase		)
       lowercase					:   Optional[Any]				  ={'''input_ids''': input_ids, '''attention_mask''': input_mask}
       lowercase					:   str				  =model(UpperCAmelCase		)
       self.parent.assertEqual(result.logits.shape     ,      (self.batch_size, self.seq_length, self.num_labels)		)






      def 				A__      ( self			:		List[str]		)  ->  Dict:


       '''simple docstring'''

       lowercase					:   int				  =self.prepare_config_and_inputs()
       ((lowercase)  ,		(lowercase)  ,		(lowercase)  ,		(lowercase)  ,		(lowercase)  ,		(lowercase))					:   Union[str, Any]				  =config_and_inputs
       lowercase					:   Tuple				  ={'''input_ids''': input_ids, '''attention_mask''': input_mask}
       return config, inputs_dict





@require_tf
class UpperCAmelCase_					(    __A				,       __A				,       unittest.TestCase				):




      """simple docstring"""




      UpperCamelCase_								=			(
          (
              TFDistilBertModel,
              TFDistilBertForMaskedLM,
              TFDistilBertForQuestionAnswering,
              TFDistilBertForSequenceClassification,
              TFDistilBertForTokenClassification,
              TFDistilBertForMultipleChoice,
          )
          if is_tf_available()
          else None
      )
      UpperCamelCase_								=			(
          {
              '''feature-extraction''': TFDistilBertModel,
              '''fill-mask''': TFDistilBertForMaskedLM,
              '''question-answering''': TFDistilBertForQuestionAnswering,
              '''text-classification''': TFDistilBertForSequenceClassification,
              '''token-classification''': TFDistilBertForTokenClassification,
              '''zero-shot''': TFDistilBertForSequenceClassification,
          }
          if is_tf_available()
          else {}
      )
      UpperCamelCase_								=			False
      UpperCamelCase_								=			False






      def 				A__      ( self			:		Dict		)  ->  str:


       '''simple docstring'''

       lowercase					:   str				  =TFDistilBertModelTester(self		)
       lowercase					:   int				  =ConfigTester(self     ,      config_class=UpperCAmelCase     ,      dim=37		)






      def 				A__      ( self			:		Union[str, Any]		)  ->  Dict:


       '''simple docstring'''

       self.config_tester.run_common_tests()






      def 				A__      ( self			:		Optional[Any]		)  ->  Tuple:


       '''simple docstring'''

       lowercase					:   List[Any]				  =self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_distilbert_model(*UpperCAmelCase		)






      def 				A__      ( self			:		Tuple		)  ->  Any:


       '''simple docstring'''

       lowercase					:   str				  =self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_distilbert_for_masked_lm(*UpperCAmelCase		)






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


       '''simple docstring'''

       lowercase					:   Any				  =self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_distilbert_for_question_answering(*UpperCAmelCase		)






      def 				A__      ( self			:		Any		)  ->  str:


       '''simple docstring'''

       lowercase					:   List[Any]				  =self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_distilbert_for_sequence_classification(*UpperCAmelCase		)






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


       '''simple docstring'''

       lowercase					:   str				  =self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_distilbert_for_multiple_choice(*UpperCAmelCase		)






      def 				A__      ( self			:		str		)  ->  Union[str, Any]:


       '''simple docstring'''

       lowercase					:   str				  =self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_distilbert_for_token_classification(*UpperCAmelCase		)






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


       '''simple docstring'''

       for model_name in list(TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]		):
        lowercase					:   Union[str, Any]				  =TFDistilBertModel.from_pretrained(UpperCAmelCase		)
        self.assertIsNotNone(UpperCAmelCase		)





@require_tf
class UpperCAmelCase_					(    unittest.TestCase				):




      """simple docstring"""




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


       '''simple docstring'''

       lowercase					:   Optional[Any]				  =TFDistilBertModel.from_pretrained('''distilbert-base-uncased'''		)
       lowercase					:   Tuple				  =tf.constant([[0, 1, 2, 3, 4, 5]]		)
       lowercase					:   List[Any]				  =model(UpperCAmelCase		)[0]

       lowercase					:   str				  =[1, 6, 768]
       self.assertEqual(output.shape     ,      UpperCAmelCase		)

       lowercase					:   Optional[int]				  =tf.constant(
           [
               [
                   [0.1_9_2_6_1_8_8_5, -0.1_3_7_3_2_9_5_5, 0.4_1_1_9_7_9_9],
                   [0.2_2_1_5_0_1_5_6, -0.0_7_4_2_2_6_6_1, 0.3_9_0_3_7_2_0_4],
                   [0.2_2_7_5_6_0_1_8, -0.0_8_9_6_4_1_4, 0.3_7_0_1_4_6_7],
               ]
           ]		)
       tf.debugging.assert_near(output[:, :3, :3]     ,      UpperCAmelCase     ,      atol=1e-4		)



