


import argparse
import json
import os

import fairseq
import torch
from fairseq.data import Dictionary

from transformers import (
    WavaVecaConfig,
    WavaVecaCTCTokenizer,
    WavaVecaFeatureExtractor,
    WavaVecaForCTC,
    WavaVecaForPreTraining,
    WavaVecaProcessor,
    logging,
)
from transformers.models.wavaveca.modeling_wavaveca import WavaVecaForSequenceClassification


logging.set_verbosity_info()
snake_case__				:	List[Any]					       =					logging.get_logger(__name__)

snake_case__				:	Dict					       =					{
    'post_extract_proj': 'feature_projection.projection',
    'encoder.pos_conv.0': 'encoder.pos_conv_embed.conv',
    'self_attn.k_proj': 'encoder.layers.*.attention.k_proj',
    'self_attn.v_proj': 'encoder.layers.*.attention.v_proj',
    'self_attn.q_proj': 'encoder.layers.*.attention.q_proj',
    'self_attn.out_proj': 'encoder.layers.*.attention.out_proj',
    'self_attn_layer_norm': 'encoder.layers.*.layer_norm',
    'fc1': 'encoder.layers.*.feed_forward.intermediate_dense',
    'fc2': 'encoder.layers.*.feed_forward.output_dense',
    'final_layer_norm': 'encoder.layers.*.final_layer_norm',
    'encoder.layer_norm': 'encoder.layer_norm',
    'adapter_layer': 'encoder.layers.*.adapter_layer',
    'w2v_model.layer_norm': 'feature_projection.layer_norm',
    'quantizer.weight_proj': 'quantizer.weight_proj',
    'quantizer.vars': 'quantizer.codevectors',
    'project_q': 'project_q',
    'final_proj': 'project_hid',
    'w2v_encoder.proj': 'lm_head',
    'mask_emb': 'masked_spec_embed',
    'pooling_layer.linear': 'projector',
    'pooling_layer.projection': 'classifier',
}
snake_case__				:	List[Any]					       =					[
    'lm_head',
    'quantizer.weight_proj',
    'quantizer.codevectors',
    'project_q',
    'project_hid',
    'projector',
    'classifier',
]


def    __lowerCamelCase   (      A__						: List[Any]					)     ->    Union[str, Any]:
   lowerCamelCase_						:   Optional[Any]		= {}
   with open(A__						,						"""r"""					) as file:
      for line_number, line in enumerate(A__					):
         lowerCamelCase_						:   Any		= line.strip()
         if line:
            lowerCamelCase_						:   Union[str, Any]		= line.split()
            lowerCamelCase_						:   Union[str, Any]		= line_number
            lowerCamelCase_						:   List[str]		= words[0]
            lowerCamelCase_						:   str		= value
   return result


def    __lowerCamelCase   (      A__						: Optional[Any]						,						A__						: Any						,						A__						: Optional[int]						,						A__						: Tuple						,						A__						: List[str]					)     ->    Any:
   for attribute in key.split("""."""					):
      lowerCamelCase_						:   int		= getattr(A__						,						A__					)

   lowerCamelCase_						:   int		= None
   for param_key in PARAM_MAPPING.keys():
      if full_name.endswith(A__					):
         lowerCamelCase_						:   Any		= PARAM_MAPPING[full_name.split("""."""					)[-1]]
         lowerCamelCase_						:   List[str]		= """param"""

   if weight_type is not None and weight_type != "param":
      lowerCamelCase_						:   Union[str, Any]		= getattr(A__						,						A__					).shape
   elif weight_type is not None and weight_type == "param":
      lowerCamelCase_						:   Tuple		= hf_pointer
      for attribute in hf_param_name.split("""."""					):
         lowerCamelCase_						:   List[Any]		= getattr(A__						,						A__					)
      lowerCamelCase_						:   Tuple		= shape_pointer.shape

      # let's reduce dimension
      lowerCamelCase_						:   Tuple		= value[0]
   else:
      lowerCamelCase_						:   Dict		= hf_pointer.shape

   if hf_shape != value.shape:
      raise ValueError(
          f'''Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be'''
          f''' {value.shape} for {full_name}'''					)

   if weight_type == "weight":
      lowerCamelCase_						:   List[Any]		= value
   elif weight_type == "weight_g":
      lowerCamelCase_						:   Dict		= value
   elif weight_type == "weight_v":
      lowerCamelCase_						:   int		= value
   elif weight_type == "bias":
      lowerCamelCase_						:   Optional[Any]		= value
   elif weight_type == "param":
      for attribute in hf_param_name.split("""."""					):
         lowerCamelCase_						:   List[str]		= getattr(A__						,						A__					)
      lowerCamelCase_						:   str		= value
   else:
      lowerCamelCase_						:   Optional[Any]		= value

   logger.info(f'''{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}.'''					)


def    __lowerCamelCase   (      A__						: Tuple						,						A__						: Dict						,						A__						: List[str]						,						A__						: Optional[int]						,						A__						: Union[str, Any]					)     ->    List[Any]:
   lowerCamelCase_						:   Optional[Any]		= None
   for param_key in PARAM_MAPPING.keys():
      if full_name.endswith(A__					):
         lowerCamelCase_						:   Tuple		= PARAM_MAPPING[full_name.split("""."""					)[-1]]
         lowerCamelCase_						:   Optional[Any]		= """param"""

   if weight_type is not None and weight_type != "param":
      lowerCamelCase_						:   Optional[Any]		= """.""".join([key, weight_type]					)
   elif weight_type is not None and weight_type == "param":
      lowerCamelCase_						:   str		= """.""".join([key, hf_param_name]					)
   else:
      lowerCamelCase_						:   str		= key

   lowerCamelCase_						:   Union[str, Any]		= value if """lm_head""" in full_key else value[0]


snake_case__				:	int					       =					{
    'W_a': 'linear_1.weight',
    'W_b': 'linear_2.weight',
    'b_a': 'linear_1.bias',
    'b_b': 'linear_2.bias',
    'ln_W': 'norm.weight',
    'ln_b': 'norm.bias',
}


def    __lowerCamelCase   (      A__						: List[str]						,						A__						: Optional[int]						,						A__						: List[Any]=None						,						A__						: Optional[int]=None					)     ->    str:
   lowerCamelCase_						:   List[str]		= False
   for key, mapped_key in MAPPING.items():
      lowerCamelCase_						:   str		= """wav2vec2.""" + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key
      if key in name or key.split("""w2v_model."""					)[-1] == name.split("""."""					)[0]:
         lowerCamelCase_						:   Dict		= True
         if "*" in mapped_key:
            lowerCamelCase_						:   Optional[int]		= name.split(A__					)[0].split("""."""					)[-2]
            lowerCamelCase_						:   Tuple		= mapped_key.replace("""*"""						,						A__					)
         if "weight_g" in name:
            lowerCamelCase_						:   str		= """weight_g"""
         elif "weight_v" in name:
            lowerCamelCase_						:   int		= """weight_v"""
         elif "bias" in name:
            lowerCamelCase_						:   Any		= """bias"""
         elif "weight" in name:
            # TODO: don't match quantizer.weight_proj
            lowerCamelCase_						:   List[Any]		= """weight"""
         else:
            lowerCamelCase_						:   Union[str, Any]		= None
         if hf_dict is not None:
            rename_dict(A__						,						A__						,						A__						,						A__						,						A__					)
         else:
            set_recursively(A__						,						A__						,						A__						,						A__						,						A__					)
         return is_used
   return is_used


def    __lowerCamelCase   (      A__						: List[str]						,						A__						: Tuple						,						A__						: List[Any]					)     ->    str:
   lowerCamelCase_						:   List[Any]		= []
   lowerCamelCase_						:   str		= fairseq_model.state_dict()

   lowerCamelCase_						:   Optional[Any]		= hf_model.wavaveca.feature_extractor

   for name, value in fairseq_dict.items():
      lowerCamelCase_						:   Dict		= False
      if "conv_layers" in name:
         load_conv_layer(
             A__						,						A__						,						A__						,						A__						,						hf_model.config.feat_extract_norm == """group"""						,						)
         lowerCamelCase_						:   Dict		= True
      else:
         lowerCamelCase_						:   List[Any]		= load_wavaveca_layer(A__						,						A__						,						A__					)
      if not is_used:
         unused_weights.append(A__					)

   logger.warning(f'''Unused weights: {unused_weights}'''					)


def    __lowerCamelCase   (      A__						: Optional[int]						,						A__						: Union[str, Any]						,						A__						: int						,						A__						: List[str]						,						A__						: int					)     ->    List[Any]:
   lowerCamelCase_						:   Optional[int]		= full_name.split("""conv_layers."""					)[-1]
   lowerCamelCase_						:   Any		= name.split("""."""					)
   lowerCamelCase_						:   List[Any]		= int(items[0]					)
   lowerCamelCase_						:   Union[str, Any]		= int(items[1]					)

   if type_id == 0:
      if "bias" in name:
         if value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape:
            raise ValueError(
                f'''{full_name} has size {value.shape}, but'''
                f''' {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.'''					)
         lowerCamelCase_						:   int		= value
         logger.info(f'''Feat extract conv layer {layer_id} was initialized from {full_name}.'''					)
      elif "weight" in name:
         if value.shape != feature_extractor.conv_layers[layer_id].conv.weight.data.shape:
            raise ValueError(
                f'''{full_name} has size {value.shape}, but'''
                f''' {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.'''					)
         lowerCamelCase_						:   Any		= value
         logger.info(f'''Feat extract conv layer {layer_id} was initialized from {full_name}.'''					)
   elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm):
      if "bias" in name:
         if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape:
            raise ValueError(
                f'''{full_name} has size {value.shape}, but'''
                f''' {feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape} was found.'''					)
         lowerCamelCase_						:   Optional[Any]		= value
         logger.info(f'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.'''					)
      elif "weight" in name:
         if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape:
            raise ValueError(
                f'''{full_name} has size {value.shape}, but'''
                f''' {feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape} was found.'''					)
         lowerCamelCase_						:   Dict		= value
         logger.info(f'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.'''					)
   else:
      unused_weights.append(A__					)


@torch.no_grad()
def    __lowerCamelCase   (      A__						: str						,						A__						: List[Any]						,						A__						: Optional[int]=None						,						A__						: Tuple=None						,						A__						: str=True						,						A__						: List[Any]=False					)     ->    Optional[Any]:
   if config_path is not None:
      lowerCamelCase_						:   Optional[int]		= WavaVecaConfig.from_pretrained(A__					)
   else:
      lowerCamelCase_						:   Union[str, Any]		= WavaVecaConfig()

   if is_seq_class:
      lowerCamelCase_						:   int		= read_txt_into_dict(A__					)
      lowerCamelCase_						:   Optional[int]		= idalabel
      lowerCamelCase_						:   str		= WavaVecaForSequenceClassification(A__					)
      lowerCamelCase_						:   Any		= WavaVecaFeatureExtractor(
          feature_size=1						,						sampling_rate=1_6000						,						padding_value=0						,						do_normalize=A__						,						return_attention_mask=A__						,						)
      feature_extractor.save_pretrained(A__					)

   elif is_finetuned:
      if dict_path:
         lowerCamelCase_						:   Optional[Any]		= Dictionary.load(A__					)

         # important change bos & pad token id since CTC symbol is <pad> and
         # not <s> as in fairseq
         lowerCamelCase_						:   Union[str, Any]		= target_dict.pad_index
         lowerCamelCase_						:   Dict		= target_dict.bos_index
         lowerCamelCase_						:   Any		= target_dict.eos_index
         lowerCamelCase_						:   List[Any]		= len(target_dict.symbols					)
         lowerCamelCase_						:   List[Any]		= os.path.join(A__						,						"""vocab.json"""					)
         if not os.path.isdir(A__					):
            logger.error("""--pytorch_dump_folder_path ({}) should be a directory""".format(A__					)					)
            return
         os.makedirs(A__						,						exist_ok=A__					)
         lowerCamelCase_						:   Dict		= target_dict.indices

         # fairseq has the <pad> and <s> switched
         lowerCamelCase_						:   str		= 0
         lowerCamelCase_						:   Union[str, Any]		= 1
         with open(A__						,						"""w"""						,						encoding="""utf-8"""					) as vocab_handle:
            json.dump(A__						,						A__					)
         lowerCamelCase_						:   int		= WavaVecaCTCTokenizer(
             A__						,						unk_token=target_dict.unk_word						,						pad_token=target_dict.pad_word						,						bos_token=target_dict.bos_word						,						eos_token=target_dict.eos_word						,						word_delimiter_token="""|"""						,						do_lower_case=A__						,						)
         lowerCamelCase_						:   int		= True if config.feat_extract_norm == """layer""" else False
         lowerCamelCase_						:   List[Any]		= WavaVecaFeatureExtractor(
             feature_size=1						,						sampling_rate=1_6000						,						padding_value=0						,						do_normalize=A__						,						return_attention_mask=A__						,						)
         lowerCamelCase_						:   Tuple		= WavaVecaProcessor(feature_extractor=A__						,						tokenizer=A__					)
         processor.save_pretrained(A__					)

      lowerCamelCase_						:   List[Any]		= WavaVecaForCTC(A__					)
   else:
      lowerCamelCase_						:   Tuple		= WavaVecaForPreTraining(A__					)

   if is_finetuned or is_seq_class:
      lowerCamelCase_,	lowerCamelCase_,	lowerCamelCase_						:   str		= fairseq.checkpoint_utils.load_model_ensemble_and_task(
          [checkpoint_path]						,						arg_overrides={"""data""": """/""".join(dict_path.split("""/"""					)[:-1]					)}					)
   else:
      lowerCamelCase_						:   Tuple		= argparse.Namespace(task="""audio_pretraining"""					)
      lowerCamelCase_						:   Tuple		= fairseq.tasks.setup_task(A__					)

      lowerCamelCase_,	lowerCamelCase_,	lowerCamelCase_						:   Union[str, Any]		= fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path]						,						task=A__					)

   lowerCamelCase_						:   Any		= model[0].eval()

   recursively_load_weights(A__						,						A__						,						not is_finetuned					)

   hf_wavavec.save_pretrained(A__					)


if __name__ == "__main__":
      snake_case__				:	List[str]					       =					argparse.ArgumentParser()
      parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.')
      parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to fairseq checkpoint')
      parser.add_argument('--dict_path', default=None, type=str, help='Path to dict of fine-tuned model')
      parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert')
      parser.add_argument(
          '--not_finetuned', action='store_true', help='Whether the model to convert is a fine-tuned model or not'
      )
      parser.add_argument(
          '--is_seq_class',
          action='store_true',
          help='Whether the model to convert is a fine-tuned sequence classification model or not',
      )
      snake_case__				:	Tuple					       =					parser.parse_args()

      snake_case__				:	Dict					       =					not args.not_finetuned and not args.is_seq_class
      convert_wavaveca_checkpoint(
          args.checkpoint_path,
          args.pytorch_dump_folder_path,
          args.config_path,
          args.dict_path,
          is_finetuned,
          args.is_seq_class,
      )









import unittest

from transformers import MobileBertConfig, is_torch_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_sentencepiece, require_tokenizers, 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 (
          MODEL_FOR_PRETRAINING_MAPPING,
          MobileBertForMaskedLM,
          MobileBertForMultipleChoice,
          MobileBertForNextSentencePrediction,
          MobileBertForPreTraining,
          MobileBertForQuestionAnswering,
          MobileBertForSequenceClassification,
          MobileBertForTokenClassification,
          MobileBertModel,
      )





class   SCREAMING_SNAKE_CASE_			:




       '''simple docstring'''



       def __init__(						self				:				Optional[Any]		,				__a				:				int		,				__a				:				str=13		,				__a				:				Tuple=7		,				__a				:				int=True		,				__a				:				int=True		,				__a				:				Dict=True		,				__a				:				str=True		,				__a				:				List[str]=99		,				__a				:				Dict=64		,				__a				:				Optional[Any]=32		,				__a				:				List[Any]=5		,				__a				:				Optional[int]=4		,				__a				:				str=37		,				__a				:				str="gelu"		,				__a				:				Optional[Any]=0.1		,				__a				:				Union[str, Any]=0.1		,				__a				:				int=512		,				__a				:				Optional[Any]=16		,				__a				:				Any=2		,				__a				:				Dict=0.02		,				__a				:				str=3		,				__a				:				List[Any]=4		,				__a				:				List[str]=None		,				)					->Optional[int]:
          lowerCamelCase_						:   Dict		= parent
          lowerCamelCase_						:   Optional[Any]		= batch_size
          lowerCamelCase_						:   Any		= seq_length
          lowerCamelCase_						:   Union[str, Any]		= is_training
          lowerCamelCase_						:   int		= use_input_mask
          lowerCamelCase_						:   int		= use_token_type_ids
          lowerCamelCase_						:   int		= use_labels
          lowerCamelCase_						:   List[str]		= vocab_size
          lowerCamelCase_						:   Any		= hidden_size
          lowerCamelCase_						:   Any		= embedding_size
          lowerCamelCase_						:   int		= num_hidden_layers
          lowerCamelCase_						:   Union[str, Any]		= num_attention_heads
          lowerCamelCase_						:   Optional[Any]		= intermediate_size
          lowerCamelCase_						:   Optional[int]		= hidden_act
          lowerCamelCase_						:   Dict		= hidden_dropout_prob
          lowerCamelCase_						:   Any		= attention_probs_dropout_prob
          lowerCamelCase_						:   Optional[int]		= max_position_embeddings
          lowerCamelCase_						:   Dict		= type_vocab_size
          lowerCamelCase_						:   List[str]		= type_sequence_label_size
          lowerCamelCase_						:   Any		= initializer_range
          lowerCamelCase_						:   Union[str, Any]		= num_labels
          lowerCamelCase_						:   List[Any]		= num_choices
          lowerCamelCase_						:   Dict		= scope



       def 				_lowerCAmelCase							(						self				:				int							)					->str:
          lowerCamelCase_						:   Dict		= ids_tensor([self.batch_size, self.seq_length]		,				self.vocab_size							)

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

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

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

          lowerCamelCase_						:   str		= self.get_config()

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



       def 				_lowerCAmelCase							(						self				:				Tuple							)					->Optional[Any]:
          return MobileBertConfig(
              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		,				embedding_size=self.embedding_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=__a		,				initializer_range=self.initializer_range		,				)



       def 				_lowerCAmelCase							(						self				:				Tuple		,				__a				:				int		,				__a				:				List[str]		,				__a				:				Tuple		,				__a				:				Any		,				__a				:				Union[str, Any]		,				__a				:				int		,				__a				:				Any							)					->Tuple:
          lowerCamelCase_						:   Tuple		= MobileBertModel(config=__a							)
          model.to(__a							)
          model.eval()
          lowerCamelCase_						:   Dict		= model(__a		,				attention_mask=__a		,				token_type_ids=__a							)
          lowerCamelCase_						:   Optional[int]		= model(__a		,				token_type_ids=__a							)
          lowerCamelCase_						:   Tuple		= model(__a							)

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



       def 				_lowerCAmelCase							(						self				:				List[str]		,				__a				:				str		,				__a				:				Union[str, Any]		,				__a				:				int		,				__a				:				List[Any]		,				__a				:				Dict		,				__a				:				List[Any]		,				__a				:				List[str]							)					->Tuple:
          lowerCamelCase_						:   List[Any]		= MobileBertForMaskedLM(config=__a							)
          model.to(__a							)
          model.eval()
          lowerCamelCase_						:   Union[str, Any]		= model(__a		,				attention_mask=__a		,				token_type_ids=__a		,				labels=__a							)
          self.parent.assertEqual(result.logits.shape		,				(self.batch_size, self.seq_length, self.vocab_size)							)



       def 				_lowerCAmelCase							(						self				:				Optional[Any]		,				__a				:				Tuple		,				__a				:				Tuple		,				__a				:				Dict		,				__a				:				Tuple		,				__a				:				Optional[Any]		,				__a				:				Union[str, Any]		,				__a				:				Dict							)					->int:
          lowerCamelCase_						:   Tuple		= MobileBertForNextSentencePrediction(config=__a							)
          model.to(__a							)
          model.eval()
          lowerCamelCase_						:   Any		= model(
              __a		,				attention_mask=__a		,				token_type_ids=__a		,				labels=__a		,				)
          self.parent.assertEqual(result.logits.shape		,				(self.batch_size, 2)							)



       def 				_lowerCAmelCase							(						self				:				str		,				__a				:				Optional[Any]		,				__a				:				int		,				__a				:				Optional[int]		,				__a				:				Optional[int]		,				__a				:				Optional[int]		,				__a				:				Optional[int]		,				__a				:				Dict							)					->List[Any]:
          lowerCamelCase_						:   Optional[int]		= MobileBertForPreTraining(config=__a							)
          model.to(__a							)
          model.eval()
          lowerCamelCase_						:   List[Any]		= model(
              __a		,				attention_mask=__a		,				token_type_ids=__a		,				labels=__a		,				next_sentence_label=__a		,				)
          self.parent.assertEqual(result.prediction_logits.shape		,				(self.batch_size, self.seq_length, self.vocab_size)							)
          self.parent.assertEqual(result.seq_relationship_logits.shape		,				(self.batch_size, 2)							)



       def 				_lowerCAmelCase							(						self				:				List[str]		,				__a				:				Tuple		,				__a				:				int		,				__a				:				Optional[Any]		,				__a				:				Optional[Any]		,				__a				:				Tuple		,				__a				:				Optional[Any]		,				__a				:				Any							)					->List[str]:
          lowerCamelCase_						:   Dict		= MobileBertForQuestionAnswering(config=__a							)
          model.to(__a							)
          model.eval()
          lowerCamelCase_						:   Tuple		= model(
              __a		,				attention_mask=__a		,				token_type_ids=__a		,				start_positions=__a		,				end_positions=__a		,				)
          self.parent.assertEqual(result.start_logits.shape		,				(self.batch_size, self.seq_length)							)
          self.parent.assertEqual(result.end_logits.shape		,				(self.batch_size, self.seq_length)							)



       def 				_lowerCAmelCase							(						self				:				Optional[Any]		,				__a				:				List[Any]		,				__a				:				str		,				__a				:				int		,				__a				:				Dict		,				__a				:				Dict		,				__a				:				List[Any]		,				__a				:				str							)					->Tuple:
          lowerCamelCase_						:   Dict		= self.num_labels
          lowerCamelCase_						:   Optional[Any]		= MobileBertForSequenceClassification(__a							)
          model.to(__a							)
          model.eval()
          lowerCamelCase_						:   str		= model(__a		,				attention_mask=__a		,				token_type_ids=__a		,				labels=__a							)
          self.parent.assertEqual(result.logits.shape		,				(self.batch_size, self.num_labels)							)



       def 				_lowerCAmelCase							(						self				:				List[str]		,				__a				:				str		,				__a				:				List[str]		,				__a				:				Optional[int]		,				__a				:				int		,				__a				:				str		,				__a				:				str		,				__a				:				Optional[Any]							)					->Tuple:
          lowerCamelCase_						:   int		= self.num_labels
          lowerCamelCase_						:   List[str]		= MobileBertForTokenClassification(config=__a							)
          model.to(__a							)
          model.eval()
          lowerCamelCase_						:   Optional[Any]		= model(__a		,				attention_mask=__a		,				token_type_ids=__a		,				labels=__a							)
          self.parent.assertEqual(result.logits.shape		,				(self.batch_size, self.seq_length, self.num_labels)							)



       def 				_lowerCAmelCase							(						self				:				Union[str, Any]		,				__a				:				Any		,				__a				:				Tuple		,				__a				:				Dict		,				__a				:				Dict		,				__a				:				List[Any]		,				__a				:				Optional[int]		,				__a				:				Optional[Any]							)					->List[str]:
          lowerCamelCase_						:   Any		= self.num_choices
          lowerCamelCase_						:   int		= MobileBertForMultipleChoice(config=__a							)
          model.to(__a							)
          model.eval()
          lowerCamelCase_						:   Tuple		= input_ids.unsqueeze(1							).expand(-1		,				self.num_choices		,				-1							).contiguous()
          lowerCamelCase_						:   Tuple		= token_type_ids.unsqueeze(1							).expand(-1		,				self.num_choices		,				-1							).contiguous()
          lowerCamelCase_						:   Any		= input_mask.unsqueeze(1							).expand(-1		,				self.num_choices		,				-1							).contiguous()
          lowerCamelCase_						:   Tuple		= model(
              __a		,				attention_mask=__a		,				token_type_ids=__a		,				labels=__a		,				)
          self.parent.assertEqual(result.logits.shape		,				(self.batch_size, self.num_choices)							)




       def 				_lowerCAmelCase							(						self				:				List[str]							)					->int:
          lowerCamelCase_						:   Optional[Any]		= self.prepare_config_and_inputs()
          (
              (
              lowerCamelCase_
          ),	(
              lowerCamelCase_
          ),	(
              lowerCamelCase_
          ),	(
              lowerCamelCase_
          ),	(
              lowerCamelCase_
          ),	(
              lowerCamelCase_
          ),	(
              lowerCamelCase_
          ),	
          )						:   Optional[Any]		= config_and_inputs
          lowerCamelCase_						:   List[Any]		= {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask}
          return config, inputs_dict







@require_torch
class   SCREAMING_SNAKE_CASE_			(a__						,       a__						,       unittest.TestCase						):




       '''simple docstring'''



       _a   							=							(
           (
               MobileBertModel,
               MobileBertForMaskedLM,
               MobileBertForMultipleChoice,
               MobileBertForNextSentencePrediction,
               MobileBertForPreTraining,
               MobileBertForQuestionAnswering,
               MobileBertForSequenceClassification,
               MobileBertForTokenClassification,
           )
           if is_torch_available()
           else ()
       )
       _a   							=							(
           {
               "feature-extraction": MobileBertModel,
               "fill-mask": MobileBertForMaskedLM,
               "question-answering": MobileBertForQuestionAnswering,
               "text-classification": MobileBertForSequenceClassification,
               "token-classification": MobileBertForTokenClassification,
               "zero-shot": MobileBertForSequenceClassification,
           }
           if is_torch_available()
           else {}
       )
       _a   							=							True



       def 				_lowerCAmelCase							(						self				:				Optional[int]		,				__a				:				Union[str, Any]		,				__a				:				Dict		,				__a				:				str=False							)					->Any:
          lowerCamelCase_						:   Optional[int]		= super()._prepare_for_class(__a		,				__a		,				return_labels=__a							)

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



       def 				_lowerCAmelCase							(						self				:				Union[str, Any]							)					->Union[str, Any]:
          lowerCamelCase_						:   List[Any]		= MobileBertModelTester(self							)
          lowerCamelCase_						:   int		= ConfigTester(self		,				config_class=__a		,				hidden_size=37							)



       def 				_lowerCAmelCase							(						self				:				Union[str, Any]							)					->List[Any]:
          self.config_tester.run_common_tests()



       def 				_lowerCAmelCase							(						self				:				str							)					->Any:
          lowerCamelCase_						:   Union[str, Any]		= self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_mobilebert_model(*__a							)



       def 				_lowerCAmelCase							(						self				:				List[str]							)					->Tuple:
          lowerCamelCase_						:   List[str]		= self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_mobilebert_for_masked_lm(*__a							)



       def 				_lowerCAmelCase							(						self				:				Optional[Any]							)					->Tuple:
          lowerCamelCase_						:   Union[str, Any]		= self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_mobilebert_for_multiple_choice(*__a							)



       def 				_lowerCAmelCase							(						self				:				Any							)					->List[Any]:
          lowerCamelCase_						:   Any		= self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_mobilebert_for_next_sequence_prediction(*__a							)



       def 				_lowerCAmelCase							(						self				:				Optional[int]							)					->str:
          lowerCamelCase_						:   List[str]		= self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_mobilebert_for_pretraining(*__a							)



       def 				_lowerCAmelCase							(						self				:				str							)					->Optional[Any]:
          lowerCamelCase_						:   int		= self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_mobilebert_for_question_answering(*__a							)



       def 				_lowerCAmelCase							(						self				:				List[str]							)					->int:
          lowerCamelCase_						:   Dict		= self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_mobilebert_for_sequence_classification(*__a							)




       def 				_lowerCAmelCase							(						self				:				List[Any]							)					->Union[str, Any]:
          lowerCamelCase_						:   Dict		= self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_mobilebert_for_token_classification(*__a							)







def    __lowerCamelCase   (      A__						: List[str]					)     ->    Optional[int]:
   return torch.tensor(
       A__						,						dtype=torch.long						,						device=A__						,						)


snake_case__				:	List[str]					       =					1e-3





@require_torch
@require_sentencepiece
@require_tokenizers
class   SCREAMING_SNAKE_CASE_			(unittest.TestCase						):




       '''simple docstring'''



       @slow
       def 				_lowerCAmelCase							(						self				:				List[Any]							)					->List[str]:
          lowerCamelCase_						:   Any		= MobileBertModel.from_pretrained("""google/mobilebert-uncased"""							).to(__a							)
          lowerCamelCase_						:   int		= _long_tensor([[101, 7_110, 1_005, 1_056, 2_023, 11_333, 17_413, 1_029, 102]]							)
          with torch.no_grad():
             lowerCamelCase_						:   Optional[Any]		= model(__a							)[0]
          lowerCamelCase_						:   Any		= torch.Size((1, 9, 512)							)
          self.assertEqual(output.shape		,				__a							)
          lowerCamelCase_						:   str		= torch.tensor(
              [
                  [
                      [-2.4_73_65_26e07, 8.2_69_16_56e04, 1.6_52_18_38e05],
                      [-5.7_54_17_04e-01, 3.9_05_60_22e00, 4.4_01_15_07e00],
                      [2.6_04_73_59e00, 1.5_67_76_52e00, -1.7_32_41_88e-01],
                  ]
              ]		,				device=__a		,				)

          # MobileBERT results range from 10e0 to 10e8. Even a 0.0000001% difference with a value of 10e8 results in a
          # ~1 difference, it's therefore not a good idea to measure using addition.
          # Here, we instead divide the expected result with the result in order to obtain ~1. We then check that the
          # result is held between bounds: 1 - TOLERANCE < expected_result / result < 1 + TOLERANCE
          lowerCamelCase_						:   str		= torch.all((expected_slice / output[..., :3, :3]) >= 1 - TOLERANCE							)
          lowerCamelCase_						:   Tuple		= torch.all((expected_slice / output[..., :3, :3]) <= 1 + TOLERANCE							)

          self.assertTrue(lower_bound and upper_bound							)





