




import argparse
import collections

import jax
import jax.numpy as jnp
import torch
import torch.nn as nn
from clip.model import CLIP
from flax.training import checkpoints
from huggingface_hub import Repository

from transformers import (
    CLIPTokenizer,
    OwlViTConfig,
    OwlViTForObjectDetection,
    OwlViTImageProcessor,
    OwlViTModel,
    OwlViTProcessor,
)


lowerCamelCase		      = {
    'vit_b32': {
        'embed_dim': 5_12,
        'image_resolution': 7_68,
        'context_length': 16,
        'vocab_size': 4_94_08,
        'vision_layers': 12,
        'vision_width': 7_68,
        'vision_patch_size': 32,
        'transformer_width': 5_12,
        'transformer_heads': 8,
        'transformer_layers': 12,
    },
    'vit_b16': {
        'embed_dim': 5_12,
        'image_resolution': 7_68,
        'context_length': 16,
        'vocab_size': 4_94_08,
        'vision_layers': 12,
        'vision_width': 7_68,
        'vision_patch_size': 16,
        'transformer_width': 5_12,
        'transformer_heads': 8,
        'transformer_layers': 12,
    },
    'vit_l14': {
        'embed_dim': 7_68,
        'image_resolution': 8_40,
        'context_length': 16,
        'vocab_size': 4_94_08,
        'vision_layers': 24,
        'vision_width': 10_24,
        'vision_patch_size': 14,
        'transformer_width': 7_68,
        'transformer_heads': 12,
        'transformer_layers': 12,
    },
}




def 			a_   (					SCREAMING_SNAKE_CASE__      :   Optional[Any]	,    SCREAMING_SNAKE_CASE__      :   str=""	,    SCREAMING_SNAKE_CASE__      :   Any="/"  ):
       '''simple docstring'''





       _lowerCamelCase :	Any						=[]

       for k, v in params.items():
              _lowerCamelCase :	int						=parent_key + sep + k if parent_key else k

              if isinstance(SCREAMING_SNAKE_CASE__	,    collections.MutableMapping  ):
                     items.extend(flatten_nested_dict(SCREAMING_SNAKE_CASE__	,    SCREAMING_SNAKE_CASE__	,    sep=SCREAMING_SNAKE_CASE__  ).items()  )
              else:
                     items.append((new_key, v)  )
       return dict(SCREAMING_SNAKE_CASE__  )




def 			a_   (					SCREAMING_SNAKE_CASE__      :   List[Any]  ):
       '''simple docstring'''





       return jax.tree_util.tree_map(lambda SCREAMING_SNAKE_CASE__  : x.astype(jnp.floataa  ) if x.dtype == jnp.bfloataa else x	,    SCREAMING_SNAKE_CASE__  )




def 			a_   (					SCREAMING_SNAKE_CASE__      :   int	,    SCREAMING_SNAKE_CASE__      :   Optional[int]  ):
       '''simple docstring'''





       _lowerCamelCase :	int						=pt_attn_layer.in_proj_weight.chunk(3	,    dim=0  )
       _lowerCamelCase :	List[str]						=pt_attn_layer.in_proj_bias.chunk(3	,    dim=0  )

       _lowerCamelCase :	List[str]						=pt_attn_layer.out_proj.weight
       _lowerCamelCase :	Union[str, Any]						=pt_attn_layer.out_proj.bias

       _lowerCamelCase :	Union[str, Any]						=q_proj
       _lowerCamelCase :	Dict						=q_proj_bias

       _lowerCamelCase :	Union[str, Any]						=k_proj
       _lowerCamelCase :	Any						=k_proj_bias

       _lowerCamelCase :	int						=v_proj
       _lowerCamelCase :	Optional[int]						=v_proj_bias

       _lowerCamelCase :	Tuple						=out_proj_weights
       _lowerCamelCase :	Union[str, Any]						=out_proj_bias




def 			a_   (					SCREAMING_SNAKE_CASE__      :   List[Any]	,    SCREAMING_SNAKE_CASE__      :   List[Any]  ):
       '''simple docstring'''





       copy_linear(hf_mlp.fca	,    pt_mlp.c_fc  )
       copy_linear(hf_mlp.fca	,    pt_mlp.c_proj  )




def 			a_   (					SCREAMING_SNAKE_CASE__      :   Optional[int]	,    SCREAMING_SNAKE_CASE__      :   Tuple  ):
       '''simple docstring'''





       _lowerCamelCase :	Optional[Any]						=pt_linear.weight
       _lowerCamelCase :	Optional[Any]						=pt_linear.bias




def 			a_   (					SCREAMING_SNAKE_CASE__      :   int	,    SCREAMING_SNAKE_CASE__      :   int  ):
       '''simple docstring'''





       copy_linear(hf_layer.layer_norma	,    pt_layer.ln_a  )
       copy_linear(hf_layer.layer_norma	,    pt_layer.ln_a  )

       # copy MLP
       copy_mlp(hf_layer.mlp	,    pt_layer.mlp  )

       # copy attn
       copy_attn_layer(hf_layer.self_attn	,    pt_layer.attn  )




def 			a_   (					SCREAMING_SNAKE_CASE__      :   Any	,    SCREAMING_SNAKE_CASE__      :   int  ):
       '''simple docstring'''





       for hf_layer, pt_layer in zip(SCREAMING_SNAKE_CASE__	,    SCREAMING_SNAKE_CASE__  ):
              copy_layer(SCREAMING_SNAKE_CASE__	,    SCREAMING_SNAKE_CASE__  )




def 			a_   (					SCREAMING_SNAKE_CASE__      :   Any	,    SCREAMING_SNAKE_CASE__      :   Dict  ):
       '''simple docstring'''





       _lowerCamelCase :	str						=pt_model.token_embedding.weight
       _lowerCamelCase :	Dict						=pt_model.positional_embedding

       # copy layer norm
       copy_linear(hf_encoder.final_layer_norm	,    pt_model.ln_final  )

       # copy hidden layers
       copy_layers(hf_encoder.encoder.layers	,    pt_model.transformer.resblocks  )




def 			a_   (					SCREAMING_SNAKE_CASE__      :   Dict	,    SCREAMING_SNAKE_CASE__      :   Tuple  ):
       '''simple docstring'''





       _lowerCamelCase :	Optional[Any]						=pt_model.text_projection.data.T

       # copy text encoder
       copy_encoder(hf_model.text_model	,    SCREAMING_SNAKE_CASE__  )




def 			a_   (					SCREAMING_SNAKE_CASE__      :   Dict	,    SCREAMING_SNAKE_CASE__      :   List[str]  ):
       '''simple docstring'''





       _lowerCamelCase :	int						=pt_model.visual.proj.data.T

       # copy layer norms
       copy_linear(hf_model.vision_model.pre_layernorm	,    pt_model.visual.ln_pre  )
       copy_linear(hf_model.vision_model.post_layernorm	,    pt_model.visual.ln_post  )

       # copy embeds
       _lowerCamelCase :	List[Any]						=pt_model.visual.conva.weight.data
       _lowerCamelCase :	Optional[int]						=pt_model.visual.class_embedding
       _lowerCamelCase :	Union[str, Any]						=pt_model.visual.positional_embedding.data

       # copy encoder
       copy_layers(hf_model.vision_model.encoder.layers	,    pt_model.visual.transformer.resblocks  )




def 			a_   (					SCREAMING_SNAKE_CASE__      :   Any	,    SCREAMING_SNAKE_CASE__      :   List[str]  ):
       '''simple docstring'''





       _lowerCamelCase :	Union[str, Any]						=flatten_nested_dict(flax_params['backbone']['merged_class_token']  )

       _lowerCamelCase :	str						=torch.from_numpy(flax_class_token_params['scale']  )
       _lowerCamelCase :	List[str]						=torch.from_numpy(flax_class_token_params['bias']  )
       _lowerCamelCase :	str						=nn.Parameter(SCREAMING_SNAKE_CASE__  )
       _lowerCamelCase :	List[str]						=nn.Parameter(SCREAMING_SNAKE_CASE__  )




def 			a_   (					SCREAMING_SNAKE_CASE__      :   Any	,    SCREAMING_SNAKE_CASE__      :   Any  ):
       '''simple docstring'''





       _lowerCamelCase :	Optional[Any]						=hf_model.state_dict()
       _lowerCamelCase :	List[Any]						={}

       # Rename class prediction head flax params to pytorch HF
       _lowerCamelCase :	List[Any]						=flatten_nested_dict(flax_params['class_head']  )

       for flax_key, v in flax_class_params.items():
              _lowerCamelCase :	Optional[Any]						=flax_key.replace('/'	,    '.'  )
              _lowerCamelCase :	int						=torch_key.replace('.kernel'	,    '.weight'  )
              _lowerCamelCase :	Union[str, Any]						=torch_key.replace('Dense_0'	,    'dense0'  )
              _lowerCamelCase :	Tuple						='class_head.' + torch_key

              if "weight" in torch_key and v.ndim == 2:
                     _lowerCamelCase :	List[str]						=v.T

              _lowerCamelCase :	List[Any]						=nn.Parameter(torch.from_numpy(SCREAMING_SNAKE_CASE__  )  )

       # Rename box prediction box flax params to pytorch HF
       _lowerCamelCase :	List[str]						=flatten_nested_dict(flax_params['obj_box_head']  )

       for flax_key, v in flax_box_params.items():
              _lowerCamelCase :	Union[str, Any]						=flax_key.replace('/'	,    '.'  )
              _lowerCamelCase :	Any						=torch_key.replace('.kernel'	,    '.weight'  )
              _lowerCamelCase :	int						=torch_key.replace('_'	,    ''  ).lower()
              _lowerCamelCase :	Optional[int]						='box_head.' + torch_key

              if "weight" in torch_key and v.ndim == 2:
                     _lowerCamelCase :	Optional[Any]						=v.T

              _lowerCamelCase :	Tuple						=nn.Parameter(torch.from_numpy(SCREAMING_SNAKE_CASE__  )  )

       # Copy flax params to PyTorch params
       for name, param in new_params.items():
              if name in pt_params.keys():
                     pt_params[name].copy_(SCREAMING_SNAKE_CASE__  )




def 			a_   (					SCREAMING_SNAKE_CASE__      :   int	,    SCREAMING_SNAKE_CASE__      :   Tuple  ):
       '''simple docstring'''





       for k, v in flax_attn_params.items():
              if k.startswith('transformer'  ):
                     _lowerCamelCase :	List[str]						=k.replace('transformer.resblocks'	,    'text_model.encoder.layers'  )
              else:
                     _lowerCamelCase :	Union[str, Any]						=k.replace('visual.transformer.resblocks'	,    'vision_model.encoder.layers'  )

              _lowerCamelCase :	Optional[Any]						=torch_key.replace('attn'	,    'self_attn'  )
              _lowerCamelCase :	Tuple						=torch_key.replace('key'	,    'k_proj'  )
              _lowerCamelCase :	str						=torch_key.replace('value'	,    'v_proj'  )
              _lowerCamelCase :	Optional[int]						=torch_key.replace('query'	,    'q_proj'  )
              _lowerCamelCase :	Union[str, Any]						=torch_key.replace('out'	,    'out_proj'  )

              if "bias" in torch_key and v.ndim == 2:
                     _lowerCamelCase :	str						=v.shape[0] * v.shape[1]
                     _lowerCamelCase :	Any						=v.reshape(SCREAMING_SNAKE_CASE__  )

              if "weight" in torch_key and "out" in torch_key:
                     _lowerCamelCase :	Optional[Any]						=(v.shape[0] * v.shape[1], v.shape[2])
                     _lowerCamelCase :	Optional[Any]						=v.reshape(SCREAMING_SNAKE_CASE__  ).T

              if "weight" in torch_key and "out" not in torch_key:
                     _lowerCamelCase :	Union[str, Any]						=(v.shape[0], v.shape[1] * v.shape[2])
                     _lowerCamelCase :	Union[str, Any]						=v.reshape(SCREAMING_SNAKE_CASE__  ).T

              # Copy flax CLIP attn params to HF PyTorch params
              _lowerCamelCase :	int						=torch.from_numpy(SCREAMING_SNAKE_CASE__  )
              hf_backbone.state_dict()[torch_key].copy_(SCREAMING_SNAKE_CASE__  )




def 			a_   (					SCREAMING_SNAKE_CASE__      :   List[str]  ):
       '''simple docstring'''





       _lowerCamelCase :	List[Any]						={}
       _lowerCamelCase :	Tuple						=[]

       for k, v in params.items():
              if "attn." in k:
                     _lowerCamelCase :	Tuple						=k[: k.rindex('attn.'  ) + 5]
                     if base in processed_attn_layers:
                            continue

                     processed_attn_layers.append(SCREAMING_SNAKE_CASE__  )
                     _lowerCamelCase :	Dict						=params[base + 'out.weight'].shape[-1]
                     _lowerCamelCase :	Optional[Any]						=params[base + 'out.weight'].reshape(SCREAMING_SNAKE_CASE__	,    SCREAMING_SNAKE_CASE__  ).T
                     _lowerCamelCase :	Union[str, Any]						=params[base + 'out.bias']
              else:
                     _lowerCamelCase :	Optional[Any]						=v
       return new_params




def 			a_   (					SCREAMING_SNAKE_CASE__      :   List[Any]	,    SCREAMING_SNAKE_CASE__      :   Union[str, Any]  ):
       '''simple docstring'''





       _lowerCamelCase :	str						=CLIP(**SCREAMING_SNAKE_CASE__  )
       torch_model.eval()
       _lowerCamelCase :	Optional[int]						=torch_model.state_dict()

       _lowerCamelCase :	List[str]						=flatten_nested_dict(flax_params['backbone']['clip']  )
       _lowerCamelCase :	List[Any]						={}

       for flax_key, v in flax_clip_params.items():
              _lowerCamelCase :	str						=flax_key.replace('/'	,    '.'  )
              _lowerCamelCase :	int						=torch_key.replace('text.token_embedding.embedding'	,    'token_embedding.kernel'  )

              if (
                  torch_key.startswith('text.transformer'  )
                  or torch_key.startswith('text.text_projection'  )
                  or torch_key.startswith('text.ln_final'  )
                  or torch_key.startswith('text.positional_embedding'  )
              ):
                     _lowerCamelCase :	Tuple						=torch_key[5:]

              _lowerCamelCase :	List[str]						=torch_key.replace('text_projection.kernel'	,    'text_projection'  )
              _lowerCamelCase :	Any						=torch_key.replace('visual.proj.kernel'	,    'visual.proj'  )
              _lowerCamelCase :	List[Any]						=torch_key.replace('.scale'	,    '.weight'  )
              _lowerCamelCase :	Union[str, Any]						=torch_key.replace('.kernel'	,    '.weight'  )

              if "conv" in torch_key or "downsample.0.weight" in torch_key:
                     _lowerCamelCase :	Optional[Any]						=v.transpose(3	,    2	,    0	,    1  )

              elif "weight" in torch_key and v.ndim == 2 and "embedding" not in torch_key:
                     # Fully connected layers are transposed, embeddings are not
                     _lowerCamelCase :	Optional[Any]						=v.T

              _lowerCamelCase :	Dict						=v

       _lowerCamelCase :	int						=_convert_attn_layers(SCREAMING_SNAKE_CASE__  )
       new_torch_params.update(SCREAMING_SNAKE_CASE__  )
       _lowerCamelCase :	Optional[int]						={}

       # Copy flax CLIP backbone params to PyTorch params
       for name, param in new_torch_params.items():
              if name in torch_clip_params.keys():
                     _lowerCamelCase :	Optional[int]						=torch.from_numpy(new_torch_params[name]  )
                     torch_clip_params[name].copy_(SCREAMING_SNAKE_CASE__  )
              else:
                     _lowerCamelCase :	Any						=param

       return torch_clip_params, torch_model, attn_params




@torch.no_grad()
def 			a_   (					SCREAMING_SNAKE_CASE__      :   Union[str, Any]	,    SCREAMING_SNAKE_CASE__      :   Tuple	,    SCREAMING_SNAKE_CASE__      :   Optional[Any]	,    SCREAMING_SNAKE_CASE__      :   Any	,    SCREAMING_SNAKE_CASE__      :   Optional[int]=None  ):
       '''simple docstring'''





       _lowerCamelCase :	List[Any]						=Repository(SCREAMING_SNAKE_CASE__	,    clone_from=F'''google/{pytorch_dump_folder_path}'''  )
       repo.git_pull()

       if config_path is not None:
              _lowerCamelCase :	Union[str, Any]						=OwlViTConfig.from_pretrained(SCREAMING_SNAKE_CASE__  )
       else:
              _lowerCamelCase :	Optional[Any]						=OwlViTConfig()

       _lowerCamelCase :	Dict						=OwlViTModel(SCREAMING_SNAKE_CASE__  ).eval()
       _lowerCamelCase :	List[Any]						=OwlViTForObjectDetection(SCREAMING_SNAKE_CASE__  ).eval()

       copy_text_model_and_projection(SCREAMING_SNAKE_CASE__	,    SCREAMING_SNAKE_CASE__  )
       copy_vision_model_and_projection(SCREAMING_SNAKE_CASE__	,    SCREAMING_SNAKE_CASE__  )
       _lowerCamelCase :	Optional[Any]						=pt_backbone.logit_scale
       copy_flax_attn_params(SCREAMING_SNAKE_CASE__	,    SCREAMING_SNAKE_CASE__  )

       _lowerCamelCase :	Optional[int]						=hf_backbone
       copy_class_merge_token(SCREAMING_SNAKE_CASE__	,    SCREAMING_SNAKE_CASE__  )
       copy_class_box_heads(SCREAMING_SNAKE_CASE__	,    SCREAMING_SNAKE_CASE__  )

       # Save HF model
       hf_model.save_pretrained(repo.local_dir  )

       # Initialize image processor
       _lowerCamelCase :	str						=OwlViTImageProcessor(
           size=config.vision_config.image_size	,    crop_size=config.vision_config.image_size  )
       # Initialize tokenizer
       _lowerCamelCase :	Optional[Any]						=CLIPTokenizer.from_pretrained('openai/clip-vit-base-patch32'	,    pad_token='!'	,    model_max_length=16  )

       # Initialize processor
       _lowerCamelCase :	Optional[int]						=OwlViTProcessor(image_processor=SCREAMING_SNAKE_CASE__	,    tokenizer=SCREAMING_SNAKE_CASE__  )
       image_processor.save_pretrained(repo.local_dir  )
       processor.save_pretrained(repo.local_dir  )

       repo.git_add()
       repo.git_commit('Upload model and processor'  )
       repo.git_push()


if __name__ == "__main__":
 lowerCamelCase		      = argparse.ArgumentParser()
 # Required parameters
 parser.add_argument(
     '--owlvit_version',
     default=None,
     type=str,
     required=True,
     help='OWL-ViT model name [clip_b16, clip_b32, clip_l14].',
 )
 parser.add_argument(
     '--owlvit_checkpoint', default=None, type=str, required=True, help='Path to flax model checkpoint.'
 )
 parser.add_argument('--hf_config', default=None, type=str, required=True, help='Path to HF model config.')
 parser.add_argument(
     '--pytorch_dump_folder_path', default='hf_model', type=str, help='Path to the output PyTorch model.'
 )
 lowerCamelCase		      = parser.parse_args()

 # Initialize PyToch clip model
 lowerCamelCase		      = args.owlvit_version
 if model_name == "clip_b16":
  lowerCamelCase		      = CONFIGS['vit_b16']
 elif model_name == "clip_b32":
  lowerCamelCase		      = CONFIGS['vit_b32']
 elif model_name == "clip_l14":
  lowerCamelCase		      = CONFIGS['vit_l14']

 # Load from checkpoint and convert params to float-32
 lowerCamelCase		      = checkpoints.restore_checkpoint(args.owlvit_checkpoint, target=None)['optimizer']['target']
 lowerCamelCase		      = jax.tree_util.tree_map(lambda x: x.astype(jnp.floataa) if x.dtype == jnp.bfloataa else x, variables)
 del variables

 # Convert CLIP backbone
 lowerCamelCase      ,       lowerCamelCase      ,       lowerCamelCase		      = convert_clip_backbone(flax_params, torch_config)

 convert_owlvit_checkpoint(clip_pt, flax_params, attn_params, args.pytorch_dump_folder_path, args.hf_config)






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 A						:






      def __init__(      self		:  int    ,     lowercase_		:  List[Any]    ,     lowercase_		:  Dict=13    ,     lowercase_		:  Optional[Any]=7    ,     lowercase_		:  List[str]=True    ,     lowercase_		:  List[str]=True    ,     lowercase_		:  Tuple=True    ,     lowercase_		:  Union[str, Any]=99    ,     lowercase_		:  Union[str, Any]=32    ,     lowercase_		:  Tuple=5    ,     lowercase_		:  List[Any]=4    ,     lowercase_		:  Any=37    ,     lowercase_		:  Union[str, Any]="gelu"    ,     lowercase_		:  Any=0.1    ,     lowercase_		:  Union[str, Any]=0.1    ,     lowercase_		:  List[str]=512    ,     lowercase_		:  Optional[int]=16    ,     lowercase_		:  int=2    ,     lowercase_		:  Optional[Any]=0.02    ,     lowercase_		:  Dict=3    ,     lowercase_		:  Any=4    ,     lowercase_		:  List[str]=None    ,     )      ->		Tuple:
             """simple docstring"""




             _lowerCamelCase :	Dict						=parent
             _lowerCamelCase :	Optional[int]						=batch_size
             _lowerCamelCase :	int						=seq_length
             _lowerCamelCase :	List[str]						=is_training
             _lowerCamelCase :	Optional[int]						=use_input_mask
             _lowerCamelCase :	Dict						=use_labels
             _lowerCamelCase :	Any						=vocab_size
             _lowerCamelCase :	Any						=hidden_size
             _lowerCamelCase :	Any						=num_hidden_layers
             _lowerCamelCase :	Optional[int]						=num_attention_heads
             _lowerCamelCase :	Optional[Any]						=intermediate_size
             _lowerCamelCase :	Union[str, Any]						=hidden_act
             _lowerCamelCase :	str						=hidden_dropout_prob
             _lowerCamelCase :	Tuple						=attention_probs_dropout_prob
             _lowerCamelCase :	Tuple						=max_position_embeddings
             _lowerCamelCase :	Optional[int]						=type_vocab_size
             _lowerCamelCase :	Optional[Any]						=type_sequence_label_size
             _lowerCamelCase :	List[str]						=initializer_range
             _lowerCamelCase :	Dict						=num_labels
             _lowerCamelCase :	List[str]						=num_choices
             _lowerCamelCase :	Optional[Any]						=scope






      def  lowerCamelCase (      self		:  Optional[Any]				)      ->		Tuple:
             """simple docstring"""




             _lowerCamelCase :	Union[str, Any]						=ids_tensor([self.batch_size, self.seq_length]    ,     self.vocab_size				)

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

             _lowerCamelCase :	Any						=None
             _lowerCamelCase :	int						=None
             _lowerCamelCase :	int						=None
             if self.use_labels:
                    _lowerCamelCase :	Optional[int]						=ids_tensor([self.batch_size]    ,     self.type_sequence_label_size				)
                    _lowerCamelCase :	List[str]						=ids_tensor([self.batch_size, self.seq_length]    ,     self.num_labels				)
                    _lowerCamelCase :	Optional[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		:  Dict				)      ->		Dict:
             """simple docstring"""




             _lowerCamelCase :	List[str]						=ids_tensor([self.batch_size, self.seq_length]    ,     self.vocab_size				)

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

             return config, input_ids, input_mask






      def  lowerCamelCase (      self		:  Any				)      ->		Any:
             """simple docstring"""




             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		:  Optional[int]    ,     lowercase_		:  Tuple    ,     lowercase_		:  Tuple    ,     lowercase_		:  Any    ,     lowercase_		:  Dict    ,     lowercase_		:  int    ,     lowercase_		:  Tuple				)      ->		List[str]:
             """simple docstring"""




             _lowerCamelCase :	Tuple						=ErnieMModel(config=lowercase_				)
             model.to(lowercase_				)
             model.eval()
             _lowerCamelCase :	str						=model(lowercase_    ,     return_dict=lowercase_				)
             self.parent.assertEqual(result.last_hidden_state.shape    ,     (self.batch_size, self.seq_length, self.hidden_size)				)






      def  lowerCamelCase (      self		:  str    ,     lowercase_		:  Union[str, Any]    ,     lowercase_		:  Union[str, Any]    ,     lowercase_		:  List[str]    ,     lowercase_		:  str    ,     lowercase_		:  List[str]    ,     lowercase_		:  str				)      ->		str:
             """simple docstring"""




             _lowerCamelCase :	Any						=ErnieMForQuestionAnswering(config=lowercase_				)
             model.to(lowercase_				)
             model.eval()
             _lowerCamelCase :	List[str]						=model(
                 lowercase_    ,     attention_mask=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  lowerCamelCase (      self		:  int    ,     lowercase_		:  List[Any]    ,     lowercase_		:  int    ,     lowercase_		:  Optional[int]    ,     lowercase_		:  Optional[Any]    ,     lowercase_		:  Any    ,     lowercase_		:  Optional[int]				)      ->		Any:
             """simple docstring"""




             _lowerCamelCase :	Union[str, Any]						=ErnieMForInformationExtraction(config=lowercase_				)
             model.to(lowercase_				)
             model.eval()
             _lowerCamelCase :	Optional[int]						=torch.ones_like(lowercase_    ,     dtype=torch.floataa				)
             _lowerCamelCase :	str						=model(
                 lowercase_    ,     attention_mask=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  lowerCamelCase (      self		:  Dict    ,     lowercase_		:  Dict    ,     lowercase_		:  Tuple    ,     lowercase_		:  List[str]    ,     lowercase_		:  str    ,     lowercase_		:  Any    ,     lowercase_		:  Tuple				)      ->		int:
             """simple docstring"""




             _lowerCamelCase :	Dict						=self.num_labels
             _lowerCamelCase :	Any						=ErnieMForSequenceClassification(lowercase_				)
             model.to(lowercase_				)
             model.eval()
             _lowerCamelCase :	Optional[int]						=model(lowercase_    ,     attention_mask=lowercase_    ,     labels=lowercase_				)
             self.parent.assertEqual(result.logits.shape    ,     (self.batch_size, self.num_labels)				)






      def  lowerCamelCase (      self		:  Dict    ,     lowercase_		:  List[str]    ,     lowercase_		:  Optional[Any]    ,     lowercase_		:  Optional[int]    ,     lowercase_		:  List[str]    ,     lowercase_		:  Optional[int]    ,     lowercase_		:  Dict				)      ->		int:
             """simple docstring"""




             _lowerCamelCase :	int						=self.num_labels
             _lowerCamelCase :	List[str]						=ErnieMForTokenClassification(config=lowercase_				)
             model.to(lowercase_				)
             model.eval()
             input_ids.to(lowercase_				)
             input_mask.to(lowercase_				)
             token_labels.to(lowercase_				)

             _lowerCamelCase :	List[Any]						=model(lowercase_    ,     attention_mask=lowercase_    ,     labels=lowercase_				)

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






      def  lowerCamelCase (      self		:  Union[str, Any]    ,     lowercase_		:  int    ,     lowercase_		:  Union[str, Any]    ,     lowercase_		:  int    ,     lowercase_		:  str    ,     lowercase_		:  Optional[int]    ,     lowercase_		:  str				)      ->		Tuple:
             """simple docstring"""




             _lowerCamelCase :	Any						=self.num_choices
             _lowerCamelCase :	Any						=ErnieMForMultipleChoice(config=lowercase_				)
             model.to(lowercase_				)
             model.eval()
             _lowerCamelCase :	str						=input_ids.unsqueeze(1				).expand(-1    ,     self.num_choices    ,     -1				).contiguous()
             _lowerCamelCase :	Optional[int]						=input_mask.unsqueeze(1				).expand(-1    ,     self.num_choices    ,     -1				).contiguous()
             _lowerCamelCase :	List[str]						=model(
                 lowercase_    ,     attention_mask=lowercase_    ,     labels=lowercase_    ,     )
             self.parent.assertEqual(result.logits.shape    ,     (self.batch_size, self.num_choices)				)






      def  lowerCamelCase (      self		:  Union[str, Any]				)      ->		List[str]:
             """simple docstring"""




             _lowerCamelCase :	Tuple						=self.prepare_config_and_inputs()
             (
                 (
                 _lowerCamelCase
             )			,  (
                 _lowerCamelCase
             )			,  (
                 _lowerCamelCase
             )			,  (
                 _lowerCamelCase
             )			,  (
                 _lowerCamelCase
             )			,  (
                 _lowerCamelCase
             )			,  
             ) :	List[Any]						=config_and_inputs
             _lowerCamelCase :	Optional[Any]						={'input_ids': input_ids, 'attention_mask': input_mask}
             return config, inputs_dict




@require_torch
class A						(     UpperCamelCase_					,							UpperCamelCase_					,							unittest.TestCase  ):
      UpperCamelCase__							:						str   =(
          (
              ErnieMModel,
              ErnieMForMultipleChoice,
              ErnieMForQuestionAnswering,
              ErnieMForSequenceClassification,
              ErnieMForTokenClassification,
          )
          if is_torch_available()
          else ()
      )
      UpperCamelCase__							:						Dict   =()
      UpperCamelCase__							:						List[str]   =(
          {
              'feature-extraction': ErnieMModel,
              'question-answering': ErnieMForQuestionAnswering,
              'text-classification': ErnieMForSequenceClassification,
              'token-classification': ErnieMForTokenClassification,
              'zero-shot': ErnieMForSequenceClassification,
          }
          if is_torch_available()
          else {}
      )
      UpperCamelCase__							:						List[str]   =False






      def  lowerCamelCase (      self		:  str    ,     lowercase_		:  List[Any]    ,     lowercase_		:  Any    ,     lowercase_		:  str    ,     lowercase_		:  Tuple    ,     lowercase_		:  Tuple				)      ->		Dict:
             """simple docstring"""




             if pipeline_test_casse_name == "QAPipelineTests":
                    return True

             return False






      def  lowerCamelCase (      self		:  Union[str, Any]				)      ->		int:
             """simple docstring"""




             _lowerCamelCase :	int						=ErnieMModelTester(self				)
             _lowerCamelCase :	Optional[int]						=ConfigTester(self    ,     config_class=lowercase_    ,     hidden_size=37				)






      def  lowerCamelCase (      self		:  Optional[Any]				)      ->		Union[str, Any]:
             """simple docstring"""




             self.config_tester.run_common_tests()






      def  lowerCamelCase (      self		:  Optional[int]				)      ->		Dict:
             """simple docstring"""




             _lowerCamelCase :	Union[str, Any]						=self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_model(*lowercase_				)






      def  lowerCamelCase (      self		:  Dict				)      ->		Optional[Any]:
             """simple docstring"""




             _lowerCamelCase :	List[Any]						=self.model_tester.prepare_config_and_inputs()
             for type in ["absolute", "relative_key", "relative_key_query"]:
                    _lowerCamelCase :	Optional[Any]						=type
                    self.model_tester.create_and_check_model(*lowercase_				)






      def  lowerCamelCase (      self		:  Tuple				)      ->		Any:
             """simple docstring"""




             _lowerCamelCase :	Optional[Any]						=self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_for_multiple_choice(*lowercase_				)






      def  lowerCamelCase (      self		:  str				)      ->		Tuple:
             """simple docstring"""




             _lowerCamelCase :	Dict						=self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_for_question_answering(*lowercase_				)






      def  lowerCamelCase (      self		:  List[str]				)      ->		Union[str, Any]:
             """simple docstring"""




             _lowerCamelCase :	Any						=self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_for_sequence_classification(*lowercase_				)






      def  lowerCamelCase (      self		:  List[str]				)      ->		Union[str, Any]:
             """simple docstring"""




             _lowerCamelCase :	List[str]						=self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_for_information_extraction(*lowercase_				)






      def  lowerCamelCase (      self		:  Optional[Any]				)      ->		Tuple:
             """simple docstring"""




             _lowerCamelCase :	str						=self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_for_token_classification(*lowercase_				)






      @slow
      def  lowerCamelCase (      self		:  Union[str, Any]				)      ->		List[str]:
             """simple docstring"""




             for model_name in ERNIE_M_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                    _lowerCamelCase :	Union[str, Any]						=ErnieMModel.from_pretrained(lowercase_				)
                    self.assertIsNotNone(lowercase_				)




@require_torch
class A						(     unittest.TestCase  ):






      @slow
      def  lowerCamelCase (      self		:  List[str]				)      ->		Dict:
             """simple docstring"""




             _lowerCamelCase :	Dict						=ErnieMModel.from_pretrained('susnato/ernie-m-base_pytorch'				)
             model.eval()
             _lowerCamelCase :	Optional[int]						=torch.tensor([[0, 1, 2, 3, 4, 5]]				)
             _lowerCamelCase :	Optional[int]						=model(lowercase_				)[0]

             # TODO Replace vocab size
             _lowerCamelCase :	Optional[Any]						=768

             _lowerCamelCase :	str						=torch.Size((1, 6, hidden_size)				)
             self.assertEqual(output.shape    ,     lowercase_				)

             _lowerCamelCase :	str						=torch.tensor(
                 [[[-0.0012, 0.1245, -0.0214], [-0.0742, 0.0244, -0.0771], [-0.0333, 0.1164, -0.1554]]]				)

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


