
import logging
import os
import sys
from dataclasses import dataclass, field
from typing import Optional

import evaluate
import numpy as np
import torch
from datasets import load_dataset
from PIL import Image
from torchvision.transforms import (
    CenterCrop,
    Compose,
    Normalize,
    RandomHorizontalFlip,
    RandomResizedCrop,
    Resize,
    ToTensor,
)

import transformers
from transformers import (
    MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING,
    AutoConfig,
    AutoImageProcessor,
    AutoModelForImageClassification,
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    set_seed,
)
from transformers.trainer_utils import get_last_checkpoint
from transformers.utils import check_min_version, send_example_telemetry
from transformers.utils.versions import require_version
UpperCamelCase_						=						logging.getLogger(__name__)

# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
check_min_version("4.31.0")

require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/image-classification/requirements.txt")

UpperCamelCase_						=						list(MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING.keys())
UpperCamelCase_						=						tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)





def 				_lowerCamelCase      (       lowerCamelCase_:	str		):



				'''simple docstring'''







				with open(lowercase__					,						'''rb'''		) as f:
								A  :	Union[str, Any]				=					Image.open(lowercase__		)
								return im.convert('''RGB'''		)

@dataclass
class      _SCREAMING_SNAKE_CASE				:
				lowerCamelCase_	  =  field(
				    default=snake_case,     metadata={
				        'help': 'Name of a dataset from the hub (could be your own, possibly private dataset hosted on the hub).'
				    },     )
				lowerCamelCase_	  =  field(
				    default=snake_case,     metadata={'help': 'The configuration name of the dataset to use (via the datasets library).'}				)
				lowerCamelCase_	  =  field(default=snake_case,     metadata={'help': 'A folder containing the training data.'}				)
				lowerCamelCase_	  =  field(default=snake_case,     metadata={'help': 'A folder containing the validation data.'}				)
				lowerCamelCase_	  =  field(
				    default=0.15,     metadata={'help': 'Percent to split off of train for validation.'}				)
				lowerCamelCase_	  =  field(
				    default=snake_case,     metadata={
				        'help': (
				            'For debugging purposes or quicker training, truncate the number of training examples to this '
				            'value if set.'
				        )
				    },     )
				lowerCamelCase_	  =  field(
				    default=snake_case,     metadata={
				        'help': (
				            'For debugging purposes or quicker training, truncate the number of evaluation examples to this '
				            'value if set.'
				        )
				    },     )





				def 							_UpperCAmelCase    (		self			:		int				):


								"""simple docstring"""

								if self.dataset_name is None and (self.train_dir is None and self.validation_dir is None):
												raise ValueError(
												    '''You must specify either a dataset name from the hub or a train and/or validation directory.'''				)



@dataclass
class      _SCREAMING_SNAKE_CASE				:
				lowerCamelCase_	  =  field(
				    default='google/vit-base-patch16-224-in21k',     metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models'},     )
				lowerCamelCase_	  =  field(
				    default=snake_case,     metadata={'help': 'If training from scratch, pass a model type from the list: ' + ', '.join(snake_case				)},     )
				lowerCamelCase_	  =  field(
				    default=snake_case,     metadata={'help': 'Pretrained config name or path if not the same as model_name'}				)
				lowerCamelCase_	  =  field(
				    default=snake_case,     metadata={'help': 'Where do you want to store the pretrained models downloaded from s3'}				)
				lowerCamelCase_	  =  field(
				    default='main',     metadata={'help': 'The specific model version to use (can be a branch name, tag name or commit id).'},     )
				lowerCamelCase_	  =  field(default=snake_case,     metadata={'help': 'Name or path of preprocessor config.'}				)
				lowerCamelCase_	  =  field(
				    default=snake_case,     metadata={
				        'help': (
				            'Will use the token generated when running `huggingface-cli login` (necessary to use this script '
				            'with private models).'
				        )
				    },     )
				lowerCamelCase_	  =  field(
				    default=snake_case,     metadata={'help': 'Will enable to load a pretrained model whose head dimensions are different.'},     )





def 				_lowerCamelCase      (       lowerCamelCase_:	int		):



				'''simple docstring'''







				A  :	Optional[int]				=					torch.stack([example['''pixel_values'''] for example in examples]		)
				A  :	Union[str, Any]				=					torch.tensor([example['''labels'''] for example in examples]		)
				return {"pixel_values": pixel_values, "labels": labels}





def 				_lowerCamelCase      (       ):



				'''simple docstring'''







				A  :	List[str]				=					HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)		)
				if len(sys.argv		) == 2 and sys.argv[1].endswith('''.json'''		):
								# If we pass only one argument to the script and it's the path to a json file,
								# let's parse it to get our arguments.
								A			,							A			,							A  :	List[str]				=					parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]		)		)
				else:
								A			,							A			,							A  :	List[Any]				=					parser.parse_args_into_dataclasses()

				# Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
				# information sent is the one passed as arguments along with your Python/PyTorch versions.
				send_example_telemetry('''run_image_classification'''					,						lowercase__					,						lowercase__		)

				# Setup logging
				logging.basicConfig(
				    format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s'''					,						datefmt='''%m/%d/%Y %H:%M:%S'''					,						handlers=[logging.StreamHandler(sys.stdout		)]					,						)

				if training_args.should_log:
								# The default of training_args.log_level is passive, so we set log level at info here to have that default.
								transformers.utils.logging.set_verbosity_info()

				A  :	int				=					training_args.get_process_log_level()
				logger.setLevel(lowercase__		)
				transformers.utils.logging.set_verbosity(lowercase__		)
				transformers.utils.logging.enable_default_handler()
				transformers.utils.logging.enable_explicit_format()

				# Log on each process the small summary:
				logger.warning(
				    f"""Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"""
				    + f"""distributed training: {bool(training_args.local_rank != -1		)}, 16-bits training: {training_args.fpaa}"""		)
				logger.info(f"""Training/evaluation parameters {training_args}"""		)

				# Detecting last checkpoint.
				A  :	List[Any]				=					None
				if os.path.isdir(training_args.output_dir		) and training_args.do_train and not training_args.overwrite_output_dir:
								A  :	Dict				=					get_last_checkpoint(training_args.output_dir		)
								if last_checkpoint is None and len(os.listdir(training_args.output_dir		)		) > 0:
												raise ValueError(
												    f"""Output directory ({training_args.output_dir}) already exists and is not empty. """
												    '''Use --overwrite_output_dir to overcome.'''		)
								elif last_checkpoint is not None and training_args.resume_from_checkpoint is None:
												logger.info(
												    f"""Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change """
												    '''the `--output_dir` or add `--overwrite_output_dir` to train from scratch.'''		)

    # Set seed before initializing model.
				set_seed(training_args.seed		)

				# Initialize our dataset and prepare it for the 'image-classification' task.
				if data_args.dataset_name is not None:
								A  :	str				=					load_dataset(
								    data_args.dataset_name					,						data_args.dataset_config_name					,						cache_dir=model_args.cache_dir					,						task='''image-classification'''					,						use_auth_token=True if model_args.use_auth_token else None					,						)
				else:
								A  :	List[Any]				=					{}
								if data_args.train_dir is not None:
												A  :	Tuple				=					os.path.join(data_args.train_dir					,						'''**'''		)
								if data_args.validation_dir is not None:
												A  :	List[Any]				=					os.path.join(data_args.validation_dir					,						'''**'''		)
								A  :	str				=					load_dataset(
								    '''imagefolder'''					,						data_files=lowercase__					,						cache_dir=model_args.cache_dir					,						task='''image-classification'''					,						)

				# If we don't have a validation split, split off a percentage of train as validation.
				A  :	Any				=					None if '''validation''' in dataset.keys() else data_args.train_val_split
				if isinstance(data_args.train_val_split					,						lowercase__		) and data_args.train_val_split > 0.0:
								A  :	str				=					dataset['''train'''].train_test_split(data_args.train_val_split		)
								A  :	List[Any]				=					split['''train''']
								A  :	int				=					split['''test''']

				# Prepare label mappings.
				# We'll include these in the model's config to get human readable labels in the Inference API.
				A  :	List[str]				=					dataset['''train'''].features['''labels'''].names
				A			,							A  :	str				=					{}, {}
				for i, label in enumerate(lowercase__		):
								A  :	Union[str, Any]				=					str(lowercase__		)
								A  :	List[Any]				=					label

				# Load the accuracy metric from the datasets package
				A  :	str				=					evaluate.load('''accuracy'''		)

				# Define our compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with a
				# predictions and label_ids field) and has to return a dictionary string to float.
				def compute_metrics(lowerCamelCase_:	Tuple		):
								return metric.compute(predictions=np.argmax(p.predictions					,						axis=1		)					,						references=p.label_ids		)

				A  :	Any				=					AutoConfig.from_pretrained(
				    model_args.config_name or model_args.model_name_or_path					,						num_labels=len(lowercase__		)					,						labelaid=lowercase__					,						idalabel=lowercase__					,						finetuning_task='''image-classification'''					,						cache_dir=model_args.cache_dir					,						revision=model_args.model_revision					,						use_auth_token=True if model_args.use_auth_token else None					,						)
				A  :	List[str]				=					AutoModelForImageClassification.from_pretrained(
				    model_args.model_name_or_path					,						from_tf=bool('''.ckpt''' in model_args.model_name_or_path		)					,						config=lowercase__					,						cache_dir=model_args.cache_dir					,						revision=model_args.model_revision					,						use_auth_token=True if model_args.use_auth_token else None					,						ignore_mismatched_sizes=model_args.ignore_mismatched_sizes					,						)
				A  :	Tuple				=					AutoImageProcessor.from_pretrained(
				    model_args.image_processor_name or model_args.model_name_or_path					,						cache_dir=model_args.cache_dir					,						revision=model_args.model_revision					,						use_auth_token=True if model_args.use_auth_token else None					,						)

				# Define torchvision transforms to be applied to each image.
				if "shortest_edge" in image_processor.size:
								A  :	Any				=					image_processor.size['''shortest_edge''']
				else:
								A  :	Optional[Any]				=					(image_processor.size['''height'''], image_processor.size['''width'''])
				A  :	int				=					Normalize(mean=image_processor.image_mean					,						std=image_processor.image_std		)
				A  :	Union[str, Any]				=					Compose(
				    [
				        RandomResizedCrop(lowercase__		),
				        RandomHorizontalFlip(),
				        ToTensor(),
				        normalize,
				    ]		)
				A  :	Tuple				=					Compose(
				    [
				        Resize(lowercase__		),
				        CenterCrop(lowercase__		),
				        ToTensor(),
				        normalize,
				    ]		)

				def train_transforms(lowerCamelCase_:	Any		):
								A  :	Tuple				=					[
								    _train_transforms(pil_img.convert('''RGB'''		)		) for pil_img in example_batch['''image''']
								]
								return example_batch

				def val_transforms(lowerCamelCase_:	int		):
								A  :	List[Any]				=					[_val_transforms(pil_img.convert('''RGB'''		)		) for pil_img in example_batch['''image''']]
								return example_batch

				if training_args.do_train:
								if "train" not in dataset:
												raise ValueError('''--do_train requires a train dataset'''		)
								if data_args.max_train_samples is not None:
												A  :	List[Any]				=					(
												    dataset['''train'''].shuffle(seed=training_args.seed		).select(range(data_args.max_train_samples		)		)
												)
								# Set the training transforms
								dataset["train"].set_transform(lowercase__		)

				if training_args.do_eval:
								if "validation" not in dataset:
												raise ValueError('''--do_eval requires a validation dataset'''		)
								if data_args.max_eval_samples is not None:
												A  :	Optional[Any]				=					(
												    dataset['''validation'''].shuffle(seed=training_args.seed		).select(range(data_args.max_eval_samples		)		)
												)
								# Set the validation transforms
								dataset["validation"].set_transform(lowercase__		)

				# Initalize our trainer
				A  :	Any				=					Trainer(
				    model=lowercase__					,						args=lowercase__					,						train_dataset=dataset['''train'''] if training_args.do_train else None					,						eval_dataset=dataset['''validation'''] if training_args.do_eval else None					,						compute_metrics=lowercase__					,						tokenizer=lowercase__					,						data_collator=lowercase__					,						)

				# Training
				if training_args.do_train:
								A  :	Dict				=					None
								if training_args.resume_from_checkpoint is not None:
												A  :	Any				=					training_args.resume_from_checkpoint
								elif last_checkpoint is not None:
												A  :	Optional[int]				=					last_checkpoint
								A  :	Optional[int]				=					trainer.train(resume_from_checkpoint=lowercase__		)
								trainer.save_model()
								trainer.log_metrics('''train'''					,						train_result.metrics		)
								trainer.save_metrics('''train'''					,						train_result.metrics		)
								trainer.save_state()

				# Evaluation
				if training_args.do_eval:
								A  :	Optional[Any]				=					trainer.evaluate()
								trainer.log_metrics('''eval'''					,						lowercase__		)
								trainer.save_metrics('''eval'''					,						lowercase__		)

				# Write model card and (optionally) push to hub
				A  :	int				=					{
				    '''finetuned_from''': model_args.model_name_or_path,
				    '''tasks''': '''image-classification''',
				    '''dataset''': data_args.dataset_name,
				    '''tags''': ['''image-classification''', '''vision'''],
				}
				if training_args.push_to_hub:
								trainer.push_to_hub(**lowercase__		)
				else:
								trainer.create_model_card(**lowercase__		)


if __name__ == "__main__":
					main()



"""simple docstring"""




from __future__ import annotations

import unittest

from transformers import RoFormerConfig, is_tf_available
from transformers.testing_utils import require_tf, slow

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


if is_tf_available():
					import tensorflow as tf

					from transformers import (
					    TFRoFormerForCausalLM,
					    TFRoFormerForMaskedLM,
					    TFRoFormerForMultipleChoice,
					    TFRoFormerForQuestionAnswering,
					    TFRoFormerForSequenceClassification,
					    TFRoFormerForTokenClassification,
					    TFRoFormerModel,
					)
					from transformers.models.roformer.modeling_tf_roformer import (
					    TFRoFormerSelfAttention,
					    TFRoFormerSinusoidalPositionalEmbedding,
					)




class 			__snake_case   :




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




							def   __a   (     self:    Optional[Any]   ):
										__lowerCamelCase          =      ids_tensor([self.batch_size, self.seq_length]     ,							self.vocab_size   )

										__lowerCamelCase          =      None
										if self.use_input_mask:
													__lowerCamelCase          =      random_attention_mask([self.batch_size, self.seq_length]   )

										__lowerCamelCase          =      None
										if self.use_token_type_ids:
													__lowerCamelCase          =      ids_tensor([self.batch_size, self.seq_length]     ,							self.type_vocab_size   )

										__lowerCamelCase          =      None
										__lowerCamelCase          =      None
										__lowerCamelCase          =      None
										if self.use_labels:
													__lowerCamelCase          =      ids_tensor([self.batch_size]     ,							self.type_sequence_label_size   )
													__lowerCamelCase          =      ids_tensor([self.batch_size, self.seq_length]     ,							self.num_labels   )
													__lowerCamelCase          =      ids_tensor([self.batch_size]     ,							self.num_choices   )

										__lowerCamelCase          =      RoFormerConfig(
										    vocab_size=self.vocab_size     ,							hidden_size=self.hidden_size     ,							num_hidden_layers=self.num_hidden_layers     ,							num_attention_heads=self.num_attention_heads     ,							intermediate_size=self.intermediate_size     ,							hidden_act=self.hidden_act     ,							hidden_dropout_prob=self.hidden_dropout_prob     ,							attention_probs_dropout_prob=self.attention_probs_dropout_prob     ,							max_position_embeddings=self.max_position_embeddings     ,							type_vocab_size=self.type_vocab_size     ,							initializer_range=self.initializer_range     ,							return_dict=A_     ,							)

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




							def   __a   (     self:    Union[str, Any]     ,							A_:    str     ,							A_:    Dict     ,							A_:    Union[str, Any]     ,							A_:    Optional[int]     ,							A_:    Any     ,							A_:    Dict     ,							A_:    int   ):
										__lowerCamelCase          =      TFRoFormerModel(config=A_   )
										__lowerCamelCase          =      {"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids}

										__lowerCamelCase          =      [input_ids, input_mask]
										__lowerCamelCase          =      model(A_   )

										__lowerCamelCase          =      model(A_   )

										self.parent.assertEqual(result.last_hidden_state.shape     ,							(self.batch_size, self.seq_length, self.hidden_size)   )




							def   __a   (     self:    List[str]     ,							A_:    int     ,							A_:    str     ,							A_:    Any     ,							A_:    int     ,							A_:    str     ,							A_:    str     ,							A_:    Union[str, Any]   ):
										__lowerCamelCase          =      True
										__lowerCamelCase          =      TFRoFormerForCausalLM(config=A_   )
										__lowerCamelCase          =      {
										    """input_ids""": input_ids,
										    """attention_mask""": input_mask,
										    """token_type_ids""": token_type_ids,
										}
										__lowerCamelCase          =      model(A_   )["""logits"""]
										self.parent.assertListEqual(
										    list(prediction_scores.numpy().shape   )     ,							[self.batch_size, self.seq_length, self.vocab_size]   )




							def   __a   (     self:    Any     ,							A_:    Optional[Any]     ,							A_:    Optional[Any]     ,							A_:    Union[str, Any]     ,							A_:    str     ,							A_:    str     ,							A_:    Optional[Any]     ,							A_:    int   ):
										__lowerCamelCase          =      TFRoFormerForMaskedLM(config=A_   )
										__lowerCamelCase          =      {
										    """input_ids""": input_ids,
										    """attention_mask""": input_mask,
										    """token_type_ids""": token_type_ids,
										}
										__lowerCamelCase          =      model(A_   )
										self.parent.assertEqual(result.logits.shape     ,							(self.batch_size, self.seq_length, self.vocab_size)   )




							def   __a   (     self:    Optional[Any]     ,							A_:    Dict     ,							A_:    Union[str, Any]     ,							A_:    List[Any]     ,							A_:    str     ,							A_:    int     ,							A_:    Optional[Any]     ,							A_:    int   ):
										__lowerCamelCase          =      self.num_labels
										__lowerCamelCase          =      TFRoFormerForSequenceClassification(config=A_   )
										__lowerCamelCase          =      {
										    """input_ids""": input_ids,
										    """attention_mask""": input_mask,
										    """token_type_ids""": token_type_ids,
										}

										__lowerCamelCase          =      model(A_   )
										self.parent.assertEqual(result.logits.shape     ,							(self.batch_size, self.num_labels)   )




							def   __a   (     self:    List[str]     ,							A_:    Tuple     ,							A_:    List[str]     ,							A_:    Union[str, Any]     ,							A_:    Optional[Any]     ,							A_:    List[str]     ,							A_:    Optional[int]     ,							A_:    List[Any]   ):
										__lowerCamelCase          =      self.num_choices
										__lowerCamelCase          =      TFRoFormerForMultipleChoice(config=A_   )
										__lowerCamelCase          =      tf.tile(tf.expand_dims(A_     ,							1   )     ,							(1, self.num_choices, 1)   )
										__lowerCamelCase          =      tf.tile(tf.expand_dims(A_     ,							1   )     ,							(1, self.num_choices, 1)   )
										__lowerCamelCase          =      tf.tile(tf.expand_dims(A_     ,							1   )     ,							(1, self.num_choices, 1)   )
										__lowerCamelCase          =      {
										    """input_ids""": multiple_choice_inputs_ids,
										    """attention_mask""": multiple_choice_input_mask,
										    """token_type_ids""": multiple_choice_token_type_ids,
										}
										__lowerCamelCase          =      model(A_   )
										self.parent.assertEqual(result.logits.shape     ,							(self.batch_size, self.num_choices)   )




							def   __a   (     self:    Union[str, Any]     ,							A_:    Dict     ,							A_:    List[Any]     ,							A_:    List[Any]     ,							A_:    Union[str, Any]     ,							A_:    str     ,							A_:    Union[str, Any]     ,							A_:    List[str]   ):
										__lowerCamelCase          =      self.num_labels
										__lowerCamelCase          =      TFRoFormerForTokenClassification(config=A_   )
										__lowerCamelCase          =      {
										    """input_ids""": input_ids,
										    """attention_mask""": input_mask,
										    """token_type_ids""": token_type_ids,
										}
										__lowerCamelCase          =      model(A_   )
										self.parent.assertEqual(result.logits.shape     ,							(self.batch_size, self.seq_length, self.num_labels)   )




							def   __a   (     self:    int     ,							A_:    Union[str, Any]     ,							A_:    Any     ,							A_:    Any     ,							A_:    Dict     ,							A_:    str     ,							A_:    int     ,							A_:    Tuple   ):
										__lowerCamelCase          =      TFRoFormerForQuestionAnswering(config=A_   )
										__lowerCamelCase          =      {
										    """input_ids""": input_ids,
										    """attention_mask""": input_mask,
										    """token_type_ids""": token_type_ids,
										}

										__lowerCamelCase          =      model(A_   )
										self.parent.assertEqual(result.start_logits.shape     ,							(self.batch_size, self.seq_length)   )
										self.parent.assertEqual(result.end_logits.shape     ,							(self.batch_size, self.seq_length)   )




							def   __a   (     self:    Union[str, Any]   ):
										__lowerCamelCase          =      self.prepare_config_and_inputs()
										(
										    (
										    __lowerCamelCase
										)     ,(
										    __lowerCamelCase
										)     ,(
										    __lowerCamelCase
										)     ,(
										    __lowerCamelCase
										)     ,(
										    __lowerCamelCase
										)     ,(
										    __lowerCamelCase
										)     ,(
										    __lowerCamelCase
										)     ,
										)          =      config_and_inputs
										__lowerCamelCase          =      {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask}
										return config, inputs_dict




@require_tf
class 			__snake_case   (lowerCamelCase			,		lowerCamelCase			,		unittest.TestCase  ):
							__a					 =       (
							    (
							        TFRoFormerModel,
							        TFRoFormerForCausalLM,
							        TFRoFormerForMaskedLM,
							        TFRoFormerForQuestionAnswering,
							        TFRoFormerForSequenceClassification,
							        TFRoFormerForTokenClassification,
							        TFRoFormerForMultipleChoice,
							    )
							    if is_tf_available()
							    else ()
							)
							__a					 =       (
							    {
							        '''feature-extraction''': TFRoFormerModel,
							        '''fill-mask''': TFRoFormerForMaskedLM,
							        '''question-answering''': TFRoFormerForQuestionAnswering,
							        '''text-classification''': TFRoFormerForSequenceClassification,
							        '''text-generation''': TFRoFormerForCausalLM,
							        '''token-classification''': TFRoFormerForTokenClassification,
							        '''zero-shot''': TFRoFormerForSequenceClassification,
							    }
							    if is_tf_available()
							    else {}
							)

							__a					 =       False
							__a					 =       False




							def   __a   (     self:    List[str]     ,							A_:    List[Any]     ,							A_:    List[str]     ,							A_:    str     ,							A_:    Union[str, Any]     ,							A_:    Dict   ):
										if pipeline_test_casse_name == "TextGenerationPipelineTests":
													return True

										return False




							def   __a   (     self:    Tuple   ):
										__lowerCamelCase          =      TFRoFormerModelTester(self   )
										__lowerCamelCase          =      ConfigTester(self     ,							config_class=A_     ,							hidden_size=37   )




							def   __a   (     self:    int   ):
										self.config_tester.run_common_tests()




							def   __a   (     self:    Optional[int]   ):
										__lowerCamelCase          =      self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_model(*A_   )




							def   __a   (     self:    Union[str, Any]   ):
										__lowerCamelCase          =      self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_masked_lm(*A_   )




							def   __a   (     self:    Optional[Any]   ):
										__lowerCamelCase          =      self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_lm_head(*A_   )




							def   __a   (     self:    Tuple   ):
										__lowerCamelCase          =      self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_multiple_choice(*A_   )




							def   __a   (     self:    Any   ):
										__lowerCamelCase          =      self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_question_answering(*A_   )




							def   __a   (     self:    int   ):
										__lowerCamelCase          =      self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_sequence_classification(*A_   )




							def   __a   (     self:    int   ):
										__lowerCamelCase          =      self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_token_classification(*A_   )




							@slow
							def   __a   (     self:    Optional[int]   ):
										__lowerCamelCase          =      TFRoFormerModel.from_pretrained("""junnyu/roformer_chinese_base"""   )
										self.assertIsNotNone(A_   )




@require_tf
class 			__snake_case   (unittest.TestCase  ):




							@slow
							def   __a   (     self:    Optional[Any]   ):
										__lowerCamelCase          =      TFRoFormerForMaskedLM.from_pretrained("""junnyu/roformer_chinese_base"""   )
										__lowerCamelCase          =      tf.constant([[0, 1, 2, 3, 4, 5]]   )
										__lowerCamelCase          =      model(A_   )[0]

										# TODO Replace vocab size
										__lowerCamelCase          =      5_00_00

										__lowerCamelCase          =      [1, 6, vocab_size]
										self.assertEqual(output.shape     ,							A_   )

										print(output[:, :3, :3]   )

										# TODO Replace values below with what was printed above.
										__lowerCamelCase          =      tf.constant(
										    [
										        [
										            [-0.12_053_341, -1.0_264_901, 0.29_221_946],
										            [-1.5_133_783, 0.197_433, 0.15_190_607],
										            [-5.0_135_403, -3.900_256, -0.84_038_764],
										        ]
										    ]   )
										tf.debugging.assert_near(output[:, :3, :3]     ,							A_     ,							atol=1E-4   )




@require_tf
class 			__snake_case   (unittest.TestCase  ):
							__a					 =       1e-4




							def   __a   (     self:    List[Any]   ):
										__lowerCamelCase          =      tf.constant([[4, 10]]   )
										__lowerCamelCase          =      TFRoFormerSinusoidalPositionalEmbedding(num_positions=6     ,							embedding_dim=6   )

										__lowerCamelCase          =      emba(input_ids.shape   )
										__lowerCamelCase          =      tf.constant(
										    [[0.0_000, 0.0_000, 0.0_000, 1.0_000, 1.0_000, 1.0_000], [0.8_415, 0.0_464, 0.0_022, 0.5_403, 0.9_989, 1.0_000]]   )

										tf.debugging.assert_near(A_     ,							A_     ,							atol=self.tolerance   )




							def   __a   (     self:    Optional[Any]   ):
										__lowerCamelCase          =      tf.constant(
										    [
										        [0.0_000, 0.0_000, 0.0_000, 0.0_000, 0.0_000],
										        [0.8_415, 0.8_219, 0.8_020, 0.7_819, 0.7_617],
										        [0.9_093, 0.9_364, 0.9_581, 0.9_749, 0.9_870],
										    ]   )
										__lowerCamelCase          =      TFRoFormerSinusoidalPositionalEmbedding(num_positions=5_12     ,							embedding_dim=5_12   )
										emba([2, 16, 5_12]   )
										__lowerCamelCase          =      emba.weight[:3, :5]

										tf.debugging.assert_near(A_     ,							A_     ,							atol=self.tolerance   )




@require_tf
class 			__snake_case   (unittest.TestCase  ):
							__a					 =       1e-4




							def   __a   (     self:    str   ):
										# 2,12,16,64
										__lowerCamelCase          =      tf.reshape(tf.range(2 * 12 * 16 * 64     ,							dtype=tf.floataa   )     ,							shape=(2, 12, 16, 64)   ) / 1_00

										__lowerCamelCase          =      -tf.reshape(tf.range(2 * 12 * 16 * 64     ,							dtype=tf.floataa   )     ,							shape=(2, 12, 16, 64)   ) / 1_00

										__lowerCamelCase          =      TFRoFormerSinusoidalPositionalEmbedding(num_positions=32     ,							embedding_dim=64   )
										__lowerCamelCase          =      embed_positions([2, 16, 7_68]   )[None, None, :, :]

										__lowerCamelCase     ,__lowerCamelCase          =      TFRoFormerSelfAttention.apply_rotary_position_embeddings(
										    A_     ,							A_     ,							A_   )

										__lowerCamelCase          =      tf.constant(
										    [
										        [0.0_000, 0.0_100, 0.0_200, 0.0_300, 0.0_400, 0.0_500, 0.0_600, 0.0_700],
										        [-0.2_012, 0.8_897, 0.0_263, 0.9_401, 0.2_074, 0.9_463, 0.3_481, 0.9_343],
										        [-1.7_057, 0.6_271, -1.2_145, 1.3_897, -0.6_303, 1.7_647, -0.1_173, 1.8_985],
										        [-2.1_731, -1.6_397, -2.7_358, 0.2_854, -2.1_840, 1.7_183, -1.3_018, 2.4_871],
										        [0.2_717, -3.6_173, -2.9_206, -2.1_988, -3.6_638, 0.3_858, -2.9_155, 2.2_980],
										        [3.9_859, -2.1_580, -0.7_984, -4.4_904, -4.1_181, -2.0_252, -4.4_782, 1.1_253],
										    ]   )
										__lowerCamelCase          =      tf.constant(
										    [
										        [0.0_000, -0.0_100, -0.0_200, -0.0_300, -0.0_400, -0.0_500, -0.0_600, -0.0_700],
										        [0.2_012, -0.8_897, -0.0_263, -0.9_401, -0.2_074, -0.9_463, -0.3_481, -0.9_343],
										        [1.7_057, -0.6_271, 1.2_145, -1.3_897, 0.6_303, -1.7_647, 0.1_173, -1.8_985],
										        [2.1_731, 1.6_397, 2.7_358, -0.2_854, 2.1_840, -1.7_183, 1.3_018, -2.4_871],
										        [-0.2_717, 3.6_173, 2.9_206, 2.1_988, 3.6_638, -0.3_858, 2.9_155, -2.2_980],
										        [-3.9_859, 2.1_580, 0.7_984, 4.4_904, 4.1_181, 2.0_252, 4.4_782, -1.1_253],
										    ]   )

										tf.debugging.assert_near(query_layer[0, 0, :6, :8]     ,							A_     ,							atol=self.tolerance   )
										tf.debugging.assert_near(key_layer[0, 0, :6, :8]     ,							A_     ,							atol=self.tolerance   )




