






from typing import Dict

import numpy as np

from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging
from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline, PipelineException


if is_tf_available():
				import tensorflow as tf

				from ..tf_utils import stable_softmax


if is_torch_available():
				import torch


A        =			logging.get_logger(__name__)


@add_end_docstrings(
    SCREAMING_SNAKE_CASE_ ,	R"""\n        top_k (`int`, defaults to 5):\n            The number of predictions to return.\n        targets (`str` or `List[str]`, *optional*):\n            When passed, the model will limit the scores to the passed targets instead of looking up in the whole\n            vocab. If the provided targets are not in the model vocab, they will be tokenized and the first resulting\n            token will be used (with a warning, and that might be slower).\n\n    """ ,	)
class 							__a							(  SCREAMING_SNAKE_CASE_						):





		'''simple docstring'''



		def   __snake_case			(						self ,    UpperCamelCase__       ):
						if self.framework == "tf":
										SCREAMING_SNAKE_CASE_   :	List[str]													=   tf.where(input_ids == self.tokenizer.mask_token_id       ).numpy()
						elif self.framework == "pt":
										SCREAMING_SNAKE_CASE_   :	Any													=   torch.nonzero(input_ids == self.tokenizer.mask_token_id ,    as_tuple=UpperCamelCase__       )
						else:
										raise ValueError('Unsupported framework'       )
						return masked_index


		def   __snake_case			(						self ,    UpperCamelCase__       ):
						SCREAMING_SNAKE_CASE_   :	Dict													=   self.get_masked_index(UpperCamelCase__       )
						SCREAMING_SNAKE_CASE_   :	str													=   np.prod(masked_index.shape       )
						if numel < 1:
										raise PipelineException(
										    'fill-mask' ,    self.model.base_model_prefix ,    F'''No mask_token ({self.tokenizer.mask_token}) found on the input''' ,    )


		def   __snake_case			(						self ,    UpperCamelCase__       ):
						if isinstance(UpperCamelCase__ ,    UpperCamelCase__       ):
										for model_input in model_inputs:
														self._ensure_exactly_one_mask_token(model_input['input_ids'][0]       )
						else:
										for input_ids in model_inputs["input_ids"]:
														self._ensure_exactly_one_mask_token(UpperCamelCase__       )


		def   __snake_case			(						self ,    UpperCamelCase__ ,    UpperCamelCase__=None ,    **UpperCamelCase__       ):
						if return_tensors is None:
										SCREAMING_SNAKE_CASE_   :	str													=   self.framework
						SCREAMING_SNAKE_CASE_   :	str													=   self.tokenizer(UpperCamelCase__ ,    return_tensors=UpperCamelCase__       )
						self.ensure_exactly_one_mask_token(UpperCamelCase__       )
						return model_inputs


		def   __snake_case			(						self ,    UpperCamelCase__       ):
						SCREAMING_SNAKE_CASE_   :	Tuple													=   self.model(**UpperCamelCase__       )
						SCREAMING_SNAKE_CASE_   :	List[str]													=   model_inputs['''input_ids''']
						return model_outputs


		def   __snake_case			(						self ,    UpperCamelCase__ ,    UpperCamelCase__=5 ,    UpperCamelCase__=None       ):
						# Cap top_k if there are targets
						if target_ids is not None and target_ids.shape[0] < top_k:
										SCREAMING_SNAKE_CASE_   :	Union[str, Any]													=   target_ids.shape[0]
						SCREAMING_SNAKE_CASE_   :	str													=   model_outputs['''input_ids'''][0]
						SCREAMING_SNAKE_CASE_   :	Tuple													=   model_outputs['''logits''']

						if self.framework == "tf":
										SCREAMING_SNAKE_CASE_   :	Tuple													=   tf.where(input_ids == self.tokenizer.mask_token_id       ).numpy()[:, 0]

										SCREAMING_SNAKE_CASE_   :	Dict													=   outputs.numpy()

										SCREAMING_SNAKE_CASE_   :	Tuple													=   outputs[0, masked_index, :]
										SCREAMING_SNAKE_CASE_   :	str													=   stable_softmax(UpperCamelCase__ ,    axis=-1       )
										if target_ids is not None:
														SCREAMING_SNAKE_CASE_   :	int													=   tf.gather_nd(tf.squeeze(UpperCamelCase__ ,    0       ) ,    target_ids.reshape(-1 ,    1       )       )
														SCREAMING_SNAKE_CASE_   :	str													=   tf.expand_dims(UpperCamelCase__ ,    0       )

										SCREAMING_SNAKE_CASE_   :	str													=   tf.math.top_k(UpperCamelCase__ ,    k=UpperCamelCase__       )
										SCREAMING_SNAKE_CASE_   :	List[str]													=   topk.values.numpy(), topk.indices.numpy()
						else:
										SCREAMING_SNAKE_CASE_   :	Optional[Any]													=   torch.nonzero(input_ids == self.tokenizer.mask_token_id ,    as_tuple=UpperCamelCase__       ).squeeze(-1       )
										# Fill mask pipeline supports only one ${mask_token} per sample

										SCREAMING_SNAKE_CASE_   :	List[Any]													=   outputs[0, masked_index, :]
										SCREAMING_SNAKE_CASE_   :	Tuple													=   logits.softmax(dim=-1       )
										if target_ids is not None:
														SCREAMING_SNAKE_CASE_   :	str													=   probs[..., target_ids]

										SCREAMING_SNAKE_CASE_   :	Tuple													=   probs.topk(UpperCamelCase__       )

						SCREAMING_SNAKE_CASE_   :	Union[str, Any]													=   []
						SCREAMING_SNAKE_CASE_   :	str													=   values.shape[0] == 1
						for i, (_values, _predictions) in enumerate(zip(values.tolist() ,    predictions.tolist()       )       ):
										SCREAMING_SNAKE_CASE_   :	Optional[Any]													=   []
										for v, p in zip(_values ,    _predictions       ):
														# Copy is important since we're going to modify this array in place
														SCREAMING_SNAKE_CASE_   :	List[str]													=   input_ids.numpy().copy()
														if target_ids is not None:
																		SCREAMING_SNAKE_CASE_   :	Any													=   target_ids[p].tolist()

														SCREAMING_SNAKE_CASE_   :	List[str]													=   p
														# Filter padding out:
														SCREAMING_SNAKE_CASE_   :	Dict													=   tokens[np.where(tokens != self.tokenizer.pad_token_id       )]
														# Originally we skip special tokens to give readable output.
														# For multi masks though, the other [MASK] would be removed otherwise
														# making the output look odd, so we add them back
														SCREAMING_SNAKE_CASE_   :	Any													=   self.tokenizer.decode(UpperCamelCase__ ,    skip_special_tokens=UpperCamelCase__       )
														SCREAMING_SNAKE_CASE_   :	str													=   {'''score''': v, '''token''': p, '''token_str''': self.tokenizer.decode([p]       ), '''sequence''': sequence}
														row.append(UpperCamelCase__       )
										result.append(UpperCamelCase__       )
						if single_mask:
										return result[0]
						return result


		def   __snake_case			(						self ,    UpperCamelCase__ ,    UpperCamelCase__=None       ):
						if isinstance(UpperCamelCase__ ,    UpperCamelCase__       ):
										SCREAMING_SNAKE_CASE_   :	Dict													=   [targets]
						try:
										SCREAMING_SNAKE_CASE_   :	Any													=   self.tokenizer.get_vocab()
						except Exception:
										SCREAMING_SNAKE_CASE_   :	Tuple													=   {}
						SCREAMING_SNAKE_CASE_   :	str													=   []
						for target in targets:
										SCREAMING_SNAKE_CASE_   :	int													=   vocab.get(UpperCamelCase__ ,    UpperCamelCase__       )
										if id_ is None:
														SCREAMING_SNAKE_CASE_   :	Tuple													=   self.tokenizer(
														    UpperCamelCase__ ,    add_special_tokens=UpperCamelCase__ ,    return_attention_mask=UpperCamelCase__ ,    return_token_type_ids=UpperCamelCase__ ,    max_length=1 ,    truncation=UpperCamelCase__ ,    )['''input_ids''']
														if len(UpperCamelCase__       ) == 0:
																		logger.warning(
																		    F'''The specified target token `{target}` does not exist in the model vocabulary. '''
																		    'We cannot replace it with anything meaningful, ignoring it'       )
																		continue
														SCREAMING_SNAKE_CASE_   :	int													=   input_ids[0]
														# XXX: If users encounter this pass
														# it becomes pretty slow, so let's make sure
														# The warning enables them to fix the input to
														# get faster performance.
														logger.warning(
														    F'''The specified target token `{target}` does not exist in the model vocabulary. '''
														    F'''Replacing with `{self.tokenizer.convert_ids_to_tokens(id_       )}`.'''       )
										target_ids.append(id_       )
						SCREAMING_SNAKE_CASE_   :	str													=   list(set(UpperCamelCase__       )       )
						if len(UpperCamelCase__       ) == 0:
										raise ValueError('At least one target must be provided when passed.'       )
						SCREAMING_SNAKE_CASE_   :	Optional[int]													=   np.array(UpperCamelCase__       )
						return target_ids


		def   __snake_case			(						self ,    UpperCamelCase__=None ,    UpperCamelCase__=None       ):
						SCREAMING_SNAKE_CASE_   :	Tuple													=   {}

						if targets is not None:
										SCREAMING_SNAKE_CASE_   :	Any													=   self.get_target_ids(UpperCamelCase__ ,    UpperCamelCase__       )
										SCREAMING_SNAKE_CASE_   :	List[Any]													=   target_ids

						if top_k is not None:
										SCREAMING_SNAKE_CASE_   :	Union[str, Any]													=   top_k

						if self.tokenizer.mask_token_id is None:
										raise PipelineException(
										    'fill-mask' ,    self.model.base_model_prefix ,    'The tokenizer does not define a `mask_token`.'       )
						return {}, {}, postprocess_params






		def __call__(						self ,    UpperCamelCase__ ,    *UpperCamelCase__ ,    **UpperCamelCase__       ):
						SCREAMING_SNAKE_CASE_   :	Any													=   super().__call__(UpperCamelCase__ ,    **UpperCamelCase__       )
						if isinstance(UpperCamelCase__ ,    UpperCamelCase__       ) and len(UpperCamelCase__       ) == 1:
										return outputs[0]
						return outputs







import argparse
import logging
import os
import re

import tensorflow as tf

from transformers import (
    AutoConfig,
    AutoTokenizer,
    DataCollatorForLanguageModeling,
    PushToHubCallback,
    TFAutoModelForMaskedLM,
    create_optimizer,
)


A        =			logging.getLogger(__name__)

A        =			tf.data.AUTOTUNE



def 					_lowerCamelCase(			):





				'''simple docstring'''







				SCREAMING_SNAKE_CASE_   :	List[Any]													=   argparse.ArgumentParser(description='Train a masked language model on TPU.'      )
				parser.add_argument(
				    '--pretrained_model_config'    ,    type=lowerCAmelCase__    ,    default='roberta-base'    ,    help='The model config to use. Note that we don\'t copy the model\'s weights, only the config!'    ,    )
				parser.add_argument(
				    '--tokenizer'    ,    type=lowerCAmelCase__    ,    default='unigram-tokenizer-wikitext'    ,    help='The name of the tokenizer to load. We use the pretrained tokenizer to initialize the model\'s vocab size.'    ,    )

				parser.add_argument(
				    '--per_replica_batch_size'    ,    type=lowerCAmelCase__    ,    default=8    ,    help='Batch size per TPU core.'    ,    )

				parser.add_argument(
				    '--no_tpu'    ,    action='store_true'    ,    help='If set, run on CPU and don\'t try to initialize a TPU. Useful for debugging on non-TPU instances.'    ,    )

				parser.add_argument(
				    '--tpu_name'    ,    type=lowerCAmelCase__    ,    help='Name of TPU resource to initialize. Should be blank on Colab, and \'local\' on TPU VMs.'    ,    default='local'    ,    )

				parser.add_argument(
				    '--tpu_zone'    ,    type=lowerCAmelCase__    ,    help='Google cloud zone that TPU resource is located in. Only used for non-Colab TPU nodes.'    ,    )

				parser.add_argument(
				    '--gcp_project'    ,    type=lowerCAmelCase__    ,    help='Google cloud project name. Only used for non-Colab TPU nodes.'      )

				parser.add_argument(
				    '--bfloat16'    ,    action='store_true'    ,    help='Use mixed-precision bfloat16 for training. This is the recommended lower-precision format for TPU.'    ,    )

				parser.add_argument(
				    '--train_dataset'    ,    type=lowerCAmelCase__    ,    help='Path to training dataset to load. If the path begins with `gs://`'
				    ' then the dataset will be loaded from a Google Cloud Storage bucket.'    ,    )

				parser.add_argument(
				    '--shuffle_buffer_size'    ,    type=lowerCAmelCase__    ,    default=2**18    ,    help='Size of the shuffle buffer (in samples)'    ,    )

				parser.add_argument(
				    '--eval_dataset'    ,    type=lowerCAmelCase__    ,    help='Path to evaluation dataset to load. If the path begins with `gs://`'
				    ' then the dataset will be loaded from a Google Cloud Storage bucket.'    ,    )

				parser.add_argument(
				    '--num_epochs'    ,    type=lowerCAmelCase__    ,    default=1    ,    help='Number of epochs to train for.'    ,    )

				parser.add_argument(
				    '--learning_rate'    ,    type=lowerCAmelCase__    ,    default=1E-4    ,    help='Learning rate to use for training.'    ,    )

				parser.add_argument(
				    '--weight_decay_rate'    ,    type=lowerCAmelCase__    ,    default=1E-3    ,    help='Weight decay rate to use for training.'    ,    )

				parser.add_argument(
				    '--max_length'    ,    type=lowerCAmelCase__    ,    default=512    ,    help='Maximum length of tokenized sequences. Should match the setting used in prepare_tfrecord_shards.py'    ,    )

				parser.add_argument(
				    '--mlm_probability'    ,    type=lowerCAmelCase__    ,    default=0.15    ,    help='Fraction of tokens to mask during training.'    ,    )

				parser.add_argument('--output_dir'    ,    type=lowerCAmelCase__    ,    required=lowerCAmelCase__    ,    help='Path to save model checkpoints to.'      )
				parser.add_argument('--hub_model_id'    ,    type=lowerCAmelCase__    ,    help='Model ID to upload to on the Hugging Face Hub.'      )

				SCREAMING_SNAKE_CASE_   :	Union[str, Any]													=   parser.parse_args()
				return args



def 					_lowerCamelCase(			lowerCAmelCase__				:		List[str]      ):





				'''simple docstring'''







				try:
								if args.tpu_name:
												SCREAMING_SNAKE_CASE_   :	Dict													=   tf.distribute.cluster_resolver.TPUClusterResolver(
												    args.tpu_name    ,    zone=args.tpu_zone    ,    project=args.gcp_project      )
								else:
												SCREAMING_SNAKE_CASE_   :	Any													=   tf.distribute.cluster_resolver.TPUClusterResolver()
				except ValueError:
								raise RuntimeError(
								    'Couldn\'t connect to TPU! Most likely you need to specify --tpu_name, --tpu_zone, or '
								    '--gcp_project. When running on a TPU VM, use --tpu_name local.'      )

				tf.config.experimental_connect_to_cluster(lowerCAmelCase__      )
				tf.tpu.experimental.initialize_tpu_system(lowerCAmelCase__      )

				return tpu



def 					_lowerCamelCase(			lowerCAmelCase__				:		List[Any]      ):





				'''simple docstring'''







				SCREAMING_SNAKE_CASE_   :	Union[str, Any]													=   0
				for file in file_list:
								SCREAMING_SNAKE_CASE_   :	Dict													=   file.split('/'      )[-1]
								SCREAMING_SNAKE_CASE_   :	Any													=   re.search(R'-\d+-(\d+)\.tfrecord'    ,    lowerCAmelCase__      ).group(1      )
								SCREAMING_SNAKE_CASE_   :	Dict													=   int(lowerCAmelCase__      )
								num_samples += sample_count

				return num_samples



def 					_lowerCamelCase(			lowerCAmelCase__				:		Tuple    ,    lowerCAmelCase__				:		Optional[Any]    ,    lowerCAmelCase__				:		Optional[Any]    ,    lowerCAmelCase__				:		Any    ,    lowerCAmelCase__				:		Dict    ,    lowerCAmelCase__				:		List[str]=None      ):





				'''simple docstring'''







				SCREAMING_SNAKE_CASE_   :	Union[str, Any]													=   count_samples(lowerCAmelCase__      )
				SCREAMING_SNAKE_CASE_   :	int													=   tf.data.Dataset.from_tensor_slices(lowerCAmelCase__      )
				if shuffle:
								SCREAMING_SNAKE_CASE_   :	List[str]													=   dataset.shuffle(len(lowerCAmelCase__      )      )
				SCREAMING_SNAKE_CASE_   :	Optional[int]													=   tf.data.TFRecordDataset(lowerCAmelCase__    ,    num_parallel_reads=lowerCAmelCase__      )
				# TF can't infer the total sample count because it doesn't read all the records yet, so we assert it here
				SCREAMING_SNAKE_CASE_   :	List[Any]													=   dataset.apply(tf.data.experimental.assert_cardinality(lowerCAmelCase__      )      )
				SCREAMING_SNAKE_CASE_   :	List[str]													=   dataset.map(lowerCAmelCase__    ,    num_parallel_calls=lowerCAmelCase__      )
				if shuffle:
								assert shuffle_buffer_size is not None
								SCREAMING_SNAKE_CASE_   :	Any													=   dataset.shuffle(args.shuffle_buffer_size      )
				SCREAMING_SNAKE_CASE_   :	str													=   dataset.batch(lowerCAmelCase__    ,    drop_remainder=lowerCAmelCase__      )
				SCREAMING_SNAKE_CASE_   :	Any													=   dataset.map(lowerCAmelCase__    ,    num_parallel_calls=lowerCAmelCase__      )
				SCREAMING_SNAKE_CASE_   :	int													=   dataset.prefetch(lowerCAmelCase__      )
				return dataset



def 					_lowerCamelCase(			lowerCAmelCase__				:		Optional[Any]      ):





				'''simple docstring'''







				if not args.no_tpu:
								SCREAMING_SNAKE_CASE_   :	Tuple													=   initialize_tpu(lowerCAmelCase__      )
								SCREAMING_SNAKE_CASE_   :	str													=   tf.distribute.TPUStrategy(lowerCAmelCase__      )
				else:
								SCREAMING_SNAKE_CASE_   :	List[Any]													=   tf.distribute.OneDeviceStrategy(device='/gpu:0'      )

				if args.bfloataa:
								tf.keras.mixed_precision.set_global_policy('mixed_bfloat16'      )

				SCREAMING_SNAKE_CASE_   :	str													=   AutoTokenizer.from_pretrained(args.tokenizer      )
				SCREAMING_SNAKE_CASE_   :	Optional[Any]													=   AutoConfig.from_pretrained(args.pretrained_model_config      )
				SCREAMING_SNAKE_CASE_   :	Any													=   tokenizer.vocab_size

				SCREAMING_SNAKE_CASE_   :	str													=   tf.io.gfile.glob(os.path.join(args.train_dataset    ,    '*.tfrecord'      )      )
				if not training_records:
								raise ValueError(F'''No .tfrecord files found in {args.train_dataset}.'''      )
				SCREAMING_SNAKE_CASE_   :	str													=   tf.io.gfile.glob(os.path.join(args.eval_dataset    ,    '*.tfrecord'      )      )
				if not eval_records:
								raise ValueError(F'''No .tfrecord files found in {args.eval_dataset}.'''      )

				SCREAMING_SNAKE_CASE_   :	Optional[Any]													=   count_samples(lowerCAmelCase__      )

				SCREAMING_SNAKE_CASE_   :	int													=   num_train_samples // (args.per_replica_batch_size * strategy.num_replicas_in_sync)
				SCREAMING_SNAKE_CASE_   :	Optional[Any]													=   steps_per_epoch * args.num_epochs

				with strategy.scope():
								SCREAMING_SNAKE_CASE_   :	Optional[Any]													=   TFAutoModelForMaskedLM.from_config(lowerCAmelCase__      )
								model(model.dummy_inputs      )  # Pass some dummy inputs through the model to ensure all the weights are built
								SCREAMING_SNAKE_CASE_							,       SCREAMING_SNAKE_CASE_   :	str													=   create_optimizer(
								    num_train_steps=lowerCAmelCase__    ,    num_warmup_steps=total_train_steps // 20    ,    init_lr=args.learning_rate    ,    weight_decay_rate=args.weight_decay_rate    ,    )

								# Transformers models compute the right loss for their task by default when labels are passed, and will
								# use this for training unless you specify your own loss function in compile().
								model.compile(optimizer=lowerCAmelCase__    ,    metrics=['accuracy']      )

				def decode_fn(lowerCAmelCase__				:		Optional[int]      ):
								SCREAMING_SNAKE_CASE_   :	int													=   {
								    'input_ids': tf.io.FixedLenFeature(dtype=tf.intaa    ,    shape=(args.max_length,)      ),
								    'attention_mask': tf.io.FixedLenFeature(dtype=tf.intaa    ,    shape=(args.max_length,)      ),
								}
								return tf.io.parse_single_example(lowerCAmelCase__    ,    lowerCAmelCase__      )

				# Many of the data collators in Transformers are TF-compilable when return_tensors == "tf", so we can
				# use their methods in our data pipeline.
				SCREAMING_SNAKE_CASE_   :	Union[str, Any]													=   DataCollatorForLanguageModeling(
				    tokenizer=lowerCAmelCase__    ,    mlm_probability=args.mlm_probability    ,    mlm=lowerCAmelCase__    ,    return_tensors='tf'      )

				def mask_with_collator(lowerCAmelCase__				:		Optional[Any]      ):
								# TF really needs an isin() function
								SCREAMING_SNAKE_CASE_   :	Tuple													=   (
								    ~tf.cast(batch['attention_mask']    ,    tf.bool      )
								    | (batch['input_ids'] == tokenizer.cls_token_id)
								    | (batch['input_ids'] == tokenizer.sep_token_id)
								)
								SCREAMING_SNAKE_CASE_							,       SCREAMING_SNAKE_CASE_   :	Optional[int]													=   data_collator.tf_mask_tokens(
								    batch['input_ids']    ,    vocab_size=len(lowerCAmelCase__      )    ,    mask_token_id=tokenizer.mask_token_id    ,    special_tokens_mask=lowerCAmelCase__    ,    )
								return batch

				SCREAMING_SNAKE_CASE_   :	Any													=   args.per_replica_batch_size * strategy.num_replicas_in_sync

				SCREAMING_SNAKE_CASE_   :	Optional[int]													=   prepare_dataset(
				    lowerCAmelCase__    ,    decode_fn=lowerCAmelCase__    ,    mask_fn=lowerCAmelCase__    ,    batch_size=lowerCAmelCase__    ,    shuffle=lowerCAmelCase__    ,    shuffle_buffer_size=args.shuffle_buffer_size    ,    )

				SCREAMING_SNAKE_CASE_   :	List[Any]													=   prepare_dataset(
				    lowerCAmelCase__    ,    decode_fn=lowerCAmelCase__    ,    mask_fn=lowerCAmelCase__    ,    batch_size=lowerCAmelCase__    ,    shuffle=lowerCAmelCase__    ,    )

				SCREAMING_SNAKE_CASE_   :	str													=   []
				if args.hub_model_id:
								callbacks.append(
								    PushToHubCallback(output_dir=args.output_dir    ,    hub_model_id=args.hub_model_id    ,    tokenizer=lowerCAmelCase__      )      )

				model.fit(
				    lowerCAmelCase__    ,    validation_data=lowerCAmelCase__    ,    epochs=args.num_epochs    ,    callbacks=lowerCAmelCase__    ,    )

				model.save_pretrained(args.output_dir      )


if __name__ == "__main__":
				A        =			parse_args()
				main(args)