






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, SequentialSampler, Subset
from torch.utils.data.distributed import DistributedSampler
from tqdm import tqdm

import transformers
from transformers import (
    AutoConfig,
    AutoModelForSequenceClassification,
    AutoTokenizer,
    GlueDataset,
    default_data_collator,
    glue_compute_metrics,
    glue_output_modes,
    glue_processors,
    set_seed,
)
from transformers.trainer_utils import is_main_process


__A       :					Optional[Any]     					=     logging.getLogger(__name__)





def 		__SCREAMING_SNAKE_CASE						(       UpperCamelCase__				)						->       Optional[int]:







			'''simple docstring'''

			UpperCAmelCase     	=       p * torch.log(UpperCamelCase__				)
			UpperCAmelCase     	=       0
			return -plogp.sum(dim=-1				)





def 		__SCREAMING_SNAKE_CASE						(       UpperCamelCase__				)						->       Optional[Any]:







			'''simple docstring'''

			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 		__SCREAMING_SNAKE_CASE						(       UpperCamelCase__    ,    UpperCamelCase__    ,    UpperCamelCase__    ,    UpperCamelCase__=True    ,    UpperCamelCase__=True    ,    UpperCamelCase__=None    ,    UpperCamelCase__=False				)						->       Dict:







			'''simple docstring'''

			UpperCAmelCase	,    UpperCAmelCase     	=       model.config.num_hidden_layers, model.config.num_attention_heads
			UpperCAmelCase     	=       torch.zeros(UpperCamelCase__    ,    UpperCamelCase__				).to(args.device				)
			UpperCAmelCase     	=       torch.zeros(UpperCamelCase__    ,    UpperCamelCase__				).to(args.device				)

			if head_mask is None:
						UpperCAmelCase     	=       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:
						UpperCAmelCase     	=       None

			UpperCAmelCase     	=       None
			UpperCAmelCase     	=       None
			UpperCAmelCase     	=       0.0

			for step, inputs in enumerate(tqdm(UpperCamelCase__    ,    desc='''Iteration'''    ,    disable=args.local_rank not in [-1, 0]				)				):
						for k, v in inputs.items():
									UpperCAmelCase     	=       v.to(args.device				)

						# Do a forward pass (not with torch.no_grad() since we need gradients for importance score - see below)
						UpperCAmelCase     	=       model(**UpperCamelCase__    ,    head_mask=UpperCamelCase__				)
						UpperCAmelCase	,    UpperCAmelCase	,    UpperCAmelCase     	=       (
						    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

						if compute_entropy:
									for layer, attn in enumerate(UpperCamelCase__				):
												UpperCAmelCase     	=       entropy(attn.detach()				) * inputs['''attention_mask'''].float().unsqueeze(1				)
												attn_entropy[layer] += masked_entropy.sum(-1				).sum(0				).detach()

						if compute_importance:
									head_importance += head_mask.grad.abs().detach()

						# Also store our logits/labels if we want to compute metrics afterwards
						if preds is None:
									UpperCAmelCase     	=       logits.detach().cpu().numpy()
									UpperCAmelCase     	=       inputs['''labels'''].detach().cpu().numpy()
						else:
									UpperCAmelCase     	=       np.append(UpperCamelCase__    ,    logits.detach().cpu().numpy()    ,    axis=0				)
									UpperCAmelCase     	=       np.append(UpperCamelCase__    ,    inputs['''labels'''].detach().cpu().numpy()    ,    axis=0				)

						tot_tokens += inputs["attention_mask"].float().detach().sum().data

			# Normalize
			attn_entropy /= tot_tokens
			head_importance /= tot_tokens
			# Layerwise importance normalization
			if not args.dont_normalize_importance_by_layer:
						UpperCAmelCase     	=       2
						UpperCAmelCase     	=       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:
						UpperCAmelCase     	=       (head_importance - head_importance.min()) / (head_importance.max() - head_importance.min())

			# Print/save matrices
			np.save(os.path.join(args.output_dir    ,    '''attn_entropy.npy'''				)    ,    attn_entropy.detach().cpu().numpy()				)
			np.save(os.path.join(args.output_dir    ,    '''head_importance.npy'''				)    ,    head_importance.detach().cpu().numpy()				)

			logger.info('''Attention entropies'''				)
			print_ad_tensor(UpperCamelCase__				)
			logger.info('''Head importance scores'''				)
			print_ad_tensor(UpperCamelCase__				)
			logger.info('''Head ranked by importance scores'''				)
			UpperCAmelCase     	=       torch.zeros(head_importance.numel()    ,    dtype=torch.long    ,    device=args.device				)
			UpperCAmelCase     	=       torch.arange(
			    head_importance.numel()    ,    device=args.device				)
			UpperCAmelCase     	=       head_ranks.view_as(UpperCamelCase__				)
			print_ad_tensor(UpperCamelCase__				)

			return attn_entropy, head_importance, preds, labels





def 		__SCREAMING_SNAKE_CASE						(       UpperCamelCase__    ,    UpperCamelCase__    ,    UpperCamelCase__				)						->       Tuple:







			'''simple docstring'''

			UpperCAmelCase	,    UpperCAmelCase	,    UpperCAmelCase	,    UpperCAmelCase     	=       compute_heads_importance(UpperCamelCase__    ,    UpperCamelCase__    ,    UpperCamelCase__    ,    compute_entropy=UpperCamelCase__				)
			UpperCAmelCase     	=       np.argmax(UpperCamelCase__    ,    axis=1				) if args.output_mode == '''classification''' else np.squeeze(UpperCamelCase__				)
			UpperCAmelCase     	=       glue_compute_metrics(args.task_name    ,    UpperCamelCase__    ,    UpperCamelCase__				)[args.metric_name]
			logger.info('''Pruning: original score: %f, threshold: %f'''    ,    UpperCamelCase__    ,    original_score * args.masking_threshold				)

			UpperCAmelCase     	=       torch.ones_like(UpperCamelCase__				)
			UpperCAmelCase     	=       max(1    ,    int(new_head_mask.numel() * args.masking_amount				)				)

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

						if len(UpperCamelCase__				) <= num_to_mask:
									break

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

						# Compute metric and head importance again
						UpperCAmelCase	,    UpperCAmelCase	,    UpperCAmelCase	,    UpperCAmelCase     	=       compute_heads_importance(
						    UpperCamelCase__    ,    UpperCamelCase__    ,    UpperCamelCase__    ,    compute_entropy=UpperCamelCase__    ,    head_mask=UpperCamelCase__				)
						UpperCAmelCase     	=       np.argmax(UpperCamelCase__    ,    axis=1				) if args.output_mode == '''classification''' else np.squeeze(UpperCamelCase__				)
						UpperCAmelCase     	=       glue_compute_metrics(args.task_name    ,    UpperCamelCase__    ,    UpperCamelCase__				)[args.metric_name]
						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 		__SCREAMING_SNAKE_CASE						(       UpperCamelCase__    ,    UpperCamelCase__    ,    UpperCamelCase__    ,    UpperCamelCase__				)						->       int:







			'''simple docstring'''

			UpperCAmelCase     	=       datetime.now()
			UpperCAmelCase	,    UpperCAmelCase	,    UpperCAmelCase	,    UpperCAmelCase     	=       compute_heads_importance(
			    UpperCamelCase__    ,    UpperCamelCase__    ,    UpperCamelCase__    ,    compute_entropy=UpperCamelCase__    ,    compute_importance=UpperCamelCase__    ,    head_mask=UpperCamelCase__				)
			UpperCAmelCase     	=       np.argmax(UpperCamelCase__    ,    axis=1				) if args.output_mode == '''classification''' else np.squeeze(UpperCamelCase__				)
			UpperCAmelCase     	=       glue_compute_metrics(args.task_name    ,    UpperCamelCase__    ,    UpperCamelCase__				)[args.metric_name]
			UpperCAmelCase     	=       datetime.now() - before_time

			UpperCAmelCase     	=       sum(p.numel() for p in model.parameters()				)
			UpperCAmelCase     	=       {
			    layer: (1 - head_mask[layer].long()).nonzero().squeeze().tolist() for layer in range(len(UpperCamelCase__				)				)
			}

			assert sum(len(UpperCamelCase__				) for h in heads_to_prune.values()				) == (1 - head_mask.long()).sum().item()
			model.prune_heads(UpperCamelCase__				)
			UpperCAmelCase     	=       sum(p.numel() for p in model.parameters()				)

			UpperCAmelCase     	=       datetime.now()
			UpperCAmelCase	,    UpperCAmelCase	,    UpperCAmelCase	,    UpperCAmelCase     	=       compute_heads_importance(
			    UpperCamelCase__    ,    UpperCamelCase__    ,    UpperCamelCase__    ,    compute_entropy=UpperCamelCase__    ,    compute_importance=UpperCamelCase__    ,    head_mask=UpperCamelCase__    ,    actually_pruned=UpperCamelCase__    ,    )
			UpperCAmelCase     	=       np.argmax(UpperCamelCase__    ,    axis=1				) if args.output_mode == '''classification''' else np.squeeze(UpperCamelCase__				)
			UpperCAmelCase     	=       glue_compute_metrics(args.task_name    ,    UpperCamelCase__    ,    UpperCamelCase__				)[args.metric_name]
			UpperCAmelCase     	=       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 (new timing / original timing): %f percents'''    ,    original_time / new_time * 100				)





def 		__SCREAMING_SNAKE_CASE						(       )						->       str:







			'''simple docstring'''

			UpperCAmelCase     	=       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(
			    '''--task_name'''    ,    default=UpperCamelCase__    ,    type=UpperCamelCase__    ,    required=UpperCamelCase__    ,    help='''The name of the task to train selected in the list: ''' + ''', '''.join(glue_processors.keys()				)    ,    )
			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 huggingface.co'''    ,    )
			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.'''				)
			UpperCAmelCase     	=       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:
						UpperCAmelCase     	=       torch.device('''cuda''' if torch.cuda.is_available() and not args.no_cuda else '''cpu'''				)
						UpperCAmelCase     	=       0 if args.no_cuda else torch.cuda.device_count()
			else:
						torch.cuda.set_device(args.local_rank				)
						UpperCAmelCase     	=       torch.device('''cuda'''    ,    args.local_rank				)
						UpperCAmelCase     	=       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				)				)				)
			# Set the verbosity to info of the Transformers logger (on main process only):
			if is_main_process(args.local_rank				):
						transformers.utils.logging.set_verbosity_info()
						transformers.utils.logging.enable_default_handler()
						transformers.utils.logging.enable_explicit_format()

			# Set seeds
			set_seed(args.seed				)

			# Prepare GLUE task
			UpperCAmelCase     	=       args.task_name.lower()
			if args.task_name not in glue_processors:
						raise ValueError('''Task not found: %s''' % (args.task_name)				)
			UpperCAmelCase     	=       glue_processors[args.task_name]()
			UpperCAmelCase     	=       glue_output_modes[args.task_name]
			UpperCAmelCase     	=       processor.get_labels()
			UpperCAmelCase     	=       len(UpperCamelCase__				)

			# Load pretrained model and tokenizer
			#
			# Distributed training:
			# The .from_pretrained methods guarantee that only one local process can concurrently
			# download model & vocab.

			UpperCAmelCase     	=       AutoConfig.from_pretrained(
			    args.config_name if args.config_name else args.model_name_or_path    ,    num_labels=UpperCamelCase__    ,    finetuning_task=args.task_name    ,    output_attentions=UpperCamelCase__    ,    cache_dir=args.cache_dir    ,    )
			UpperCAmelCase     	=       AutoTokenizer.from_pretrained(
			    args.tokenizer_name if args.tokenizer_name else args.model_name_or_path    ,    cache_dir=args.cache_dir    ,    )
			UpperCAmelCase     	=       AutoModelForSequenceClassification.from_pretrained(
			    args.model_name_or_path    ,    from_tf=bool('''.ckpt''' in args.model_name_or_path				)    ,    config=UpperCamelCase__    ,    cache_dir=args.cache_dir    ,    )

			# Distributed and parallel training
			model.to(args.device				)
			if args.local_rank != -1:
						UpperCAmelCase     	=       nn.parallel.DistributedDataParallel(
						    UpperCamelCase__    ,    device_ids=[args.local_rank]    ,    output_device=args.local_rank    ,    find_unused_parameters=UpperCamelCase__				)
			elif args.n_gpu > 1:
						UpperCAmelCase     	=       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 for the GLUE task
			UpperCAmelCase     	=       GlueDataset(UpperCamelCase__    ,    tokenizer=UpperCamelCase__    ,    mode='''dev'''				)
			if args.data_subset > 0:
						UpperCAmelCase     	=       Subset(UpperCamelCase__    ,    list(range(min(args.data_subset    ,    len(UpperCamelCase__				)				)				)				)				)
			UpperCAmelCase     	=       SequentialSampler(UpperCamelCase__				) if args.local_rank == -1 else DistributedSampler(UpperCamelCase__				)
			UpperCAmelCase     	=       DataLoader(
			    UpperCamelCase__    ,    sampler=UpperCamelCase__    ,    batch_size=args.batch_size    ,    collate_fn=UpperCamelCase__				)

			# 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:
						UpperCAmelCase     	=       mask_heads(UpperCamelCase__    ,    UpperCamelCase__    ,    UpperCamelCase__				)
						prune_heads(UpperCamelCase__    ,    UpperCamelCase__    ,    UpperCamelCase__    ,    UpperCamelCase__				)


if __name__ == "__main__":
				main()










import os
from typing import List, Union

import tensorflow as tf
from tensorflow_text import BertTokenizer as BertTokenizerLayer
from tensorflow_text import FastBertTokenizer, ShrinkLongestTrimmer, case_fold_utfa, combine_segments, pad_model_inputs

from .tokenization_bert import BertTokenizer

class 			A_ (tf.keras.layers.Layer    ):
	def __init__(					self							,      _A							,      _A							,      _A = None							,      _A = None							,      _A = None							,      _A = "longest"							,      _A = True							,      _A = 5_1_2							,      _A = None							,      _A = True							,      _A = True							,      _A = True							,      **_A							,      ):






				'''simple docstring'''







				super().__init__()
				if use_fast_bert_tokenizer:
							UpperCAmelCase     	=       FastBertTokenizer(
							    _A							,      token_out_type=tf.intaa							,      lower_case_nfd_strip_accents=_A							,      **_A	)
				else:
							UpperCAmelCase     	=       tf.lookup.StaticVocabularyTable(
							    tf.lookup.KeyValueTensorInitializer(
							        keys=_A							,      key_dtype=tf.string							,      values=tf.range(tf.size(_A							,      out_type=tf.intaa	)							,      dtype=tf.intaa	)							,      value_dtype=tf.intaa							,      )							,      num_oov_buckets=1							,      )
							UpperCAmelCase     	=       BertTokenizerLayer(
							    _A							,      token_out_type=tf.intaa							,      lower_case=_A							,      **_A	)

				UpperCAmelCase     	=       vocab_list
				UpperCAmelCase     	=       do_lower_case
				UpperCAmelCase     	=       cls_token_id or vocab_list.index('''[CLS]'''	)
				UpperCAmelCase     	=       sep_token_id or vocab_list.index('''[SEP]'''	)
				UpperCAmelCase     	=       pad_token_id or vocab_list.index('''[PAD]'''	)
				UpperCAmelCase     	=       ShrinkLongestTrimmer(max_length - 3							,      axis=1	)  # Allow room for special tokens
				UpperCAmelCase     	=       max_length
				UpperCAmelCase     	=       padding
				UpperCAmelCase     	=       truncation
				UpperCAmelCase     	=       pad_to_multiple_of
				UpperCAmelCase     	=       return_token_type_ids
				UpperCAmelCase     	=       return_attention_mask
	@classmethod
	def   _lowercase       (					cls							,      _A							,      **_A	):  # noqa: F821






				'''simple docstring'''







				UpperCAmelCase     	=       kwargs.pop('''do_lower_case'''							,      _A	)
				UpperCAmelCase     	=       tokenizer.do_lower_case if do_lower_case is None else do_lower_case
				UpperCAmelCase     	=       kwargs.pop('''cls_token_id'''							,      _A	)
				UpperCAmelCase     	=       tokenizer.cls_token_id if cls_token_id is None else cls_token_id
				UpperCAmelCase     	=       kwargs.pop('''sep_token_id'''							,      _A	)
				UpperCAmelCase     	=       tokenizer.sep_token_id if sep_token_id is None else sep_token_id
				UpperCAmelCase     	=       kwargs.pop('''pad_token_id'''							,      _A	)
				UpperCAmelCase     	=       tokenizer.pad_token_id if pad_token_id is None else pad_token_id

				UpperCAmelCase     	=       tokenizer.get_vocab()
				UpperCAmelCase     	=       sorted([(wordpiece, idx) for wordpiece, idx in vocab.items()]							,      key=lambda _A	: x[1]	)
				UpperCAmelCase     	=       [entry[0] for entry in vocab]
				return cls(
				    vocab_list=_A							,      do_lower_case=_A							,      cls_token_id=_A							,      sep_token_id=_A							,      pad_token_id=_A							,      **_A							,      )
	@classmethod
	def   _lowercase       (					cls							,      _A							,      *_A							,      **_A	):






				'''simple docstring'''







				try:
							UpperCAmelCase     	=       BertTokenizer.from_pretrained(_A							,      *_A							,      **_A	)
				except:  # noqa: E722
							from .tokenization_bert_fast import BertTokenizerFast

							UpperCAmelCase     	=       BertTokenizerFast.from_pretrained(_A							,      *_A							,      **_A	)
				return cls.from_tokenizer(_A							,      **_A	)
	def   _lowercase       (					self							,      _A	):






				'''simple docstring'''







				if self.do_lower_case:
							UpperCAmelCase     	=       case_fold_utfa(_A	)
				UpperCAmelCase     	=       self.tf_tokenizer.tokenize(_A	)
				return tokens.merge_dims(1							,      -1	)
	def   _lowercase       (					self							,      _A							,      _A=None							,      _A=None							,      _A=None							,      _A=None							,      _A=None							,      _A=None							,      _A=None							,      ):






				'''simple docstring'''







				if padding is None:
							UpperCAmelCase     	=       self.padding
				if padding not in ("longest", "max_length"):
							raise ValueError('''Padding must be either \'longest\' or \'max_length\'!'''	)
				if max_length is not None and text_pair is not None:
							# Because we have to instantiate a Trimmer to do it properly
							raise ValueError('''max_length cannot be overridden at call time when truncating paired texts!'''	)
				if max_length is None:
							UpperCAmelCase     	=       self.max_length
				if truncation is None:
							UpperCAmelCase     	=       self.truncation
				if pad_to_multiple_of is None:
							UpperCAmelCase     	=       self.pad_to_multiple_of
				if return_token_type_ids is None:
							UpperCAmelCase     	=       self.return_token_type_ids
				if return_attention_mask is None:
							UpperCAmelCase     	=       self.return_attention_mask
				if not isinstance(_A							,      tf.Tensor	):
							UpperCAmelCase     	=       tf.convert_to_tensor(_A	)
				if text_pair is not None and not isinstance(_A							,      tf.Tensor	):
							UpperCAmelCase     	=       tf.convert_to_tensor(_A	)
				if text_pair is not None:
							if text.shape.rank > 1:
										raise ValueError('''text argument should not be multidimensional when a text pair is supplied!'''	)
							if text_pair.shape.rank > 1:
										raise ValueError('''text_pair should not be multidimensional!'''	)
				if text.shape.rank == 2:
							UpperCAmelCase	,    UpperCAmelCase     	=       text[:, 0], text[:, 1]
				UpperCAmelCase     	=       self.unpaired_tokenize(_A	)
				if text_pair is None:  # Unpaired text
							if truncation:
										UpperCAmelCase     	=       text[:, : max_length - 2]  # Allow room for special tokens
							UpperCAmelCase	,    UpperCAmelCase     	=       combine_segments(
							    (text,)							,      start_of_sequence_id=self.cls_token_id							,      end_of_segment_id=self.sep_token_id	)
				else:  # Paired text
							UpperCAmelCase     	=       self.unpaired_tokenize(_A	)
							if truncation:
										UpperCAmelCase	,    UpperCAmelCase     	=       self.paired_trimmer.trim([text, text_pair]	)
							UpperCAmelCase	,    UpperCAmelCase     	=       combine_segments(
							    (text, text_pair)							,      start_of_sequence_id=self.cls_token_id							,      end_of_segment_id=self.sep_token_id	)
				if padding == "longest":
							UpperCAmelCase     	=       input_ids.bounding_shape(axis=1	)
							if pad_to_multiple_of is not None:
										# No ceiling division in tensorflow, so we negate floordiv instead
										UpperCAmelCase     	=       pad_to_multiple_of * (-tf.math.floordiv(-pad_length							,      _A	))
				else:
							UpperCAmelCase     	=       max_length

				UpperCAmelCase	,    UpperCAmelCase     	=       pad_model_inputs(_A							,      max_seq_length=_A							,      pad_value=self.pad_token_id	)
				UpperCAmelCase     	=       {'''input_ids''': input_ids}
				if return_attention_mask:
							UpperCAmelCase     	=       attention_mask
				if return_token_type_ids:
							UpperCAmelCase	,    UpperCAmelCase     	=       pad_model_inputs(
							    _A							,      max_seq_length=_A							,      pad_value=self.pad_token_id	)
							UpperCAmelCase     	=       token_type_ids
				return output







	def   _lowercase       (					self	):






				'''simple docstring'''







				return {
				    "vocab_list": self.vocab_list,
				    "do_lower_case": self.do_lower_case,
				    "cls_token_id": self.cls_token_id,
				    "sep_token_id": self.sep_token_id,
				    "pad_token_id": self.pad_token_id,
				}



