



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()
UpperCamelCase_									=   logging.get_logger()







@dataclass
class       _snake_case				:






   '''simple docstring'''






   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:     Union[str, Any]  ,lowerCamelCase_:     Optional[Any]  ,lowerCamelCase_:     Tensor  ,lowerCamelCase_:     Tensor  ,lowerCamelCase_:     str							)	->      Dict:
       UpperCAmelCase_     :       Tuple  		=					len(list(m.modules()							)							) == 1 or isinstance(lowerCamelCase_  ,nn.Convad							) or isinstance(lowerCamelCase_  ,nn.BatchNormad							)
       if has_not_submodules:
           self.traced.append(lowerCamelCase_							)
           UpperCAmelCase_     :       str  		=					m


   def __call__(    self:     Tuple  ,lowerCamelCase_:     Tensor							)	->      List[str]:
       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:     str							)	->      Optional[int]:
       # check the len of the state_dict keys to see if we have learnable params
       return {k: v for k, v in self.nameamodule.items() if len(list(v.state_dict().keys()							)							) > 0}







class       _snake_case				(     nn.Module ):






   '''simple docstring'''






   def __init__(    self:     Optional[int]  ,lowerCamelCase_:     nn.Module							)	->      Any:
       super().__init__()

       UpperCAmelCase_     :       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}'''
           UpperCAmelCase_     :       Dict  		=					len(lowerCamelCase_							) + 1
           feature_blocks.append((F'''res{block_index}''', v)							)

       UpperCAmelCase_     :       Tuple  		=					nn.ModuleDict(lowerCamelCase_							)






   def       A__    (    self:     Optional[int]  ,lowerCamelCase_:     Tensor							)	->      Dict:
       return get_trunk_forward_outputs(
           lowerCamelCase_  ,out_feat_keys=lowerCamelCase_  ,feature_blocks=self._feature_blocks  ,)







class       _snake_case				(     __snake_case ):






   '''simple docstring'''






   def       A__    (    self:     Dict							)	->      Dict:
       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       lowerCamelCase_  (    _a       :						str    ):



    '''simple docstring'''




    UpperCAmelCase_     :       Tuple  		=					RegNetConfig(depths=[2, 7, 17, 1]   ,		hidden_sizes=[8, 8, 8, 8]   ,		groups_width=8    )
    if "in1k" in model_name:
        UpperCAmelCase_     :       Optional[int]  		=					RegNetForImageClassification(_a    )
    else:
        UpperCAmelCase_     :       Optional[Any]  		=					RegNetModel(_a    )
    # create from model (with small weights)
    UpperCAmelCase_     :       Tuple  		=					FakeRegNetVisslWrapper(
        RegNet(FakeRegNetParams(depth=27   ,		group_width=1010   ,		w_a=1744   ,		w_a=6_2_0.8_3   ,		w_m=2.5_2    )    )    )

    with torch.no_grad():
        UpperCAmelCase_     :       int  		=					from_model.eval()
        UpperCAmelCase_     :       List[Any]  		=					our_model.eval()

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

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

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

    UpperCAmelCase_     :       int  		=					{}

    UpperCAmelCase_     :       str  		=					to_params_dict(_a    )
    UpperCAmelCase_     :       Dict  		=					to_params_dict(_a    )

    for (src_key, src_param), (dest_key, dest_param) in zip(src_state_dict.items()   ,		dst_state_dict.items()    ):
        UpperCAmelCase_     :       Union[str, Any]  		=					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:
        UpperCAmelCase_     :       int  		=					"""classifier.1.weight"""
        UpperCAmelCase_     :       Union[str, Any]  		=					"""classifier.1.bias"""

    return from_to_ours_keys







def       lowerCamelCase_  (    _a       :						Path   ,		_a       :						str = None   ,		_a       :						bool = True    ):



    '''simple docstring'''




    UpperCAmelCase_     :       Tuple  		=					"""imagenet-1k-id2label.json"""
    UpperCAmelCase_     :       List[Any]  		=					1000

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

    UpperCAmelCase_     :       List[str]  		=					idalabel
    UpperCAmelCase_     :       List[Any]  		=					{v: k for k, v in idalabel.items()}

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

    UpperCAmelCase_     :       int  		=					{
        """regnet-y-10b-seer""": ImageNetPreTrainedConfig(
            depths=[2, 7, 17, 1]   ,		hidden_sizes=[2020, 4040, 1_1110, 2_8280]   ,		groups_width=1010    ),
        # finetuned on imagenet
        """regnet-y-10b-seer-in1k""": ImageNetPreTrainedConfig(
            depths=[2, 7, 17, 1]   ,		hidden_sizes=[2020, 4040, 1_1110, 2_8280]   ,		groups_width=1010    ),
    }

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

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

    UpperCAmelCase_     :       Union[str, Any]  		=					get_from_to_our_keys(_a    )

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

        UpperCAmelCase_     :       Any  		=					{}

        UpperCAmelCase_     :       List[Any]  		=					list(from_state_dict.keys()    )
        UpperCAmelCase_     :       List[Any]  		=					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
            UpperCAmelCase_     :       Dict  		=					re.sub(_a   ,		""""""   ,		_a    )
            # 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
            UpperCAmelCase_     :       List[str]  		=					from_to_ours_keys[src_key]
            # store the parameter with our key
            UpperCAmelCase_     :       str  		=					from_state_dict[key]
            not_used_keys.remove(_a    )
        # check that all keys have been updated
        assert len(_a    ) == 0, F'''Some keys where not used {','.join(_a    )}'''

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

        # save our state dict to disk
        torch.save(_a   ,		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
        UpperCAmelCase_     :       int  		=					names_to_config[model_name]
        UpperCAmelCase_     :       Dict  		=					RegNetModel
        if "in1k" in model_name:
            UpperCAmelCase_     :       Dict  		=					RegNetForImageClassification
        UpperCAmelCase_     :       List[str]  		=					our_model_func(_a    )
        # 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
        UpperCAmelCase_     :       Any  		=					our_model.state_dict().keys()
        PreTrainedModel._load_pretrained_model_low_mem(
            _a   ,		_a   ,		[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   ,		)
        UpperCAmelCase_     :       int  		=					384
        # we can use the convnext one
        UpperCAmelCase_     :       int  		=					AutoImageProcessor.from_pretrained("""facebook/convnext-base-224-22k-1k"""   ,		size=_a    )
        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__":
      UpperCamelCase_									=   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.''',
      )

      UpperCamelCase_									=   parser.parse_args()

      UpperCamelCase_									=   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"""





import unittest

from transformers import ErnieMConfig, is_torch_available
from transformers.testing_utils import require_torch, 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 (
     ErnieMForInformationExtraction,
     ErnieMForMultipleChoice,
     ErnieMForQuestionAnswering,
     ErnieMForSequenceClassification,
     ErnieMForTokenClassification,
     ErnieMModel,
 )
 from transformers.models.ernie_m.modeling_ernie_m import ERNIE_M_PRETRAINED_MODEL_ARCHIVE_LIST



class 		snake_case_:






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






     def   lowerCamelCase__  (						self	:       Dict					):
           lowerCAmelCase       :						str							= ids_tensor([self.batch_size, self.seq_length]       ,					self.vocab_size					)

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

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

           lowerCAmelCase       :						Any							= self.get_config()

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






     def   lowerCamelCase__  (						self	:       str					):
           lowerCAmelCase       :						Tuple							= ids_tensor([self.batch_size, self.seq_length]       ,					self.vocab_size					)

           lowerCAmelCase       :						Optional[Any]							= None
           if self.use_input_mask:
                 lowerCAmelCase       :						Union[str, Any]							= random_attention_mask([self.batch_size, self.seq_length]					)
           lowerCAmelCase       :						Dict							= self.get_config()

           return config, input_ids, input_mask






     def   lowerCamelCase__  (						self	:       Union[str, Any]					):
           return ErnieMConfig(
               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       ,					initializer_range=self.initializer_range       ,					)






     def   lowerCamelCase__  (						self	:       Union[str, Any]       ,					UpperCamelCase_	:       Tuple       ,					UpperCamelCase_	:       Union[str, Any]       ,					UpperCamelCase_	:       Optional[Any]       ,					UpperCamelCase_	:       Dict       ,					UpperCamelCase_	:       Union[str, Any]       ,					UpperCamelCase_	:       Optional[Any]					):
           lowerCAmelCase       :						List[str]							= ErnieMModel(config=UpperCamelCase_					)
           model.to(UpperCamelCase_					)
           model.eval()
           lowerCAmelCase       :						List[Any]							= model(UpperCamelCase_       ,					return_dict=UpperCamelCase_					)
           self.parent.assertEqual(result.last_hidden_state.shape       ,					(self.batch_size, self.seq_length, self.hidden_size)					)






     def   lowerCamelCase__  (						self	:       Union[str, Any]       ,					UpperCamelCase_	:       Union[str, Any]       ,					UpperCamelCase_	:       Optional[Any]       ,					UpperCamelCase_	:       int       ,					UpperCamelCase_	:       List[Any]       ,					UpperCamelCase_	:       List[Any]       ,					UpperCamelCase_	:       Optional[Any]					):
           lowerCAmelCase       :						Optional[int]							= ErnieMForQuestionAnswering(config=UpperCamelCase_					)
           model.to(UpperCamelCase_					)
           model.eval()
           lowerCAmelCase       :						List[Any]							= model(
               UpperCamelCase_       ,					attention_mask=UpperCamelCase_       ,					start_positions=UpperCamelCase_       ,					end_positions=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   lowerCamelCase__  (						self	:       Dict       ,					UpperCamelCase_	:       Optional[int]       ,					UpperCamelCase_	:       Any       ,					UpperCamelCase_	:       List[str]       ,					UpperCamelCase_	:       Dict       ,					UpperCamelCase_	:       Optional[Any]       ,					UpperCamelCase_	:       Union[str, Any]					):
           lowerCAmelCase       :						Tuple							= ErnieMForInformationExtraction(config=UpperCamelCase_					)
           model.to(UpperCamelCase_					)
           model.eval()
           lowerCAmelCase       :						Tuple							= torch.ones_like(UpperCamelCase_       ,					dtype=torch.floataa					)
           lowerCAmelCase       :						str							= model(
               UpperCamelCase_       ,					attention_mask=UpperCamelCase_       ,					start_positions=UpperCamelCase_       ,					end_positions=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   lowerCamelCase__  (						self	:       Optional[int]       ,					UpperCamelCase_	:       Optional[int]       ,					UpperCamelCase_	:       Dict       ,					UpperCamelCase_	:       int       ,					UpperCamelCase_	:       int       ,					UpperCamelCase_	:       Union[str, Any]       ,					UpperCamelCase_	:       Any					):
           lowerCAmelCase       :						Union[str, Any]							= self.num_labels
           lowerCAmelCase       :						Tuple							= ErnieMForSequenceClassification(UpperCamelCase_					)
           model.to(UpperCamelCase_					)
           model.eval()
           lowerCAmelCase       :						Union[str, Any]							= model(UpperCamelCase_       ,					attention_mask=UpperCamelCase_       ,					labels=UpperCamelCase_					)
           self.parent.assertEqual(result.logits.shape       ,					(self.batch_size, self.num_labels)					)






     def   lowerCamelCase__  (						self	:       Optional[int]       ,					UpperCamelCase_	:       Any       ,					UpperCamelCase_	:       List[str]       ,					UpperCamelCase_	:       int       ,					UpperCamelCase_	:       Dict       ,					UpperCamelCase_	:       str       ,					UpperCamelCase_	:       List[str]					):
           lowerCAmelCase       :						Union[str, Any]							= self.num_labels
           lowerCAmelCase       :						List[Any]							= ErnieMForTokenClassification(config=UpperCamelCase_					)
           model.to(UpperCamelCase_					)
           model.eval()
           input_ids.to(UpperCamelCase_					)
           input_mask.to(UpperCamelCase_					)
           token_labels.to(UpperCamelCase_					)

           lowerCAmelCase       :						Optional[Any]							= model(UpperCamelCase_       ,					attention_mask=UpperCamelCase_       ,					labels=UpperCamelCase_					)

           self.parent.assertEqual(result.logits.shape       ,					(self.batch_size, self.seq_length, self.num_labels)					)






     def   lowerCamelCase__  (						self	:       Any       ,					UpperCamelCase_	:       str       ,					UpperCamelCase_	:       Optional[int]       ,					UpperCamelCase_	:       Tuple       ,					UpperCamelCase_	:       Dict       ,					UpperCamelCase_	:       Dict       ,					UpperCamelCase_	:       str					):
           lowerCAmelCase       :						Union[str, Any]							= self.num_choices
           lowerCAmelCase       :						Any							= ErnieMForMultipleChoice(config=UpperCamelCase_					)
           model.to(UpperCamelCase_					)
           model.eval()
           lowerCAmelCase       :						Any							= input_ids.unsqueeze(1					).expand(-1       ,					self.num_choices       ,					-1					).contiguous()
           lowerCAmelCase       :						int							= input_mask.unsqueeze(1					).expand(-1       ,					self.num_choices       ,					-1					).contiguous()
           lowerCAmelCase       :						Any							= model(
               UpperCamelCase_       ,					attention_mask=UpperCamelCase_       ,					labels=UpperCamelCase_       ,					)
           self.parent.assertEqual(result.logits.shape       ,					(self.batch_size, self.num_choices)					)






     def   lowerCamelCase__  (						self	:       Tuple					):
           lowerCAmelCase       :						List[Any]							= self.prepare_config_and_inputs()
           (
               (
               lowerCAmelCase
           ),   (
               lowerCAmelCase
           ),   (
               lowerCAmelCase
           ),   (
               lowerCAmelCase
           ),   (
               lowerCAmelCase
           ),   (
               lowerCAmelCase
           ),   
           )       :						str							= config_and_inputs
           lowerCAmelCase       :						Dict							= {'''input_ids''': input_ids, '''attention_mask''': input_mask}
           return config, inputs_dict



@require_torch
class 		snake_case_(							a__				,       a__				,       unittest.TestCase      ):
     __UpperCamelCase	=       (
         (
             ErnieMModel,
             ErnieMForMultipleChoice,
             ErnieMForQuestionAnswering,
             ErnieMForSequenceClassification,
             ErnieMForTokenClassification,
         )
         if is_torch_available()
         else ()
     )
     __UpperCamelCase	=       ()
     __UpperCamelCase	=       (
         {
             '''feature-extraction''': ErnieMModel,
             '''question-answering''': ErnieMForQuestionAnswering,
             '''text-classification''': ErnieMForSequenceClassification,
             '''token-classification''': ErnieMForTokenClassification,
             '''zero-shot''': ErnieMForSequenceClassification,
         }
         if is_torch_available()
         else {}
     )
     __UpperCamelCase	=       False






     def   lowerCamelCase__  (						self	:       Optional[Any]       ,					UpperCamelCase_	:       str       ,					UpperCamelCase_	:       List[Any]       ,					UpperCamelCase_	:       Tuple       ,					UpperCamelCase_	:       int       ,					UpperCamelCase_	:       Any					):
           if pipeline_test_casse_name == "QAPipelineTests":
                 return True

           return False






     def   lowerCamelCase__  (						self	:       Dict					):
           lowerCAmelCase       :						str							= ErnieMModelTester(self					)
           lowerCAmelCase       :						Optional[Any]							= ConfigTester(self       ,					config_class=UpperCamelCase_       ,					hidden_size=3_7					)






     def   lowerCamelCase__  (						self	:       Tuple					):
           self.config_tester.run_common_tests()






     def   lowerCamelCase__  (						self	:       List[str]					):
           lowerCAmelCase       :						str							= self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(*UpperCamelCase_					)






     def   lowerCamelCase__  (						self	:       Union[str, Any]					):
           lowerCAmelCase       :						Optional[Any]							= self.model_tester.prepare_config_and_inputs()
           for type in ["absolute", "relative_key", "relative_key_query"]:
                 lowerCAmelCase       :						Union[str, Any]							= type
                 self.model_tester.create_and_check_model(*UpperCamelCase_					)






     def   lowerCamelCase__  (						self	:       Tuple					):
           lowerCAmelCase       :						Dict							= self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_multiple_choice(*UpperCamelCase_					)






     def   lowerCamelCase__  (						self	:       Dict					):
           lowerCAmelCase       :						int							= self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_question_answering(*UpperCamelCase_					)






     def   lowerCamelCase__  (						self	:       Optional[int]					):
           lowerCAmelCase       :						Tuple							= self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_sequence_classification(*UpperCamelCase_					)






     def   lowerCamelCase__  (						self	:       Tuple					):
           lowerCAmelCase       :						List[str]							= self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_information_extraction(*UpperCamelCase_					)






     def   lowerCamelCase__  (						self	:       List[Any]					):
           lowerCAmelCase       :						str							= self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_token_classification(*UpperCamelCase_					)






     @slow
     def   lowerCamelCase__  (						self	:       List[str]					):
           for model_name in ERNIE_M_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                 lowerCAmelCase       :						int							= ErnieMModel.from_pretrained(UpperCamelCase_					)
                 self.assertIsNotNone(UpperCamelCase_					)



@require_torch
class 		snake_case_(							unittest.TestCase      ):






     @slow
     def   lowerCamelCase__  (						self	:       Dict					):
           lowerCAmelCase       :						Optional[int]							= ErnieMModel.from_pretrained('''susnato/ernie-m-base_pytorch'''					)
           model.eval()
           lowerCAmelCase       :						Optional[int]							= torch.tensor([[0, 1, 2, 3, 4, 5]]					)
           lowerCAmelCase       :						str							= model(UpperCamelCase_					)[0]

           # TODO Replace vocab size
           lowerCAmelCase       :						Any							= 7_6_8

           lowerCAmelCase       :						int							= torch.Size((1, 6, hidden_size)					)
           self.assertEqual(output.shape       ,					UpperCamelCase_					)

           lowerCAmelCase       :						str							= torch.tensor(
               [[[-0.0_012, 0.1_245, -0.0_214], [-0.0_742, 0.0_244, -0.0_771], [-0.0_333, 0.1_164, -0.1_554]]]					)

           self.assertTrue(torch.allclose(output[:, :3, :3]       ,					UpperCamelCase_       ,					atol=1E-3					)					)


