




'''simple docstring'''





import argparse
import json
import os
import re
from collections import OrderedDict
from dataclasses import dataclass, field
from functools import partial
from pathlib import Path
from pprint import pprint
from typing import Dict, List, Tuple

import torch
import torch.nn as nn
from classy_vision.models.regnet import RegNet, RegNetParams
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.modeling_utils import PreTrainedModel
from transformers.utils import logging


logging.set_verbosity_info()
a		:	Optional[int]       =      logging.get_logger()




@dataclass
class      UpperCamelCase       :
  a     :nn.Module
  a     :List[nn.Module]          =					field(default_factory=snake_case__       )
  a     :list          =					field(default_factory=snake_case__       )
  a     :Dict[str, nn.Module]          =					field(default_factory=snake_case__       )



  def     a_							(			self		,     __lowerCAmelCase		,     __lowerCAmelCase		,     __lowerCAmelCase		,     __lowerCAmelCase ):







      '''simple docstring'''


      _a				:							Optional[Any]							       =      len(list(m.modules() ) ) == 1 or isinstance(__lowerCAmelCase		,     nn.Convad ) or isinstance(__lowerCAmelCase		,     nn.BatchNormad )
      if has_not_submodules:
          self.traced.append(__lowerCAmelCase )
          _a				:							Optional[int]							       =      m



  def __call__(			self		,     __lowerCAmelCase ):







      '''simple docstring'''


      for name, m in self.module.named_modules():
          self.handles.append(m.register_forward_hook(partial(self._forward_hook		,     name=__lowerCAmelCase ) ) )
      self.module(__lowerCAmelCase )
      [x.remove() for x in self.handles]
      return self



  @property
  def     a_							(			self ):







      '''simple docstring'''


      return {k: v for k, v in self.nameamodule.items() if len(list(v.state_dict().keys() ) ) > 0}






class      UpperCamelCase       (	nn.Module       ):



  def __init__(			self		,     __lowerCAmelCase ):







      '''simple docstring'''


      super().__init__()

      _a				:							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}'''
          _a				:							Tuple							       =      len(__lowerCAmelCase ) + 1
          feature_blocks.append((f'''res{block_index}''', v) )

      _a				:							List[str]							       =      nn.ModuleDict(__lowerCAmelCase )



  def     a_							(			self		,     __lowerCAmelCase ):







      '''simple docstring'''


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






class      UpperCamelCase       (	snake_case__       ):



  def     a_							(			self ):







      '''simple docstring'''


      return [(8, 2, 2, 8, 1.0), (8, 2, 7, 8, 1.0), (8, 2, 17, 8, 1.0), (8, 2, 1, 8, 1.0)]






def UpperCAmelCase    (       UpperCAmelCase_						):
    _a				:							Any							       =      RegNetConfig(depths=[2, 7, 17, 1]   ,	hidden_sizes=[8, 8, 8, 8]   ,	groups_width=8						)
    if "in1k" in model_name:
        _a				:							Dict							       =      RegNetForImageClassification(UpperCAmelCase_						)
    else:
        _a				:							str							       =      RegNetModel(UpperCAmelCase_						)
    # create from model (with small weights)
    _a				:							Union[str, Any]							       =      FakeRegNetVisslWrapper(
        RegNet(FakeRegNetParams(depth=27   ,	group_width=1_010   ,	w_a=1_744   ,	w_a=620.83   ,	w_m=2.52						)						)						)

    with torch.no_grad():
        _a				:							Tuple							       =      from_model.eval()
        _a				:							List[str]							       =      our_model.eval()

        _a				:							int							       =      torch.randn((1, 3, 32, 32)						)
        # trace both
        _a				:							Union[str, Any]							       =      Tracker(UpperCAmelCase_						)
        _a				:							Any							       =      dest_tracker(UpperCAmelCase_						).parametrized

        pprint(dest_tracker.nameamodule						)
        _a				:							List[str]							       =      Tracker(UpperCAmelCase_						)
        _a				:							Dict							       =      src_tracker(UpperCAmelCase_						).parametrized

    # convert the keys -> module dict to keys -> params
    def to_params_dict(UpperCAmelCase_						):
        _a				:							List[Any]							       =      OrderedDict()
        for name, module in dict_with_modules.items():
            for param_name, param in module.state_dict().items():
                _a				:							Any							       =      param
        return params_dict

    _a				:							Optional[int]							       =      {}

    _a				:							Optional[Any]							       =      to_params_dict(UpperCAmelCase_						)
    _a				:							Tuple							       =      to_params_dict(UpperCAmelCase_						)

    for (src_key, src_param), (dest_key, dest_param) in zip(src_state_dict.items()   ,	dst_state_dict.items()						):
        _a				:							Dict							       =      dest_key
        logger.info(F'''{src_key} -> {dest_key}'''						)
    # if "in1k" was in the model_name it means it must have a classification head (was finetuned)
    if "in1k" in model_name:
        _a				:							str							       =      """classifier.1.weight"""
        _a				:							str							       =      """classifier.1.bias"""

    return from_to_ours_keys





def UpperCAmelCase    (       UpperCAmelCase_   ,	UpperCAmelCase_ = None   ,	UpperCAmelCase_ = True						):
    _a				:							Union[str, Any]							       =      """imagenet-1k-id2label.json"""
    _a				:							Optional[Any]							       =      1_000

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

    _a				:							Optional[int]							       =      idalabel
    _a				:							List[str]							       =      {v: k for k, v in idalabel.items()}

    _a				:							int							       =      partial(UpperCAmelCase_   ,	num_labels=UpperCAmelCase_   ,	idalabel=UpperCAmelCase_   ,	labelaid=UpperCAmelCase_						)

    _a				:							Any							       =      {
        """regnet-y-10b-seer""": ImageNetPreTrainedConfig(
            depths=[2, 7, 17, 1]   ,	hidden_sizes=[2_020, 4_040, 11_110, 28_280]   ,	groups_width=1_010						),
        # finetuned on imagenet
        """regnet-y-10b-seer-in1k""": ImageNetPreTrainedConfig(
            depths=[2, 7, 17, 1]   ,	hidden_sizes=[2_020, 4_040, 11_110, 28_280]   ,	groups_width=1_010						),
    }

    # add seer weights logic
    def load_using_classy_vision(UpperCAmelCase_						) -> Tuple[Dict, Dict]:
        _a				:							Any							       =      torch.hub.load_state_dict_from_url(UpperCAmelCase_   ,	model_dir=str(UpperCAmelCase_						)   ,	map_location="""cpu"""						)
        # check if we have a head, if yes add it
        _a				:							Optional[int]							       =      files["""classy_state_dict"""]["""base_model"""]["""model"""]
        return model_state_dict["trunk"], model_state_dict["heads"]

    _a				:							Tuple							       =      {
        """regnet-y-10b-seer""": partial(
            UpperCAmelCase_   ,	"""https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet10B/model_iteration124500_conso.torch"""   ,	),
        """regnet-y-10b-seer-in1k""": partial(
            UpperCAmelCase_   ,	"""https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_10b_finetuned_in1k_model_phase28_conso.torch"""   ,	),
    }

    _a				:							Optional[Any]							       =      get_from_to_our_keys(UpperCAmelCase_						)

    if not (save_directory / F'''{model_name}.pth''').exists():
        logger.info("""Loading original state_dict."""						)
        _a       , _a				:							Dict							       =      names_to_from_model[model_name]()
        _a				:							Any							       =      from_state_dict_trunk
        if "in1k" in model_name:
            # add the head
            _a				:							str							       =      {**from_state_dict_trunk, **from_state_dict_head}
        logger.info("""Done!"""						)

        _a				:							List[Any]							       =      {}

        _a				:							int							       =      list(from_state_dict.keys()						)
        _a				:							str							       =      r"""\.block.-part."""
        # this is "interesting", so the original checkpoints have `block[0,1]-part` in each key name, we remove it
        for key in from_state_dict.keys():
            # remove the weird "block[0,1]-part" from the key
            _a				:							str							       =      re.sub(UpperCAmelCase_   ,	""""""   ,	UpperCAmelCase_						)
            # now src_key from the model checkpoints is the one we got from the original model after tracing, so use it to get the correct destination key
            _a				:							int							       =      from_to_ours_keys[src_key]
            # store the parameter with our key
            _a				:							Tuple							       =      from_state_dict[key]
            not_used_keys.remove(UpperCAmelCase_						)
        # check that all keys have been updated
        assert len(UpperCAmelCase_						) == 0, F'''Some keys where not used {','.join(UpperCAmelCase_						)}'''

        logger.info(F'''The following keys were not used: {','.join(UpperCAmelCase_						)}'''						)

        # save our state dict to disk
        torch.save(UpperCAmelCase_   ,	save_directory / F'''{model_name}.pth'''						)

        del converted_state_dict
    else:
        logger.info("""The state_dict was already stored on disk."""						)
    if push_to_hub:
        logger.info(F'''Token is {os.environ['HF_TOKEN']}'''						)
        logger.info("""Loading our model."""						)
        # create our model
        _a				:							Tuple							       =      names_to_config[model_name]
        _a				:							Tuple							       =      RegNetModel
        if "in1k" in model_name:
            _a				:							Tuple							       =      RegNetForImageClassification
        _a				:							Optional[Any]							       =      our_model_func(UpperCAmelCase_						)
        # place our model to the meta device (so remove all the weights)
        our_model.to(torch.device("""meta"""						)						)
        logger.info("""Loading state_dict in our model."""						)
        # load state dict
        _a				:							Optional[Any]							       =      our_model.state_dict().keys()
        PreTrainedModel._load_pretrained_model_low_mem(
            UpperCAmelCase_   ,	UpperCAmelCase_   ,	[save_directory / F'''{model_name}.pth''']						)
        logger.info("""Finally, pushing!"""						)
        # push it to hub
        our_model.push_to_hub(
            repo_path_or_name=save_directory / model_name   ,	commit_message="""Add model"""   ,	output_dir=save_directory / model_name   ,	)
        _a				:							int							       =      384
        # we can use the convnext one
        _a				:							List[str]							       =      AutoImageProcessor.from_pretrained("""facebook/convnext-base-224-22k-1k"""   ,	size=UpperCAmelCase_						)
        image_processor.push_to_hub(
            repo_path_or_name=save_directory / model_name   ,	commit_message="""Add image processor"""   ,	output_dir=save_directory / model_name   ,	)


if __name__ == "__main__":
  a		:	Optional[Any]       =      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.''',
  )

  a		:	Optional[int]       =      parser.parse_args()

  a		:	Path       =      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)








import unittest

from transformers import ElectraConfig, is_torch_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, slow, torch_device

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


if is_torch_available():
  import torch

  from transformers import (
      MODEL_FOR_PRETRAINING_MAPPING,
      ElectraForCausalLM,
      ElectraForMaskedLM,
      ElectraForMultipleChoice,
      ElectraForPreTraining,
      ElectraForQuestionAnswering,
      ElectraForSequenceClassification,
      ElectraForTokenClassification,
      ElectraModel,
  )
  from transformers.models.electra.modeling_electra import ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST
class 							__lowercase   :



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



     def 				__magic_name__		(  self   :							str       ):
       a_		    =  ids_tensor([self.batch_size, self.seq_length]      ,		self.vocab_size       )

       a_		    =  None
       if self.use_input_mask:
         a_		    =  random_attention_mask([self.batch_size, self.seq_length]       )

       a_		    =  None
       if self.use_token_type_ids:
         a_		    =  ids_tensor([self.batch_size, self.seq_length]      ,		self.type_vocab_size       )

       a_		    =  None
       a_		    =  None
       a_		    =  None
       if self.use_labels:
         a_		    =  ids_tensor([self.batch_size]      ,		self.type_sequence_label_size       )
         a_		    =  ids_tensor([self.batch_size, self.seq_length]      ,		self.num_labels       )
         a_		    =  ids_tensor([self.batch_size]      ,		self.num_choices       )
         a_		    =  ids_tensor([self.batch_size, self.seq_length]      ,		1       )

       a_		    =  self.get_config()

       return (
           config,
           input_ids,
           token_type_ids,
           input_mask,
           sequence_labels,
           token_labels,
           choice_labels,
           fake_token_labels,
       )



     def 				__magic_name__		(  self   :							Any       ):
       return ElectraConfig(
           vocab_size=self.vocab_size      ,		hidden_size=self.hidden_size      ,		num_hidden_layers=self.num_hidden_layers      ,		num_attention_heads=self.num_attention_heads      ,		intermediate_size=self.intermediate_size      ,		hidden_act=self.hidden_act      ,		hidden_dropout_prob=self.hidden_dropout_prob      ,		attention_probs_dropout_prob=self.attention_probs_dropout_prob      ,		max_position_embeddings=self.max_position_embeddings      ,		type_vocab_size=self.type_vocab_size      ,		is_decoder=lowercase__      ,		initializer_range=self.initializer_range      ,		)



     def 				__magic_name__		(  self   :							Dict       ):
       (
           (
           a_
       )    , (
           a_
       )    , (
           a_
       )    , (
           a_
       )    , (
           a_
       )    , (
           a_
       )    , (
           a_
       )    , (
           a_
       )    , 
       )		    =  self.prepare_config_and_inputs()

       a_		    =  True
       a_		    =  floats_tensor([self.batch_size, self.seq_length, self.hidden_size]       )
       a_		    =  ids_tensor([self.batch_size, self.seq_length]      ,		vocab_size=2       )

       return (
           config,
           input_ids,
           token_type_ids,
           input_mask,
           sequence_labels,
           token_labels,
           choice_labels,
           encoder_hidden_states,
           encoder_attention_mask,
       )



     def 				__magic_name__		(  self   :							Union[str, Any]      ,		lowercase__   :							Optional[Any]      ,		lowercase__   :							int      ,		lowercase__   :							List[Any]      ,		lowercase__   :							List[Any]      ,		lowercase__   :							str      ,		lowercase__   :							Union[str, Any]      ,		lowercase__   :							str      ,		lowercase__   :							str      ,		):
       a_		    =  ElectraModel(config=lowercase__       )
       model.to(lowercase__       )
       model.eval()
       a_		    =  model(lowercase__      ,		attention_mask=lowercase__      ,		token_type_ids=lowercase__       )
       a_		    =  model(lowercase__      ,		token_type_ids=lowercase__       )
       a_		    =  model(lowercase__       )
       self.parent.assertEqual(result.last_hidden_state.shape      ,		(self.batch_size, self.seq_length, self.hidden_size)       )



     def 				__magic_name__		(  self   :							Optional[int]      ,		lowercase__   :							int      ,		lowercase__   :							Tuple      ,		lowercase__   :							Union[str, Any]      ,		lowercase__   :							Optional[Any]      ,		lowercase__   :							List[str]      ,		lowercase__   :							Optional[Any]      ,		lowercase__   :							Any      ,		lowercase__   :							Dict      ,		lowercase__   :							Optional[Any]      ,		):
       a_		    =  True
       a_		    =  ElectraModel(lowercase__       )
       model.to(lowercase__       )
       model.eval()
       a_		    =  model(
           lowercase__      ,		attention_mask=lowercase__      ,		token_type_ids=lowercase__      ,		encoder_hidden_states=lowercase__      ,		encoder_attention_mask=lowercase__      ,		)
       a_		    =  model(
           lowercase__      ,		attention_mask=lowercase__      ,		token_type_ids=lowercase__      ,		encoder_hidden_states=lowercase__      ,		)
       a_		    =  model(lowercase__      ,		attention_mask=lowercase__      ,		token_type_ids=lowercase__       )
       self.parent.assertEqual(result.last_hidden_state.shape      ,		(self.batch_size, self.seq_length, self.hidden_size)       )



     def 				__magic_name__		(  self   :							str      ,		lowercase__   :							List[Any]      ,		lowercase__   :							Any      ,		lowercase__   :							Union[str, Any]      ,		lowercase__   :							Tuple      ,		lowercase__   :							Union[str, Any]      ,		lowercase__   :							Any      ,		lowercase__   :							Dict      ,		lowercase__   :							Any      ,		):
       a_		    =  ElectraForMaskedLM(config=lowercase__       )
       model.to(lowercase__       )
       model.eval()
       a_		    =  model(lowercase__      ,		attention_mask=lowercase__      ,		token_type_ids=lowercase__      ,		labels=lowercase__       )
       self.parent.assertEqual(result.logits.shape      ,		(self.batch_size, self.seq_length, self.vocab_size)       )



     def 				__magic_name__		(  self   :							Optional[int]      ,		lowercase__   :							Dict      ,		lowercase__   :							Dict      ,		lowercase__   :							Dict      ,		lowercase__   :							str      ,		lowercase__   :							List[Any]      ,		lowercase__   :							List[str]      ,		lowercase__   :							Union[str, Any]      ,		lowercase__   :							int      ,		lowercase__   :							str      ,		):
       a_		    =  ElectraForCausalLM(config=lowercase__       )
       model.to(lowercase__       )
       model.eval()
       a_		    =  model(lowercase__      ,		attention_mask=lowercase__      ,		token_type_ids=lowercase__      ,		labels=lowercase__       )
       self.parent.assertEqual(result.logits.shape      ,		(self.batch_size, self.seq_length, self.vocab_size)       )



     def 				__magic_name__		(  self   :							str      ,		lowercase__   :							Union[str, Any]      ,		lowercase__   :							List[Any]      ,		lowercase__   :							str      ,		lowercase__   :							List[str]      ,		lowercase__   :							Union[str, Any]      ,		lowercase__   :							Dict      ,		lowercase__   :							Dict      ,		lowercase__   :							List[Any]      ,		):
       a_		    =  self.num_labels
       a_		    =  ElectraForTokenClassification(config=lowercase__       )
       model.to(lowercase__       )
       model.eval()
       a_		    =  model(lowercase__      ,		attention_mask=lowercase__      ,		token_type_ids=lowercase__      ,		labels=lowercase__       )
       self.parent.assertEqual(result.logits.shape      ,		(self.batch_size, self.seq_length, self.num_labels)       )



     def 				__magic_name__		(  self   :							Any      ,		lowercase__   :							Any      ,		lowercase__   :							Optional[Any]      ,		lowercase__   :							List[str]      ,		lowercase__   :							Any      ,		lowercase__   :							Dict      ,		lowercase__   :							List[str]      ,		lowercase__   :							List[str]      ,		lowercase__   :							List[str]      ,		):
       a_		    =  self.num_labels
       a_		    =  ElectraForPreTraining(config=lowercase__       )
       model.to(lowercase__       )
       model.eval()
       a_		    =  model(lowercase__      ,		attention_mask=lowercase__      ,		token_type_ids=lowercase__      ,		labels=lowercase__       )
       self.parent.assertEqual(result.logits.shape      ,		(self.batch_size, self.seq_length)       )



     def 				__magic_name__		(  self   :							Optional[int]      ,		lowercase__   :							Dict      ,		lowercase__   :							Tuple      ,		lowercase__   :							Any      ,		lowercase__   :							Any      ,		lowercase__   :							int      ,		lowercase__   :							List[str]      ,		lowercase__   :							Optional[int]      ,		lowercase__   :							int      ,		):
       a_		    =  self.num_labels
       a_		    =  ElectraForSequenceClassification(lowercase__       )
       model.to(lowercase__       )
       model.eval()
       a_		    =  model(lowercase__      ,		attention_mask=lowercase__      ,		token_type_ids=lowercase__      ,		labels=lowercase__       )
       self.parent.assertEqual(result.logits.shape      ,		(self.batch_size, self.num_labels)       )



     def 				__magic_name__		(  self   :							Any      ,		lowercase__   :							Union[str, Any]      ,		lowercase__   :							int      ,		lowercase__   :							Any      ,		lowercase__   :							List[Any]      ,		lowercase__   :							Optional[int]      ,		lowercase__   :							Optional[int]      ,		lowercase__   :							List[str]      ,		lowercase__   :							Optional[Any]      ,		):
       a_		    =  ElectraForQuestionAnswering(config=lowercase__       )
       model.to(lowercase__       )
       model.eval()
       a_		    =  model(
           lowercase__      ,		attention_mask=lowercase__      ,		token_type_ids=lowercase__      ,		start_positions=lowercase__      ,		end_positions=lowercase__      ,		)
       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 				__magic_name__		(  self   :							int      ,		lowercase__   :							List[str]      ,		lowercase__   :							List[Any]      ,		lowercase__   :							Union[str, Any]      ,		lowercase__   :							Tuple      ,		lowercase__   :							List[Any]      ,		lowercase__   :							List[Any]      ,		lowercase__   :							Dict      ,		lowercase__   :							Optional[Any]      ,		):
       a_		    =  self.num_choices
       a_		    =  ElectraForMultipleChoice(config=lowercase__       )
       model.to(lowercase__       )
       model.eval()
       a_		    =  input_ids.unsqueeze(1       ).expand(-1      ,		self.num_choices      ,		-1       ).contiguous()
       a_		    =  token_type_ids.unsqueeze(1       ).expand(-1      ,		self.num_choices      ,		-1       ).contiguous()
       a_		    =  input_mask.unsqueeze(1       ).expand(-1      ,		self.num_choices      ,		-1       ).contiguous()
       a_		    =  model(
           lowercase__      ,		attention_mask=lowercase__      ,		token_type_ids=lowercase__      ,		labels=lowercase__      ,		)
       self.parent.assertEqual(result.logits.shape      ,		(self.batch_size, self.num_choices)       )



     def 				__magic_name__		(  self   :							Tuple       ):
       a_		    =  self.prepare_config_and_inputs()
       (
           (
           a_
       )    , (
           a_
       )    , (
           a_
       )    , (
           a_
       )    , (
           a_
       )    , (
           a_
       )    , (
           a_
       )    , (
           a_
       )    , 
       )		    =  config_and_inputs
       a_		    =  {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask}
       return config, inputs_dict



@require_torch
class 							__lowercase   (			a__	,		a__	,		unittest.TestCase    ):
     _lowerCAmelCase		       =						(
         (
             ElectraModel,
             ElectraForPreTraining,
             ElectraForMaskedLM,
             ElectraForCausalLM,
             ElectraForMultipleChoice,
             ElectraForTokenClassification,
             ElectraForSequenceClassification,
             ElectraForQuestionAnswering,
         )
         if is_torch_available()
         else ()
     )
     _lowerCAmelCase		       =						(
         {
             "feature-extraction": ElectraModel,
             "fill-mask": ElectraForMaskedLM,
             "question-answering": ElectraForQuestionAnswering,
             "text-classification": ElectraForSequenceClassification,
             "text-generation": ElectraForCausalLM,
             "token-classification": ElectraForTokenClassification,
             "zero-shot": ElectraForSequenceClassification,
         }
         if is_torch_available()
         else {}
     )
     _lowerCAmelCase		       =						True



     def 				__magic_name__		(  self   :							Tuple      ,		lowercase__   :							Optional[int]      ,		lowercase__   :							List[Any]      ,		lowercase__   :							Dict=False       ):
       a_		    =  super()._prepare_for_class(lowercase__      ,		lowercase__      ,		return_labels=lowercase__       )

       if return_labels:
         if model_class in get_values(lowercase__       ):
           a_		    =  torch.zeros(
               (self.model_tester.batch_size, self.model_tester.seq_length)      ,		dtype=torch.long      ,		device=lowercase__       )
       return inputs_dict



     def 				__magic_name__		(  self   :							List[str]       ):
       a_		    =  ElectraModelTester(self       )
       a_		    =  ConfigTester(self      ,		config_class=lowercase__      ,		hidden_size=3_7       )



     def 				__magic_name__		(  self   :							str       ):
       self.config_tester.run_common_tests()



     def 				__magic_name__		(  self   :							Any       ):
       a_		    =  self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_electra_model(*lowercase__       )



     def 				__magic_name__		(  self   :							Optional[Any]       ):
       a_		    =  self.model_tester.prepare_config_and_inputs_for_decoder()
       self.model_tester.create_and_check_electra_model_as_decoder(*lowercase__       )



     def 				__magic_name__		(  self   :							int       ):
       a_		    =  self.model_tester.prepare_config_and_inputs()
       for type in ["absolute", "relative_key", "relative_key_query"]:
         a_		    =  type
         self.model_tester.create_and_check_electra_model(*lowercase__       )



     def 				__magic_name__		(  self   :							List[str]       ):
       a_		    =  self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_electra_for_masked_lm(*lowercase__       )



     def 				__magic_name__		(  self   :							Optional[int]       ):
       a_		    =  self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_electra_for_token_classification(*lowercase__       )



     def 				__magic_name__		(  self   :							Optional[Any]       ):
       a_		    =  self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_electra_for_pretraining(*lowercase__       )



     def 				__magic_name__		(  self   :							List[Any]       ):
       a_		    =  self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_electra_for_sequence_classification(*lowercase__       )



     def 				__magic_name__		(  self   :							List[str]       ):
       a_		    =  self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_electra_for_question_answering(*lowercase__       )



     def 				__magic_name__		(  self   :							str       ):
       a_		    =  self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_electra_for_multiple_choice(*lowercase__       )



     @slow
     def 				__magic_name__		(  self   :							Union[str, Any]       ):
       for model_name in ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
         a_		    =  ElectraModel.from_pretrained(lowercase__       )
         self.assertIsNotNone(lowercase__       )



     def 				__magic_name__		(  self   :							Dict       ):
       a_		    =  self.model_tester.prepare_config_and_inputs_for_decoder()
       self.model_tester.create_and_check_electra_for_causal_lm(*lowercase__       )



@require_torch
class 							__lowercase   (			unittest.TestCase    ):



     @slow
     def 				__magic_name__		(  self   :							Tuple       ):
       a_		    =  ElectraModel.from_pretrained('''google/electra-small-discriminator'''       )
       a_		    =  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]]       )
       a_		    =  torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]       )
       a_		    =  model(lowercase__      ,		attention_mask=lowercase__       )[0]
       a_		    =  torch.Size((1, 1_1, 2_5_6)       )
       self.assertEqual(output.shape      ,		lowercase__       )
       a_		    =  torch.tensor(
           [[[0.4471, 0.6821, -0.3265], [0.4627, 0.5255, -0.3668], [0.4532, 0.3313, -0.4344]]]       )

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