





'''simple docstring'''






import argparse
import logging
import os
from datetime import datetime

import numpy as np
import torch
from torch import nn
from torch.utils.data import DataLoader, RandomSampler, TensorDataset
from tqdm import tqdm

from transformers import GPTaLMHeadModel


A   : List[Any]             =			logging.getLogger(__name__)





def       lowercase_      (		lowercase__				,  lowercase__						)   ->Optional[Any]:







						if os.path.exists(__UpperCAmelCase						):
												if os.path.exists(os.path.join(__UpperCAmelCase				,  'config.json'						)						) and os.path.isfile(
												    os.path.join(__UpperCAmelCase				,  'config.json'						)						):
																		os.remove(os.path.join(__UpperCAmelCase				,  'config.json'						)						)
												if os.path.exists(os.path.join(__UpperCAmelCase				,  'pytorch_model.bin'						)						) and os.path.isfile(
												    os.path.join(__UpperCAmelCase				,  'pytorch_model.bin'						)						):
																		os.remove(os.path.join(__UpperCAmelCase				,  'pytorch_model.bin'						)						)
						else:
												os.makedirs(__UpperCAmelCase						)
						model.save_pretrained(__UpperCAmelCase						)





def       lowercase_      (		lowercase__				,  lowercase__=False						)   ->List[Any]:
						_snake_case:   List[Any]  					=		2
						if unlogit:
												_snake_case:   int  					=		torch.pow(__UpperCAmelCase				,  __UpperCAmelCase						)
						_snake_case:   List[str]  					=		p * torch.log(__UpperCAmelCase						)
						_snake_case:   Any  					=		0
						return -plogp.sum(dim=-1						)





def       lowercase_      (		lowercase__						)   ->Optional[int]:
						logger.info('lv, h >\t' + '\t'.join(F'''{x + 1}''' for x in range(len(__UpperCAmelCase						)						)						)						)
						for row in range(len(__UpperCAmelCase						)						):
												if tensor.dtype != torch.long:
																		logger.info(F'''layer {row + 1}:\t''' + '\t'.join(F'''{x:.5f}''' for x in tensor[row].cpu().data						)						)
												else:
																		logger.info(F'''layer {row + 1}:\t''' + '\t'.join(F'''{x:d}''' for x in tensor[row].cpu().data						)						)





def       lowercase_      (		lowercase__				,  lowercase__				,  lowercase__				,  lowercase__=True				,  lowercase__=True				,  lowercase__=None				,  lowercase__=False						)   ->List[Any]:
						_snake_case					,						_snake_case:   List[Any]  					=		model.config.num_hidden_layers, model.config.num_attention_heads
						_snake_case:   Dict  					=		torch.zeros(__UpperCAmelCase				,  __UpperCAmelCase						).to(args.device						)
						_snake_case:   Dict  					=		torch.zeros(__UpperCAmelCase				,  __UpperCAmelCase						).to(args.device						)

						if head_mask is None:
												_snake_case:   Union[str, Any]  					=		torch.ones(__UpperCAmelCase				,  __UpperCAmelCase						).to(args.device						)

						head_mask.requires_grad_(requires_grad=__UpperCAmelCase						)
						# If actually pruned attention multi-head, set head mask to None to avoid shape mismatch
						if actually_pruned:
												_snake_case:   Any  					=		None

						_snake_case:   List[Any]  					=		0.0
						_snake_case:   Tuple  					=		0.0
						for step, inputs in enumerate(tqdm(__UpperCAmelCase				,  desc='Iteration'				,  disable=args.local_rank not in [-1, 0]						)						):
												_snake_case:   List[str]  					=		tuple(t.to(args.device						) for t in inputs						)
												((_snake_case     )					,						     ):   Optional[int]  					=		inputs

												# Do a forward pass (not with torch.no_grad() since we need gradients for importance score - see below)
												_snake_case:   Union[str, Any]  					=		model(__UpperCAmelCase				,  labels=__UpperCAmelCase				,  head_mask=__UpperCAmelCase						)
												#  (loss), lm_logits, presents, (all hidden_states), (attentions)
												_snake_case					,						_snake_case					,						_snake_case:   Optional[Any]  					=		(
												    outputs[0],
												    outputs[1],
												    outputs[-1],
												)  # Loss and logits are the first, attention the last
												loss.backward()  # Backpropagate to populate the gradients in the head mask
												total_loss += loss.detach().cpu().numpy()
												if compute_entropy:
																		for layer, attn in enumerate(__UpperCAmelCase						):
																								_snake_case:   List[Any]  					=		entropy(attn.detach()				,  __UpperCAmelCase						)
																								attn_entropy[layer] += masked_entropy.sum(-1						).sum(0						).sum(0						).detach()

												if compute_importance:
																		head_importance += head_mask.grad.abs().detach()
												tot_tokens += torch.ones_like(__UpperCAmelCase						).float().detach().sum().data

						# Normalize
						attn_entropy /= tot_tokens
						head_importance /= tot_tokens
						# Layerwise importance normalization
						if not args.dont_normalize_importance_by_layer:
												_snake_case:   List[str]  					=		2
												_snake_case:   str  					=		torch.pow(torch.pow(__UpperCAmelCase				,  __UpperCAmelCase						).sum(-1						)				,  1 / exponent						)
												head_importance /= norm_by_layer.unsqueeze(-1						) + 1e-20

						if not args.dont_normalize_global_importance:
												_snake_case:   List[str]  					=		(head_importance - head_importance.min()) / (head_importance.max() - head_importance.min())

						# Print matrices
						if compute_entropy:
												logger.info('Attention entropies'						)
												print_ad_tensor(__UpperCAmelCase						)
						if compute_importance:
												logger.info('Head importance scores'						)
												print_ad_tensor(__UpperCAmelCase						)
						logger.info('Head ranked by importance scores'						)
						_snake_case:   List[str]  					=		torch.zeros(head_importance.numel()				,  dtype=torch.long				,  device=args.device						)
						_snake_case:   List[Any]  					=		torch.arange(
						    head_importance.numel()				,  device=args.device						)
						_snake_case:   Any  					=		head_ranks.view_as(__UpperCAmelCase						)
						print_ad_tensor(__UpperCAmelCase						)
						return attn_entropy, head_importance, total_loss





def       lowercase_      (		lowercase__				,  lowercase__				,  lowercase__						)   ->Optional[Any]:
						_snake_case					,						_snake_case					,						_snake_case:   int  					=		compute_heads_importance(__UpperCAmelCase				,  __UpperCAmelCase				,  __UpperCAmelCase				,  compute_entropy=__UpperCAmelCase						)
						_snake_case:   List[str]  					=		1 / loss  # instead of downsteam score use the LM loss
						logger.info('Pruning: original score: %f, threshold: %f'				,  __UpperCAmelCase				,  original_score * args.masking_threshold						)

						_snake_case:   str  					=		torch.ones_like(__UpperCAmelCase						)
						_snake_case:   Optional[Any]  					=		max(1				,  int(new_head_mask.numel() * args.masking_amount						)						)

						_snake_case:   Optional[int]  					=		original_score
						while current_score >= original_score * args.masking_threshold:
												_snake_case:   Optional[Any]  					=		new_head_mask.clone().detach()  # save current head mask
												# heads from least important to most - keep only not-masked heads
												_snake_case:   int  					=		float('Inf'						)
												_snake_case:   Any  					=		head_importance.view(-1						).sort()[1]

												if len(__UpperCAmelCase						) <= num_to_mask:
																		print('BREAK BY num_to_mask'						)
																		break

												# mask heads
												_snake_case:   List[str]  					=		current_heads_to_mask[:num_to_mask]
												logger.info('Heads to mask: %s'				,  str(current_heads_to_mask.tolist()						)						)
												_snake_case:   int  					=		new_head_mask.view(-1						)
												_snake_case:   List[Any]  					=		0.0
												_snake_case:   List[str]  					=		new_head_mask.view_as(__UpperCAmelCase						)
												_snake_case:   List[str]  					=		new_head_mask.clone().detach()
												print_ad_tensor(__UpperCAmelCase						)

												# Compute metric and head importance again
												_snake_case					,						_snake_case					,						_snake_case:   List[Any]  					=		compute_heads_importance(
												    __UpperCAmelCase				,  __UpperCAmelCase				,  __UpperCAmelCase				,  compute_entropy=__UpperCAmelCase				,  head_mask=__UpperCAmelCase						)
												_snake_case:   Tuple  					=		1 / loss
												logger.info(
												    'Masking: current score: %f, remaining heads %d (%.1f percents)'				,  __UpperCAmelCase				,  new_head_mask.sum()				,  new_head_mask.sum() / new_head_mask.numel() * 100				,  )

						logger.info('Final head mask'						)
						print_ad_tensor(__UpperCAmelCase						)
						np.save(os.path.join(args.output_dir				,  'head_mask.npy'						)				,  head_mask.detach().cpu().numpy()						)

						return head_mask





def       lowercase_      (		lowercase__				,  lowercase__				,  lowercase__				,  lowercase__						)   ->List[Any]:
						_snake_case:   List[str]  					=		datetime.now()
						_snake_case					,						_snake_case					,						_snake_case:   Dict  					=		compute_heads_importance(
						    __UpperCAmelCase				,  __UpperCAmelCase				,  __UpperCAmelCase				,  compute_entropy=__UpperCAmelCase				,  compute_importance=__UpperCAmelCase				,  head_mask=__UpperCAmelCase						)
						_snake_case:   List[str]  					=		1 / loss
						_snake_case:   Optional[int]  					=		datetime.now() - before_time

						_snake_case:   List[str]  					=		sum(p.numel() for p in model.parameters()						)
						_snake_case:   Dict  					=		{
						    layer: (1 - head_mask[layer].long()).nonzero().squeeze().tolist() for layer in range(len(__UpperCAmelCase						)						)
						}

						for k, v in heads_to_prune.items():
												if isinstance(__UpperCAmelCase				,  __UpperCAmelCase						):
																		_snake_case:   Dict  					=		[
																		    v,
																		]

						assert sum(len(__UpperCAmelCase						) for h in heads_to_prune.values()						) == (1 - head_mask.long()).sum().item()
						model.prune_heads(__UpperCAmelCase						)
						_snake_case:   Optional[Any]  					=		sum(p.numel() for p in model.parameters()						)

						_snake_case:   Union[str, Any]  					=		datetime.now()
						_snake_case					,						_snake_case					,						_snake_case:   List[str]  					=		compute_heads_importance(
						    __UpperCAmelCase				,  __UpperCAmelCase				,  __UpperCAmelCase				,  compute_entropy=__UpperCAmelCase				,  compute_importance=__UpperCAmelCase				,  head_mask=__UpperCAmelCase				,  actually_pruned=__UpperCAmelCase				,  )

						_snake_case:   List[str]  					=		1 / loss
						_snake_case:   Any  					=		datetime.now() - before_time

						logger.info(
						    'Pruning: original num of params: %.2e, after pruning %.2e (%.1f percents)'				,  __UpperCAmelCase				,  __UpperCAmelCase				,  pruned_num_params / original_num_params * 100				,  )
						logger.info('Pruning: score with masking: %f score with pruning: %f'				,  __UpperCAmelCase				,  __UpperCAmelCase						)
						logger.info('Pruning: speed ratio (original timing / new timing): %f percents'				,  original_time / new_time * 100						)
						save_model(__UpperCAmelCase				,  args.output_dir						)





def       lowercase_      (		)   ->Any:
						_snake_case:   Dict  					=		argparse.ArgumentParser()
						# Required parameters
						parser.add_argument(
						    '--data_dir'				,  default=__UpperCAmelCase				,  type=__UpperCAmelCase				,  required=__UpperCAmelCase				,  help='The input data dir. Should contain the .tsv files (or other data files) for the task.'				,  )
						parser.add_argument(
						    '--model_name_or_path'				,  default=__UpperCAmelCase				,  type=__UpperCAmelCase				,  required=__UpperCAmelCase				,  help='Path to pretrained model or model identifier from huggingface.co/models'				,  )
						parser.add_argument(
						    '--output_dir'				,  default=__UpperCAmelCase				,  type=__UpperCAmelCase				,  required=__UpperCAmelCase				,  help='The output directory where the model predictions and checkpoints will be written.'				,  )

						# Other parameters
						parser.add_argument(
						    '--config_name'				,  default=''				,  type=__UpperCAmelCase				,  help='Pretrained config name or path if not the same as model_name_or_path'				,  )
						parser.add_argument(
						    '--tokenizer_name'				,  default=''				,  type=__UpperCAmelCase				,  help='Pretrained tokenizer name or path if not the same as model_name_or_path'				,  )
						parser.add_argument(
						    '--cache_dir'				,  default=__UpperCAmelCase				,  type=__UpperCAmelCase				,  help='Where do you want to store the pre-trained models downloaded from s3'				,  )
						parser.add_argument(
						    '--data_subset'				,  type=__UpperCAmelCase				,  default=-1				,  help='If > 0: limit the data to a subset of data_subset instances.'						)
						parser.add_argument(
						    '--overwrite_output_dir'				,  action='store_true'				,  help='Whether to overwrite data in output directory'						)
						parser.add_argument(
						    '--overwrite_cache'				,  action='store_true'				,  help='Overwrite the cached training and evaluation sets'						)

						parser.add_argument(
						    '--dont_normalize_importance_by_layer'				,  action='store_true'				,  help='Don\'t normalize importance score by layers'						)
						parser.add_argument(
						    '--dont_normalize_global_importance'				,  action='store_true'				,  help='Don\'t normalize all importance scores between 0 and 1'				,  )

						parser.add_argument(
						    '--try_masking'				,  action='store_true'				,  help='Whether to try to mask head until a threshold of accuracy.'						)
						parser.add_argument(
						    '--masking_threshold'				,  default=0.9				,  type=__UpperCAmelCase				,  help='masking threshold in term of metrics (stop masking when metric < threshold * original metric value).'				,  )
						parser.add_argument(
						    '--masking_amount'				,  default=0.1				,  type=__UpperCAmelCase				,  help='Amount to heads to masking at each masking step.'						)
						parser.add_argument('--metric_name'				,  default='acc'				,  type=__UpperCAmelCase				,  help='Metric to use for head masking.'						)

						parser.add_argument(
						    '--max_seq_length'				,  default=128				,  type=__UpperCAmelCase				,  help=(
						        'The maximum total input sequence length after WordPiece tokenization. \n'
						        'Sequences longer than this will be truncated, sequences shorter padded.'
						    )				,  )
						parser.add_argument('--batch_size'				,  default=1				,  type=__UpperCAmelCase				,  help='Batch size.'						)

						parser.add_argument('--seed'				,  type=__UpperCAmelCase				,  default=42						)
						parser.add_argument('--local_rank'				,  type=__UpperCAmelCase				,  default=-1				,  help='local_rank for distributed training on gpus'						)
						parser.add_argument('--no_cuda'				,  action='store_true'				,  help='Whether not to use CUDA when available'						)
						parser.add_argument('--server_ip'				,  type=__UpperCAmelCase				,  default=''				,  help='Can be used for distant debugging.'						)
						parser.add_argument('--server_port'				,  type=__UpperCAmelCase				,  default=''				,  help='Can be used for distant debugging.'						)
						_snake_case:   Optional[int]  					=		parser.parse_args()

						if args.server_ip and args.server_port:
												# Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script
												import ptvsd

												print('Waiting for debugger attach'						)
												ptvsd.enable_attach(address=(args.server_ip, args.server_port)				,  redirect_output=__UpperCAmelCase						)
												ptvsd.wait_for_attach()

						# Setup devices and distributed training
						if args.local_rank == -1 or args.no_cuda:
												_snake_case:   List[str]  					=		torch.device('cuda' if torch.cuda.is_available() and not args.no_cuda else 'cpu'						)
												_snake_case:   str  					=		0 if args.no_cuda else torch.cuda.device_count()
						else:
												torch.cuda.set_device(args.local_rank						)
												_snake_case:   Optional[int]  					=		torch.device('cuda'				,  args.local_rank						)
												_snake_case:   int  					=		1
												torch.distributed.init_process_group(backend='nccl'						)  # Initializes the distributed backend

						# Setup logging
						logging.basicConfig(level=logging.INFO if args.local_rank in [-1, 0] else logging.WARN						)
						logger.info('device: {} n_gpu: {}, distributed: {}'.format(args.device				,  args.n_gpu				,  bool(args.local_rank != -1						)						)						)

						_snake_case:   Dict  					=		GPTaLMHeadModel.from_pretrained(args.model_name_or_path						)

						# Distributed and parallel training
						model.to(args.device						)
						if args.local_rank != -1:
												_snake_case:   Optional[int]  					=		nn.parallel.DistributedDataParallel(
												    __UpperCAmelCase				,  device_ids=[args.local_rank]				,  output_device=args.local_rank				,  find_unused_parameters=__UpperCAmelCase						)
						elif args.n_gpu > 1:
												_snake_case:   Optional[Any]  					=		nn.DataParallel(__UpperCAmelCase						)

						# Print/save training arguments
						os.makedirs(args.output_dir				,  exist_ok=__UpperCAmelCase						)
						torch.save(__UpperCAmelCase				,  os.path.join(args.output_dir				,  'run_args.bin'						)						)
						logger.info('Training/evaluation parameters %s'				,  __UpperCAmelCase						)

						# Prepare dataset
						_snake_case:   Tuple  					=		np.concatenate(
						    [
						        np.loadtxt(args.data_dir				,  dtype=np.intaa						),
						    ]						)
						_snake_case:   Dict  					=		(torch.from_numpy(__UpperCAmelCase						),)
						_snake_case:   List[str]  					=		TensorDataset(*__UpperCAmelCase						)
						_snake_case:   Dict  					=		RandomSampler(__UpperCAmelCase						)
						_snake_case:   str  					=		DataLoader(__UpperCAmelCase				,  sampler=__UpperCAmelCase				,  batch_size=args.batch_size						)

						# Compute head entropy and importance score
						compute_heads_importance(__UpperCAmelCase				,  __UpperCAmelCase				,  __UpperCAmelCase						)

						# Try head masking (set heads to zero until the score goes under a threshole)
						# and head pruning (remove masked heads and see the effect on the network)
						if args.try_masking and args.masking_threshold > 0.0 and args.masking_threshold < 1.0:
												_snake_case:   List[Any]  					=		mask_heads(__UpperCAmelCase				,  __UpperCAmelCase				,  __UpperCAmelCase						)
												prune_heads(__UpperCAmelCase				,  __UpperCAmelCase				,  __UpperCAmelCase				,  __UpperCAmelCase						)


if __name__ == "__main__":
		main()









'''simple docstring'''






from __future__ import annotations

import unittest

from transformers import MobileBertConfig, is_tf_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_tf, slow

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


if is_tf_available():
		import tensorflow as tf

		from transformers import (
		    TF_MODEL_FOR_PRETRAINING_MAPPING,
		    TFMobileBertForMaskedLM,
		    TFMobileBertForMultipleChoice,
		    TFMobileBertForNextSentencePrediction,
		    TFMobileBertForPreTraining,
		    TFMobileBertForQuestionAnswering,
		    TFMobileBertForSequenceClassification,
		    TFMobileBertForTokenClassification,
		    TFMobileBertModel,
		)







@require_tf
class 			lowerCamelCase					(						__UpperCAmelCase     ,							__UpperCAmelCase     ,							unittest.TestCase  ):
					_SCREAMING_SNAKE_CASE							   =    (
					    (
					        TFMobileBertModel,
					        TFMobileBertForMaskedLM,
					        TFMobileBertForNextSentencePrediction,
					        TFMobileBertForPreTraining,
					        TFMobileBertForQuestionAnswering,
					        TFMobileBertForSequenceClassification,
					        TFMobileBertForTokenClassification,
					        TFMobileBertForMultipleChoice,
					    )
					    if is_tf_available()
					    else ()
					)
					_SCREAMING_SNAKE_CASE							   =    (
					    {
					        "feature-extraction": TFMobileBertModel,
					        "fill-mask": TFMobileBertForMaskedLM,
					        "question-answering": TFMobileBertForQuestionAnswering,
					        "text-classification": TFMobileBertForSequenceClassification,
					        "token-classification": TFMobileBertForTokenClassification,
					        "zero-shot": TFMobileBertForSequenceClassification,
					    }
					    if is_tf_available()
					    else {}
					)
					_SCREAMING_SNAKE_CASE							   =    False
					_SCREAMING_SNAKE_CASE							   =    False


					def    SCREAMING_SNAKE_CASE_		(					self	:  Union[str, Any]       ,     __snake_case	:  Optional[int]       ,     __snake_case	:  List[Any]       ,     __snake_case	:  Optional[int]=False       ):





											'''simple docstring'''





											_snake_case:   Dict  					=		super()._prepare_for_class(__snake_case       ,     __snake_case       ,     return_labels=__snake_case       )

											if return_labels:
																	if model_class in get_values(__snake_case       ):
																							_snake_case:   List[str]  					=		tf.zeros(self.model_tester.batch_size       ,     dtype=tf.intaa       )

											return inputs_dict







					class 			lowerCamelCase					(						__UpperCAmelCase  ):


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





																'''simple docstring'''





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


										def    SCREAMING_SNAKE_CASE_		(					self	:  List[Any]       ):





																'''simple docstring'''





																_snake_case:   int  					=		ids_tensor([self.batch_size, self.seq_length]       ,     self.vocab_size       )

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

																_snake_case:   List[str]  					=		None
																if self.use_token_type_ids:
																						_snake_case:   Dict  					=		ids_tensor([self.batch_size, self.seq_length]       ,     self.type_vocab_size       )

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

																_snake_case:   str  					=		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       ,     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       ,     embedding_size=self.embedding_size       ,     )

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


										def    SCREAMING_SNAKE_CASE_		(					self	:  int       ,     __snake_case	:  int       ,     __snake_case	:  Optional[Any]       ,     __snake_case	:  Optional[int]       ,     __snake_case	:  int       ,     __snake_case	:  List[str]       ,     __snake_case	:  List[Any]       ,     __snake_case	:  List[str]       ):





																'''simple docstring'''





																_snake_case:   int  					=		TFMobileBertModel(config=__snake_case       )
																_snake_case:   str  					=		{'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids}
																_snake_case:   List[str]  					=		model(__snake_case       )

																_snake_case:   List[str]  					=		[input_ids, input_mask]
																_snake_case:   Dict  					=		model(__snake_case       )

																_snake_case:   List[str]  					=		model(__snake_case       )

																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    SCREAMING_SNAKE_CASE_		(					self	:  str       ,     __snake_case	:  int       ,     __snake_case	:  str       ,     __snake_case	:  List[str]       ,     __snake_case	:  Dict       ,     __snake_case	:  str       ,     __snake_case	:  Tuple       ,     __snake_case	:  List[str]       ):





																'''simple docstring'''





																_snake_case:   str  					=		TFMobileBertForMaskedLM(config=__snake_case       )
																_snake_case:   Optional[Any]  					=		{'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids}
																_snake_case:   Optional[int]  					=		model(__snake_case       )
																self.parent.assertEqual(result.logits.shape       ,     (self.batch_size, self.seq_length, self.vocab_size)       )


										def    SCREAMING_SNAKE_CASE_		(					self	:  Optional[int]       ,     __snake_case	:  int       ,     __snake_case	:  List[str]       ,     __snake_case	:  List[str]       ,     __snake_case	:  Optional[int]       ,     __snake_case	:  Optional[Any]       ,     __snake_case	:  int       ,     __snake_case	:  str       ):





																'''simple docstring'''





																_snake_case:   Union[str, Any]  					=		TFMobileBertForNextSentencePrediction(config=__snake_case       )
																_snake_case:   List[str]  					=		{'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids}
																_snake_case:   List[str]  					=		model(__snake_case       )
																self.parent.assertEqual(result.logits.shape       ,     (self.batch_size, 2)       )


										def    SCREAMING_SNAKE_CASE_		(					self	:  int       ,     __snake_case	:  Tuple       ,     __snake_case	:  Tuple       ,     __snake_case	:  Tuple       ,     __snake_case	:  Dict       ,     __snake_case	:  List[str]       ,     __snake_case	:  Union[str, Any]       ,     __snake_case	:  List[Any]       ):





																'''simple docstring'''





																_snake_case:   str  					=		TFMobileBertForPreTraining(config=__snake_case       )
																_snake_case:   str  					=		{'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids}
																_snake_case:   List[str]  					=		model(__snake_case       )
																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    SCREAMING_SNAKE_CASE_		(					self	:  Optional[Any]       ,     __snake_case	:  Optional[Any]       ,     __snake_case	:  Dict       ,     __snake_case	:  Dict       ,     __snake_case	:  int       ,     __snake_case	:  Any       ,     __snake_case	:  Union[str, Any]       ,     __snake_case	:  Optional[int]       ):





																'''simple docstring'''





																_snake_case:   int  					=		self.num_labels
																_snake_case:   Tuple  					=		TFMobileBertForSequenceClassification(config=__snake_case       )
																_snake_case:   Optional[Any]  					=		{'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids}
																_snake_case:   List[Any]  					=		model(__snake_case       )
																self.parent.assertEqual(result.logits.shape       ,     (self.batch_size, self.num_labels)       )


										def    SCREAMING_SNAKE_CASE_		(					self	:  Any       ,     __snake_case	:  List[Any]       ,     __snake_case	:  Any       ,     __snake_case	:  Dict       ,     __snake_case	:  Dict       ,     __snake_case	:  Dict       ,     __snake_case	:  Union[str, Any]       ,     __snake_case	:  List[str]       ):





																'''simple docstring'''





																_snake_case:   Tuple  					=		self.num_choices
																_snake_case:   Optional[int]  					=		TFMobileBertForMultipleChoice(config=__snake_case       )
																_snake_case:   str  					=		tf.tile(tf.expand_dims(__snake_case       ,     1       )       ,     (1, self.num_choices, 1)       )
																_snake_case:   Union[str, Any]  					=		tf.tile(tf.expand_dims(__snake_case       ,     1       )       ,     (1, self.num_choices, 1)       )
																_snake_case:   Optional[int]  					=		tf.tile(tf.expand_dims(__snake_case       ,     1       )       ,     (1, self.num_choices, 1)       )
																_snake_case:   Optional[Any]  					=		{
																    'input_ids': multiple_choice_inputs_ids,
																    'attention_mask': multiple_choice_input_mask,
																    'token_type_ids': multiple_choice_token_type_ids,
																}
																_snake_case:   Optional[Any]  					=		model(__snake_case       )
																self.parent.assertEqual(result.logits.shape       ,     (self.batch_size, self.num_choices)       )


										def    SCREAMING_SNAKE_CASE_		(					self	:  int       ,     __snake_case	:  str       ,     __snake_case	:  List[Any]       ,     __snake_case	:  Any       ,     __snake_case	:  List[Any]       ,     __snake_case	:  Union[str, Any]       ,     __snake_case	:  Optional[int]       ,     __snake_case	:  Optional[Any]       ):





																'''simple docstring'''





																_snake_case:   Tuple  					=		self.num_labels
																_snake_case:   Dict  					=		TFMobileBertForTokenClassification(config=__snake_case       )
																_snake_case:   str  					=		{'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids}
																_snake_case:   Tuple  					=		model(__snake_case       )
																self.parent.assertEqual(result.logits.shape       ,     (self.batch_size, self.seq_length, self.num_labels)       )


										def    SCREAMING_SNAKE_CASE_		(					self	:  Union[str, Any]       ,     __snake_case	:  Any       ,     __snake_case	:  Tuple       ,     __snake_case	:  Dict       ,     __snake_case	:  int       ,     __snake_case	:  Dict       ,     __snake_case	:  Dict       ,     __snake_case	:  Any       ):





																'''simple docstring'''





																_snake_case:   int  					=		TFMobileBertForQuestionAnswering(config=__snake_case       )
																_snake_case:   Any  					=		{'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids}
																_snake_case:   Union[str, Any]  					=		model(__snake_case       )
																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    SCREAMING_SNAKE_CASE_		(					self	:  Optional[int]       ):





																'''simple docstring'''





																_snake_case:   str  					=		self.prepare_config_and_inputs()
																(
																    (
																    _snake_case
																)					,						(
																    _snake_case
																)					,						(
																    _snake_case
																)					,						(
																    _snake_case
																)					,						(
																    _snake_case
																)					,						(
																    _snake_case
																)					,						(
																    _snake_case
																)					,						
																):   Any  					=		config_and_inputs
																_snake_case:   str  					=		{'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask}
																return config, inputs_dict





					def    SCREAMING_SNAKE_CASE_		(					self	:  Dict       ):





											'''simple docstring'''





											_snake_case:   int  					=		TFMobileBertModelTest.TFMobileBertModelTester(self       )
											_snake_case:   Dict  					=		ConfigTester(self       ,     config_class=__snake_case       ,     hidden_size=37       )


					def    SCREAMING_SNAKE_CASE_		(					self	:  Dict       ):





											'''simple docstring'''





											self.config_tester.run_common_tests()


					def    SCREAMING_SNAKE_CASE_		(					self	:  List[Any]       ):





											'''simple docstring'''





											_snake_case:   Optional[Any]  					=		self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_mobilebert_model(*__snake_case       )


					def    SCREAMING_SNAKE_CASE_		(					self	:  Optional[Any]       ):





											'''simple docstring'''





											_snake_case:   Optional[int]  					=		self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_mobilebert_for_masked_lm(*__snake_case       )


					def    SCREAMING_SNAKE_CASE_		(					self	:  Union[str, Any]       ):





											'''simple docstring'''





											_snake_case:   Optional[Any]  					=		self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_mobilebert_for_multiple_choice(*__snake_case       )


					def    SCREAMING_SNAKE_CASE_		(					self	:  Optional[Any]       ):





											'''simple docstring'''





											_snake_case:   Any  					=		self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_mobilebert_for_next_sequence_prediction(*__snake_case       )


					def    SCREAMING_SNAKE_CASE_		(					self	:  Tuple       ):





											'''simple docstring'''





											_snake_case:   List[Any]  					=		self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_mobilebert_for_pretraining(*__snake_case       )


					def    SCREAMING_SNAKE_CASE_		(					self	:  List[str]       ):





											'''simple docstring'''





											_snake_case:   Union[str, Any]  					=		self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_mobilebert_for_question_answering(*__snake_case       )


					def    SCREAMING_SNAKE_CASE_		(					self	:  Dict       ):





											'''simple docstring'''





											_snake_case:   Dict  					=		self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_mobilebert_for_sequence_classification(*__snake_case       )


					def    SCREAMING_SNAKE_CASE_		(					self	:  List[str]       ):





											'''simple docstring'''





											_snake_case:   Any  					=		self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_mobilebert_for_token_classification(*__snake_case       )




					@slow
					def    SCREAMING_SNAKE_CASE_		(					self	:  Tuple       ):





											'''simple docstring'''





											for model_name in ["google/mobilebert-uncased"]:
																	_snake_case:   Optional[Any]  					=		TFMobileBertModel.from_pretrained(__snake_case       )
																	self.assertIsNotNone(__snake_case       )







@require_tf
class 			lowerCamelCase					(						unittest.TestCase  ):


					@slow
					def    SCREAMING_SNAKE_CASE_		(					self	:  int       ):





											'''simple docstring'''





											_snake_case:   Optional[Any]  					=		TFMobileBertForPreTraining.from_pretrained('google/mobilebert-uncased'       )
											_snake_case:   Any  					=		tf.constant([[0, 1, 2, 3, 4, 5]]       )
											_snake_case:   Optional[Any]  					=		model(__snake_case       )[0]

											_snake_case:   str  					=		[1, 6, 3_05_22]
											self.assertEqual(output.shape       ,     __snake_case       )

											_snake_case:   int  					=		tf.constant(
											    [
											        [
											            [-4.5_919_547, -9.248_295, -9.645_256],
											            [-6.7_306_175, -6.440_284, -6.6_052_837],
											            [-7.2_743_506, -6.7_847_915, -6.024_673],
											        ]
											    ]       )
											tf.debugging.assert_near(output[:, :3, :3]       ,     __snake_case       ,     atol=1e-4       )





