





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


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





def   _lowercase       (    _UpperCAmelCase					)    ->	int:
				lowerCamelCase									=p * torch.log(_UpperCAmelCase					)
				lowerCamelCase									=0
				return -plogp.sum(dim=-1					)





def   _lowercase       (    _UpperCAmelCase					)    ->	str:
				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       (    _UpperCAmelCase      ,   _UpperCAmelCase      ,   _UpperCAmelCase      ,   _UpperCAmelCase=True      ,   _UpperCAmelCase=True      ,   _UpperCAmelCase=None      ,   _UpperCAmelCase=False					)    ->	Optional[Any]:
				lowerCamelCase			,	lowerCamelCase									=model.config.num_hidden_layers, model.config.num_attention_heads
				lowerCamelCase									=torch.zeros(_UpperCAmelCase      ,   _UpperCAmelCase					).to(args.device					)
				lowerCamelCase									=torch.zeros(_UpperCAmelCase      ,   _UpperCAmelCase					).to(args.device					)

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

				lowerCamelCase									=None
				lowerCamelCase									=None
				lowerCamelCase									=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():
												lowerCamelCase									=v.to(args.device					)

								# Do a forward pass (not with torch.no_grad() since we need gradients for importance score - see below)
								lowerCamelCase									=model(**_UpperCAmelCase      ,   head_mask=_UpperCAmelCase					)
								lowerCamelCase			,	lowerCamelCase			,	lowerCamelCase									=(
								    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					):
																lowerCamelCase									=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:
												lowerCamelCase									=logits.detach().cpu().numpy()
												lowerCamelCase									=inputs["""labels"""].detach().cpu().numpy()
								else:
												lowerCamelCase									=np.append(_UpperCAmelCase      ,   logits.detach().cpu().numpy()      ,   axis=0					)
												lowerCamelCase									=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:
								lowerCamelCase									=2
								lowerCamelCase									=torch.pow(torch.pow(_UpperCAmelCase      ,   _UpperCAmelCase					).sum(-1					)      ,   1 / exponent					)
								head_importance /= norm_by_layer.unsqueeze(-1					) + 1e-2_0

				if not args.dont_normalize_global_importance:
								lowerCamelCase									=(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"""					)
				lowerCamelCase									=torch.zeros(head_importance.numel()      ,   dtype=torch.long      ,   device=args.device					)
				lowerCamelCase									=torch.arange(
				    head_importance.numel()      ,   device=args.device					)
				lowerCamelCase									=head_ranks.view_as(_UpperCAmelCase					)
				print_ad_tensor(_UpperCAmelCase					)

				return attn_entropy, head_importance, preds, labels





def   _lowercase       (    _UpperCAmelCase      ,   _UpperCAmelCase      ,   _UpperCAmelCase					)    ->	Dict:
				lowerCamelCase			,	lowerCamelCase			,	lowerCamelCase			,	lowerCamelCase									=compute_heads_importance(_UpperCAmelCase      ,   _UpperCAmelCase      ,   _UpperCAmelCase      ,   compute_entropy=_UpperCAmelCase					)
				lowerCamelCase									=np.argmax(_UpperCAmelCase      ,   axis=1					) if args.output_mode == """classification""" else np.squeeze(_UpperCAmelCase					)
				lowerCamelCase									=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					)

				lowerCamelCase									=torch.ones_like(_UpperCAmelCase					)
				lowerCamelCase									=max(1      ,   int(new_head_mask.numel() * args.masking_amount					)					)

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

								if len(_UpperCAmelCase					) <= num_to_mask:
												break

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

								# Compute metric and head importance again
								lowerCamelCase			,	lowerCamelCase			,	lowerCamelCase			,	lowerCamelCase									=compute_heads_importance(
								    _UpperCAmelCase      ,   _UpperCAmelCase      ,   _UpperCAmelCase      ,   compute_entropy=_UpperCAmelCase      ,   head_mask=_UpperCAmelCase					)
								lowerCamelCase									=np.argmax(_UpperCAmelCase      ,   axis=1					) if args.output_mode == """classification""" else np.squeeze(_UpperCAmelCase					)
								lowerCamelCase									=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() * 1_00      ,   )

				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       (    _UpperCAmelCase      ,   _UpperCAmelCase      ,   _UpperCAmelCase      ,   _UpperCAmelCase					)    ->	Optional[Any]:
				lowerCamelCase									=datetime.now()
				lowerCamelCase			,	lowerCamelCase			,	lowerCamelCase			,	lowerCamelCase									=compute_heads_importance(
				    _UpperCAmelCase      ,   _UpperCAmelCase      ,   _UpperCAmelCase      ,   compute_entropy=_UpperCAmelCase      ,   compute_importance=_UpperCAmelCase      ,   head_mask=_UpperCAmelCase					)
				lowerCamelCase									=np.argmax(_UpperCAmelCase      ,   axis=1					) if args.output_mode == """classification""" else np.squeeze(_UpperCAmelCase					)
				lowerCamelCase									=glue_compute_metrics(args.task_name      ,   _UpperCAmelCase      ,   _UpperCAmelCase					)[args.metric_name]
				lowerCamelCase									=datetime.now() - before_time

				lowerCamelCase									=sum(p.numel() for p in model.parameters()					)
				lowerCamelCase									={
				    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					)
				lowerCamelCase									=sum(p.numel() for p in model.parameters()					)

				lowerCamelCase									=datetime.now()
				lowerCamelCase			,	lowerCamelCase			,	lowerCamelCase			,	lowerCamelCase									=compute_heads_importance(
				    _UpperCAmelCase      ,   _UpperCAmelCase      ,   _UpperCAmelCase      ,   compute_entropy=_UpperCAmelCase      ,   compute_importance=_UpperCAmelCase      ,   head_mask=_UpperCAmelCase      ,   actually_pruned=_UpperCAmelCase      ,   )
				lowerCamelCase									=np.argmax(_UpperCAmelCase      ,   axis=1					) if args.output_mode == """classification""" else np.squeeze(_UpperCAmelCase					)
				lowerCamelCase									=glue_compute_metrics(args.task_name      ,   _UpperCAmelCase      ,   _UpperCAmelCase					)[args.metric_name]
				lowerCamelCase									=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 * 1_00      ,   )
				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 * 1_00					)





def   _lowercase       (    )    ->	Dict:
				lowerCamelCase									=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=1_28      ,   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."""					)
				lowerCamelCase									=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:
								lowerCamelCase									=torch.device("""cuda""" if torch.cuda.is_available() and not args.no_cuda else """cpu"""					)
								lowerCamelCase									=0 if args.no_cuda else torch.cuda.device_count()
				else:
								torch.cuda.set_device(args.local_rank					)
								lowerCamelCase									=torch.device("""cuda"""      ,   args.local_rank					)
								lowerCamelCase									=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
				lowerCamelCase									=args.task_name.lower()
				if args.task_name not in glue_processors:
								raise ValueError("""Task not found: %s""" % (args.task_name)					)
				lowerCamelCase									=glue_processors[args.task_name]()
				lowerCamelCase									=glue_output_modes[args.task_name]
				lowerCamelCase									=processor.get_labels()
				lowerCamelCase									=len(_UpperCAmelCase					)

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

				lowerCamelCase									=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      ,   )
				lowerCamelCase									=AutoTokenizer.from_pretrained(
				    args.tokenizer_name if args.tokenizer_name else args.model_name_or_path      ,   cache_dir=args.cache_dir      ,   )
				lowerCamelCase									=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:
								lowerCamelCase									=nn.parallel.DistributedDataParallel(
								    _UpperCAmelCase      ,   device_ids=[args.local_rank]      ,   output_device=args.local_rank      ,   find_unused_parameters=_UpperCAmelCase					)
				elif args.n_gpu > 1:
								lowerCamelCase									=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
				lowerCamelCase									=GlueDataset(_UpperCAmelCase      ,   tokenizer=_UpperCAmelCase      ,   mode="""dev"""					)
				if args.data_subset > 0:
								lowerCamelCase									=Subset(_UpperCAmelCase      ,   list(range(min(args.data_subset      ,   len(_UpperCAmelCase					)					)					)					)					)
				lowerCamelCase									=SequentialSampler(_UpperCAmelCase					) if args.local_rank == -1 else DistributedSampler(_UpperCAmelCase					)
				lowerCamelCase									=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:
								lowerCamelCase									=mask_heads(_UpperCAmelCase      ,   _UpperCAmelCase      ,   _UpperCAmelCase					)
								prune_heads(_UpperCAmelCase      ,   _UpperCAmelCase      ,   _UpperCAmelCase      ,   _UpperCAmelCase					)


if __name__ == "__main__":
							main()












import json
from typing import List, Optional, Tuple

from tokenizers import normalizers

from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_layoutlm import LayoutLMTokenizer


UpperCAmelCase__    :      int       					=logging.get_logger(__name__)

UpperCAmelCase__    :      Optional[Any]       					={'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''}

UpperCAmelCase__    :      List[str]       					={
    '''vocab_file''': {
        '''microsoft/layoutlm-base-uncased''': (
            '''https://huggingface.co/microsoft/layoutlm-base-uncased/resolve/main/vocab.txt'''
        ),
        '''microsoft/layoutlm-large-uncased''': (
            '''https://huggingface.co/microsoft/layoutlm-large-uncased/resolve/main/vocab.txt'''
        ),
    },
    '''tokenizer_file''': {
        '''microsoft/layoutlm-base-uncased''': (
            '''https://huggingface.co/microsoft/layoutlm-base-uncased/resolve/main/tokenizer.json'''
        ),
        '''microsoft/layoutlm-large-uncased''': (
            '''https://huggingface.co/microsoft/layoutlm-large-uncased/resolve/main/tokenizer.json'''
        ),
    },
}

UpperCAmelCase__    :      Dict       					={
    '''microsoft/layoutlm-base-uncased''': 5_12,
    '''microsoft/layoutlm-large-uncased''': 5_12,
}

UpperCAmelCase__    :      List[Any]       					={
    '''microsoft/layoutlm-base-uncased''': {'''do_lower_case''': True},
    '''microsoft/layoutlm-large-uncased''': {'''do_lower_case''': True},
}

class    __A  (    a     ):
				__A  =					VOCAB_FILES_NAMES
				__A  =					PRETRAINED_VOCAB_FILES_MAP
				__A  =					PRETRAINED_INIT_CONFIGURATION
				__A  =					PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
				__A  =					LayoutLMTokenizer


				def __init__(		self ,			UpperCAmelCase_=None ,			UpperCAmelCase_=None ,			UpperCAmelCase_=True ,			UpperCAmelCase_="[UNK]" ,			UpperCAmelCase_="[SEP]" ,			UpperCAmelCase_="[PAD]" ,			UpperCAmelCase_="[CLS]" ,			UpperCAmelCase_="[MASK]" ,			UpperCAmelCase_=True ,			UpperCAmelCase_=None ,			**UpperCAmelCase_ ,			):
								super().__init__(
								    UpperCAmelCase_ ,			tokenizer_file=UpperCAmelCase_ ,			do_lower_case=UpperCAmelCase_ ,			unk_token=UpperCAmelCase_ ,			sep_token=UpperCAmelCase_ ,			pad_token=UpperCAmelCase_ ,			cls_token=UpperCAmelCase_ ,			mask_token=UpperCAmelCase_ ,			tokenize_chinese_chars=UpperCAmelCase_ ,			strip_accents=UpperCAmelCase_ ,			**UpperCAmelCase_ ,			)

								lowerCamelCase									=json.loads(self.backend_tokenizer.normalizer.__getstate__()				)
								if (
								    normalizer_state.get("""lowercase""" ,			UpperCAmelCase_				) != do_lower_case
								    or normalizer_state.get("""strip_accents""" ,			UpperCAmelCase_				) != strip_accents
								    or normalizer_state.get("""handle_chinese_chars""" ,			UpperCAmelCase_				) != tokenize_chinese_chars
								):
												lowerCamelCase									=getattr(UpperCAmelCase_ ,			normalizer_state.pop("""type"""				)				)
												lowerCamelCase									=do_lower_case
												lowerCamelCase									=strip_accents
												lowerCamelCase									=tokenize_chinese_chars
												lowerCamelCase									=normalizer_class(**UpperCAmelCase_				)

								lowerCamelCase									=do_lower_case


				def _snake_case							(		self ,			UpperCAmelCase_ ,			UpperCAmelCase_=None				):
								lowerCamelCase									=[self.cls_token_id] + token_ids_a + [self.sep_token_id]

								if token_ids_a:
												output += token_ids_a + [self.sep_token_id]

								return output


				def _snake_case							(		self ,			UpperCAmelCase_ ,			UpperCAmelCase_ = None				):
								lowerCamelCase									=[self.sep_token_id]
								lowerCamelCase									=[self.cls_token_id]
								if token_ids_a is None:
												return len(cls + token_ids_a + sep				) * [0]
								return len(cls + token_ids_a + sep				) * [0] + len(token_ids_a + sep				) * [1]


				def _snake_case							(		self ,			UpperCAmelCase_ ,			UpperCAmelCase_ = None				):
								lowerCamelCase									=self._tokenizer.model.save(UpperCAmelCase_ ,			name=UpperCAmelCase_				)
								return tuple(UpperCAmelCase_				)





