



'''simple docstring'''




import argparse
import logging
import os
import re

import tensorflow as tf

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


lowerCamelCase							:Optional[int]       = logging.getLogger(__name__)

lowerCamelCase							:Optional[int]       = tf.data.AUTOTUNE



def      a      (			):
			'''simple docstring'''





			A_     :						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=5_12						,				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."""   )

			A_     :						Dict     =					parser.parse_args()
			return args



def      a      (			lowerCamelCase__   ):
			'''simple docstring'''





			try:
						if args.tpu_name:
									A_     :						Optional[Any]     =					tf.distribute.cluster_resolver.TPUClusterResolver(
									    args.tpu_name						,				zone=args.tpu_zone						,				project=args.gcp_project   )
						else:
									A_     :						Union[str, 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      a      (			lowerCamelCase__   ):
			'''simple docstring'''





			A_     :						List[str]     =					0
			for file in file_list:
						A_     :						Optional[Any]     =					file.split("""/"""   )[-1]
						A_     :						Optional[int]     =					re.search(r"""-\d+-(\d+)\.tfrecord"""						,				lowerCamelCase__   ).group(1   )
						A_     :						Any     =					int(lowerCamelCase__   )
						num_samples += sample_count

			return num_samples



def      a      (			lowerCamelCase__						,				lowerCamelCase__						,				lowerCamelCase__						,				lowerCamelCase__						,				lowerCamelCase__						,				lowerCamelCase__=None   ):
			'''simple docstring'''





			A_     :						List[Any]     =					count_samples(lowerCamelCase__   )
			A_     :						List[str]     =					tf.data.Dataset.from_tensor_slices(lowerCamelCase__   )
			if shuffle:
						A_     :						Optional[int]     =					dataset.shuffle(len(lowerCamelCase__   )   )
			A_     :						Tuple     =					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
			A_     :						Union[str, Any]     =					dataset.apply(tf.data.experimental.assert_cardinality(lowerCamelCase__   )   )
			A_     :						Any     =					dataset.map(lowerCamelCase__						,				num_parallel_calls=lowerCamelCase__   )
			if shuffle:
						assert shuffle_buffer_size is not None
						A_     :						List[str]     =					dataset.shuffle(args.shuffle_buffer_size   )
			A_     :						str     =					dataset.batch(lowerCamelCase__						,				drop_remainder=lowerCamelCase__   )
			A_     :						str     =					dataset.map(lowerCamelCase__						,				num_parallel_calls=lowerCamelCase__   )
			A_     :						Optional[int]     =					dataset.prefetch(lowerCamelCase__   )
			return dataset



def      a      (			lowerCamelCase__   ):
			'''simple docstring'''





			if not args.no_tpu:
						A_     :						Dict     =					initialize_tpu(lowerCamelCase__   )
						A_     :						str     =					tf.distribute.TPUStrategy(lowerCamelCase__   )
			else:
						A_     :						Union[str, Any]     =					tf.distribute.OneDeviceStrategy(device="""/gpu:0"""   )

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

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

			A_     :						Dict     =					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}.'   )
			A_     :						Optional[int]     =					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}.'   )

			A_     :						Dict     =					count_samples(lowerCamelCase__   )

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

			with strategy.scope():
						A_     :						Optional[int]     =					TFAutoModelForMaskedLM.from_config(lowerCamelCase__   )
						model(model.dummy_inputs   )  # Pass some dummy inputs through the model to ensure all the weights are built
						A_,   A_     :						Any     =					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__   ):
						A_     :						Optional[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.
			A_     :						Optional[int]     =					DataCollatorForLanguageModeling(
			    tokenizer=lowerCamelCase__						,				mlm_probability=args.mlm_probability						,				mlm=lowerCamelCase__						,				return_tensors="""tf"""   )

			def mask_with_collator(lowerCamelCase__   ):
						# TF really needs an isin() function
						A_     :						str     =					(
						    ~tf.cast(batch["""attention_mask"""]						,				tf.bool   )
						    | (batch["""input_ids"""] == tokenizer.cls_token_id)
						    | (batch["""input_ids"""] == tokenizer.sep_token_id)
						)
						A_,   A_     :						Union[str, Any]     =					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

			A_     :						str     =					args.per_replica_batch_size * strategy.num_replicas_in_sync

			A_     :						Tuple     =					prepare_dataset(
			    lowerCamelCase__						,				decode_fn=lowerCamelCase__						,				mask_fn=lowerCamelCase__						,				batch_size=lowerCamelCase__						,				shuffle=lowerCamelCase__						,				shuffle_buffer_size=args.shuffle_buffer_size						,				)

			A_     :						Optional[Any]     =					prepare_dataset(
			    lowerCamelCase__						,				decode_fn=lowerCamelCase__						,				mask_fn=lowerCamelCase__						,				batch_size=lowerCamelCase__						,				shuffle=lowerCamelCase__						,				)

			A_     :						Union[str, Any]     =					[]
			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__":
						lowerCamelCase							:Tuple       = parse_args()
						main(args)




'''simple docstring'''




import inspect
import unittest

from transformers import ViTConfig
from transformers.testing_utils import (
    require_accelerate,
    require_torch,
    require_torch_gpu,
    require_vision,
    slow,
    torch_device,
)
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
						import torch
						from torch import nn

						from transformers import ViTForImageClassification, ViTForMaskedImageModeling, ViTModel
						from transformers.models.vit.modeling_vit import VIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
						from PIL import Image

						from transformers import ViTImageProcessor







class      _lowerCAmelCase							:


	def __init__(self	,				lowercase	,				lowercase=13	,				lowercase=30	,				lowercase=2	,				lowercase=3	,				lowercase=True	,				lowercase=True	,				lowercase=32	,				lowercase=5	,				lowercase=4	,				lowercase=37	,				lowercase="gelu"	,				lowercase=0.1	,				lowercase=0.1	,				lowercase=10	,				lowercase=0.02	,				lowercase=None	,				lowercase=2	,				):
				A_     :						List[str]     =					parent
				A_     :						str     =					batch_size
				A_     :						Optional[Any]     =					image_size
				A_     :						List[str]     =					patch_size
				A_     :						List[str]     =					num_channels
				A_     :						List[str]     =					is_training
				A_     :						str     =					use_labels
				A_     :						List[str]     =					hidden_size
				A_     :						List[Any]     =					num_hidden_layers
				A_     :						Any     =					num_attention_heads
				A_     :						Any     =					intermediate_size
				A_     :						Optional[Any]     =					hidden_act
				A_     :						Optional[int]     =					hidden_dropout_prob
				A_     :						str     =					attention_probs_dropout_prob
				A_     :						Optional[int]     =					type_sequence_label_size
				A_     :						Any     =					initializer_range
				A_     :						int     =					scope
				A_     :						str     =					encoder_stride

				# in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
				A_     :						Dict     =					(image_size // patch_size) ** 2
				A_     :						List[str]     =					num_patches + 1


	def    _a     (self							):
				A_     :						str     =					floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]							)

				A_     :						Optional[Any]     =					None
				if self.use_labels:
							A_     :						str     =					ids_tensor([self.batch_size]	,				self.type_sequence_label_size							)

				A_     :						Union[str, Any]     =					self.get_config()

				return config, pixel_values, labels


	def    _a     (self							):
				return ViTConfig(
				    image_size=self.image_size	,				patch_size=self.patch_size	,				num_channels=self.num_channels	,				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	,				is_decoder=lowercase	,				initializer_range=self.initializer_range	,				encoder_stride=self.encoder_stride	,				)


	def    _a     (self	,				lowercase	,				lowercase	,				lowercase							):
				A_     :						List[str]     =					ViTModel(config=lowercase							)
				model.to(lowercase							)
				model.eval()
				A_     :						List[str]     =					model(lowercase							)
				self.parent.assertEqual(result.last_hidden_state.shape	,				(self.batch_size, self.seq_length, self.hidden_size)							)


	def    _a     (self	,				lowercase	,				lowercase	,				lowercase							):
				A_     :						List[str]     =					ViTForMaskedImageModeling(config=lowercase							)
				model.to(lowercase							)
				model.eval()
				A_     :						Tuple     =					model(lowercase							)
				self.parent.assertEqual(
				    result.reconstruction.shape	,				(self.batch_size, self.num_channels, self.image_size, self.image_size)							)

				# test greyscale images
				A_     :						Union[str, Any]     =					1
				A_     :						Any     =					ViTForMaskedImageModeling(lowercase							)
				model.to(lowercase							)
				model.eval()

				A_     :						str     =					floats_tensor([self.batch_size, 1, self.image_size, self.image_size]							)
				A_     :						Optional[int]     =					model(lowercase							)
				self.parent.assertEqual(result.reconstruction.shape	,				(self.batch_size, 1, self.image_size, self.image_size)							)


	def    _a     (self	,				lowercase	,				lowercase	,				lowercase							):
				A_     :						Dict     =					self.type_sequence_label_size
				A_     :						str     =					ViTForImageClassification(lowercase							)
				model.to(lowercase							)
				model.eval()
				A_     :						List[str]     =					model(lowercase	,				labels=lowercase							)
				self.parent.assertEqual(result.logits.shape	,				(self.batch_size, self.type_sequence_label_size)							)

				# test greyscale images
				A_     :						Any     =					1
				A_     :						str     =					ViTForImageClassification(lowercase							)
				model.to(lowercase							)
				model.eval()

				A_     :						Optional[int]     =					floats_tensor([self.batch_size, 1, self.image_size, self.image_size]							)
				A_     :						Union[str, Any]     =					model(lowercase							)
				self.parent.assertEqual(result.logits.shape	,				(self.batch_size, self.type_sequence_label_size)							)


	def    _a     (self							):
				A_     :						str     =					self.prepare_config_and_inputs()
				(
				    (
				    A_
				),   (
				    A_
				),   (
				    A_
				),   
				)     :						Optional[int]     =					config_and_inputs
				A_     :						Tuple     =					{"""pixel_values""": pixel_values}
				return config, inputs_dict







@require_torch
class      _lowerCAmelCase							(      __UpperCAmelCase				,      __UpperCAmelCase				,      unittest.TestCase			):
	__SCREAMING_SNAKE_CASE       :		Any		      = (
	    (
	        ViTModel,
	        ViTForImageClassification,
	        ViTForMaskedImageModeling,
	    )
	    if is_torch_available()
	    else ()
	)
	__SCREAMING_SNAKE_CASE       :		Union[str, Any]		      = (
	    {'feature-extraction': ViTModel, 'image-classification': ViTForImageClassification}
	    if is_torch_available()
	    else {}
	)
	__SCREAMING_SNAKE_CASE       :		Union[str, Any]		      = True

	__SCREAMING_SNAKE_CASE       :		Dict		      = False
	__SCREAMING_SNAKE_CASE       :		Optional[int]		      = False
	__SCREAMING_SNAKE_CASE       :		Optional[int]		      = False


	def    _a     (self							):
				A_     :						Any     =					ViTModelTester(self							)
				A_     :						str     =					ConfigTester(self	,				config_class=lowercase	,				has_text_modality=lowercase	,				hidden_size=37							)


	def    _a     (self							):
				self.config_tester.run_common_tests()


	@unittest.skip(reason="""ViT does not use inputs_embeds"""							)
	def    _a     (self							):
				pass


	def    _a     (self							):
				A_,   A_     :						Union[str, Any]     =					self.model_tester.prepare_config_and_inputs_for_common()

				for model_class in self.all_model_classes:
							A_     :						Union[str, Any]     =					model_class(lowercase							)
							self.assertIsInstance(model.get_input_embeddings()	,				(nn.Module)							)
							A_     :						Tuple     =					model.get_output_embeddings()
							self.assertTrue(x is None or isinstance(lowercase	,				nn.Linear							)							)


	def    _a     (self							):
				A_,   A_     :						List[Any]     =					self.model_tester.prepare_config_and_inputs_for_common()

				for model_class in self.all_model_classes:
							A_     :						Optional[Any]     =					model_class(lowercase							)
							A_     :						Any     =					inspect.signature(model.forward							)
							# signature.parameters is an OrderedDict => so arg_names order is deterministic
							A_     :						List[str]     =					[*signature.parameters.keys()]

							A_     :						Dict     =					["""pixel_values"""]
							self.assertListEqual(arg_names[:1]	,				lowercase							)


	def    _a     (self							):
				A_     :						Tuple     =					self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_model(*lowercase							)


	def    _a     (self							):
				A_     :						List[Any]     =					self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_for_masked_image_modeling(*lowercase							)


	def    _a     (self							):
				A_     :						Dict     =					self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_for_image_classification(*lowercase							)


	@slow
	def    _a     (self							):
				for model_name in VIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
							A_     :						Dict     =					ViTModel.from_pretrained(lowercase							)
							self.assertIsNotNone(lowercase							)






def      a      (			):
			'''simple docstring'''





			A_     :						List[Any]     =					Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""   )
			return image







@require_torch
@require_vision
class      _lowerCAmelCase							(      unittest.TestCase			):


	@cached_property
	def    _a     (self							):
				return ViTImageProcessor.from_pretrained("""google/vit-base-patch16-224"""							) if is_vision_available() else None


	@slow
	def    _a     (self							):
				A_     :						Optional[int]     =					ViTForImageClassification.from_pretrained("""google/vit-base-patch16-224"""							).to(lowercase							)

				A_     :						List[str]     =					self.default_image_processor
				A_     :						Tuple     =					prepare_img()
				A_     :						int     =					image_processor(images=lowercase	,				return_tensors="""pt"""							).to(lowercase							)

				# forward pass
				with torch.no_grad():
							A_     :						str     =					model(**lowercase							)

				# verify the logits
				A_     :						Dict     =					torch.Size((1, 1000)							)
				self.assertEqual(outputs.logits.shape	,				lowercase							)

				A_     :						str     =					torch.tensor([-0.27_44, 0.82_15, -0.08_36]							).to(lowercase							)

				self.assertTrue(torch.allclose(outputs.logits[0, :3]	,				lowercase	,				atol=1E-4							)							)


	@slow
	def    _a     (self							):
				# ViT models have an `interpolate_pos_encoding` argument in their forward method,
				# allowing to interpolate the pre-trained position embeddings in order to use
				# the model on higher resolutions. The DINO model by Facebook AI leverages this
				# to visualize self-attention on higher resolution images.
				A_     :						Optional[int]     =					ViTModel.from_pretrained("""facebook/dino-vits8"""							).to(lowercase							)

				A_     :						List[Any]     =					ViTImageProcessor.from_pretrained("""facebook/dino-vits8"""	,				size=480							)
				A_     :						Dict     =					prepare_img()
				A_     :						str     =					image_processor(images=lowercase	,				return_tensors="""pt"""							)
				A_     :						int     =					inputs.pixel_values.to(lowercase							)

				# forward pass
				with torch.no_grad():
							A_     :						int     =					model(lowercase	,				interpolate_pos_encoding=lowercase							)

				# verify the logits
				A_     :						int     =					torch.Size((1, 3601, 384)							)
				self.assertEqual(outputs.last_hidden_state.shape	,				lowercase							)

				A_     :						List[Any]     =					torch.tensor(
				    [[4.23_40, 4.39_06, -6.66_92], [4.54_63, 1.89_28, -6.72_57], [4.44_29, 0.84_96, -5.85_85]]							).to(lowercase							)

				self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3]	,				lowercase	,				atol=1E-4							)							)


	@slow
	@require_accelerate
	@require_torch_gpu
	def    _a     (self							):
				A_     :						List[Any]     =					ViTModel.from_pretrained("""facebook/dino-vits8"""	,				torch_dtype=torch.floataa	,				device_map="""auto"""							)
				A_     :						int     =					self.default_image_processor

				A_     :						Any     =					prepare_img()
				A_     :						List[str]     =					image_processor(images=lowercase	,				return_tensors="""pt"""							)
				A_     :						Any     =					inputs.pixel_values.to(lowercase							)

				# forward pass to make sure inference works in fp16
				with torch.no_grad():
							A_     :						Optional[Any]     =					model(lowercase							)