




import itertools
import json
import linecache
import os
import pickle
import re
import socket
import string
from collections import Counter
from logging import getLogger
from pathlib import Path
from typing import Callable, Dict, Iterable, List

import git
import torch
from torch.utils.data import Dataset

from transformers import BartTokenizer, RagTokenizer, TaTokenizer







def lowerCamelCase__  (     _lowercase					,		_lowercase					,		_lowercase					,		_lowercase					,		_lowercase=True					,		_lowercase="pt" ):

     '''simple docstring'''


     UpperCAmelCase_     :				Dict  =     {'''add_prefix_space''': True} if isinstance(_lowercase					,		_lowercase ) and not line.startswith(''' ''' ) else {}
     UpperCAmelCase_     :				List[str]  =     padding_side
     return tokenizer(
         [line]					,		max_length=_lowercase					,		padding='''max_length''' if pad_to_max_length else None					,		truncation=_lowercase					,		return_tensors=_lowercase					,		add_special_tokens=_lowercase					,		**_lowercase					,		)







def lowerCamelCase__  (     _lowercase					,		_lowercase					,		_lowercase=None					,		):

     '''simple docstring'''


     UpperCAmelCase_     :				str  =     input_ids.ne(_lowercase ).any(dim=0 )
     if attention_mask is None:
          return input_ids[:, keep_column_mask]
     else:
          return (input_ids[:, keep_column_mask], attention_mask[:, keep_column_mask])

class     __a(	_a  ):






    """simple docstring"""





    def __init__( self  ,_SCREAMING_SNAKE_CASE  ,_SCREAMING_SNAKE_CASE  ,_SCREAMING_SNAKE_CASE  ,_SCREAMING_SNAKE_CASE  ,_SCREAMING_SNAKE_CASE="train"  ,_SCREAMING_SNAKE_CASE=None  ,_SCREAMING_SNAKE_CASE=None  ,_SCREAMING_SNAKE_CASE=None  ,_SCREAMING_SNAKE_CASE=""  ,)					->						Tuple:
         super().__init__()
         UpperCAmelCase_     :				Optional[Any]  =     Path(_SCREAMING_SNAKE_CASE    ).joinpath(type_path + '''.source'''    )
         UpperCAmelCase_     :				List[Any]  =     Path(_SCREAMING_SNAKE_CASE    ).joinpath(type_path + '''.target'''    )
         UpperCAmelCase_     :				Tuple  =     self.get_char_lens(self.src_file    )
         UpperCAmelCase_     :				Any  =     max_source_length
         UpperCAmelCase_     :				str  =     max_target_length
         assert min(self.src_lens    ) > 0, f'''found empty line in {self.src_file}'''
         UpperCAmelCase_     :				str  =     tokenizer
         UpperCAmelCase_     :				Union[str, Any]  =     prefix
         if n_obs is not None:
              UpperCAmelCase_     :				Dict  =     self.src_lens[:n_obs]
         UpperCAmelCase_     :				Union[str, Any]  =     src_lang
         UpperCAmelCase_     :				Any  =     tgt_lang





    def __len__( self    )					->						Any:
         return len(self.src_lens    )





    def __getitem__( self  ,_SCREAMING_SNAKE_CASE    )					->						Dict[str, torch.Tensor]:
         UpperCAmelCase_     :				Any  =     index + 1  # linecache starts at 1
         UpperCAmelCase_     :				int  =     self.prefix + linecache.getline(str(self.src_file    )  ,_SCREAMING_SNAKE_CASE    ).rstrip('''\n'''    )
         UpperCAmelCase_     :				int  =     linecache.getline(str(self.tgt_file    )  ,_SCREAMING_SNAKE_CASE    ).rstrip('''\n'''    )
         assert source_line, f'''empty source line for index {index}'''
         assert tgt_line, f'''empty tgt line for index {index}'''

         # Need to add eos token manually for T5
         if isinstance(self.tokenizer  ,_SCREAMING_SNAKE_CASE    ):
              source_line += self.tokenizer.eos_token
              tgt_line += self.tokenizer.eos_token

         # Pad source and target to the right
         UpperCAmelCase_     :				Tuple  =     (
             self.tokenizer.question_encoder if isinstance(self.tokenizer  ,_SCREAMING_SNAKE_CASE    ) else self.tokenizer
         )
         UpperCAmelCase_     :				Dict  =     self.tokenizer.generator if isinstance(self.tokenizer  ,_SCREAMING_SNAKE_CASE    ) else self.tokenizer

         UpperCAmelCase_     :				Tuple  =     encode_line(_SCREAMING_SNAKE_CASE  ,_SCREAMING_SNAKE_CASE  ,self.max_source_length  ,'''right'''    )
         UpperCAmelCase_     :				Tuple  =     encode_line(_SCREAMING_SNAKE_CASE  ,_SCREAMING_SNAKE_CASE  ,self.max_target_length  ,'''right'''    )

         UpperCAmelCase_     :				Optional[Any]  =     source_inputs['''input_ids'''].squeeze()
         UpperCAmelCase_     :				Optional[Any]  =     target_inputs['''input_ids'''].squeeze()
         UpperCAmelCase_     :				Tuple  =     source_inputs['''attention_mask'''].squeeze()
         return {
             "input_ids": source_ids,
             "attention_mask": src_mask,
             "decoder_input_ids": target_ids,
         }





    @staticmethod
    def 				a__ ( _SCREAMING_SNAKE_CASE    )					->						Optional[int]:
         return [len(_SCREAMING_SNAKE_CASE    ) for x in Path(_SCREAMING_SNAKE_CASE    ).open().readlines()]





    def 				a__ ( self  ,_SCREAMING_SNAKE_CASE    )					->						Dict[str, torch.Tensor]:
         UpperCAmelCase_     :				int  =     torch.stack([x['''input_ids'''] for x in batch]    )
         UpperCAmelCase_     :				Dict  =     torch.stack([x['''attention_mask'''] for x in batch]    )
         UpperCAmelCase_     :				Tuple  =     torch.stack([x['''decoder_input_ids'''] for x in batch]    )
         UpperCAmelCase_     :				int  =     (
             self.tokenizer.generator.pad_token_id
             if isinstance(self.tokenizer  ,_SCREAMING_SNAKE_CASE    )
             else self.tokenizer.pad_token_id
         )
         UpperCAmelCase_     :				Tuple  =     (
             self.tokenizer.question_encoder.pad_token_id
             if isinstance(self.tokenizer  ,_SCREAMING_SNAKE_CASE    )
             else self.tokenizer.pad_token_id
         )
         UpperCAmelCase_     :				str  =     trim_batch(_SCREAMING_SNAKE_CASE  ,_SCREAMING_SNAKE_CASE    )
         UpperCAmelCase_,       UpperCAmelCase_     :				Union[str, Any]  =     trim_batch(_SCREAMING_SNAKE_CASE  ,_SCREAMING_SNAKE_CASE  ,attention_mask=_SCREAMING_SNAKE_CASE    )
         UpperCAmelCase_     :				Tuple  =     {
             '''input_ids''': source_ids,
             '''attention_mask''': source_mask,
             '''decoder_input_ids''': y,
         }
         return batch


__a							     =					getLogger(__name__)







def lowerCamelCase__  (     _lowercase ):

     '''simple docstring'''


     return list(itertools.chain.from_iterable(_lowercase ) )







def lowerCamelCase__  (     _lowercase ):

     '''simple docstring'''


     UpperCAmelCase_     :				str  =     get_git_info()
     save_json(_lowercase					,		os.path.join(_lowercase					,		'''git_log.json''' ) )







def lowerCamelCase__  (     _lowercase					,		_lowercase					,		_lowercase=4					,		**_lowercase ):

     '''simple docstring'''


     with open(_lowercase					,		'''w''' ) as f:
          json.dump(_lowercase					,		_lowercase					,		indent=_lowercase					,		**_lowercase )







def lowerCamelCase__  (     _lowercase ):

     '''simple docstring'''


     with open(_lowercase ) as f:
          return json.load(_lowercase )







def lowerCamelCase__  (     ):

     '''simple docstring'''


     UpperCAmelCase_     :				List[Any]  =     git.Repo(search_parent_directories=_lowercase )
     UpperCAmelCase_     :				Union[str, Any]  =     {
         '''repo_id''': str(_lowercase ),
         '''repo_sha''': str(repo.head.object.hexsha ),
         '''repo_branch''': str(repo.active_branch ),
         '''hostname''': str(socket.gethostname() ),
     }
     return repo_infos







def lowerCamelCase__  (     _lowercase					,		_lowercase ):

     '''simple docstring'''


     return list(map(_lowercase					,		_lowercase ) )







def lowerCamelCase__  (     _lowercase					,		_lowercase ):

     '''simple docstring'''


     with open(_lowercase					,		'''wb''' ) as f:
          return pickle.dump(_lowercase					,		_lowercase )







def lowerCamelCase__  (     _lowercase ):

     '''simple docstring'''


     def remove_articles(_lowercase ):
          return re.sub(r'''\b(a|an|the)\b'''					,		''' '''					,		_lowercase )

     def white_space_fix(_lowercase ):
          return " ".join(text.split() )

     def remove_punc(_lowercase ):
          UpperCAmelCase_     :				Any  =     set(string.punctuation )
          return "".join(ch for ch in text if ch not in exclude )

     def lower(_lowercase ):
          return text.lower()

     return white_space_fix(remove_articles(remove_punc(lower(_lowercase ) ) ) )







def lowerCamelCase__  (     _lowercase					,		_lowercase ):

     '''simple docstring'''


     UpperCAmelCase_     :				Any  =     normalize_answer(_lowercase ).split()
     UpperCAmelCase_     :				List[Any]  =     normalize_answer(_lowercase ).split()
     UpperCAmelCase_     :				Any  =     Counter(_lowercase ) & Counter(_lowercase )
     UpperCAmelCase_     :				Tuple  =     sum(common.values() )
     if num_same == 0:
          return 0
     UpperCAmelCase_     :				str  =     1.0 * num_same / len(_lowercase )
     UpperCAmelCase_     :				Union[str, Any]  =     1.0 * num_same / len(_lowercase )
     UpperCAmelCase_     :				Any  =     (2 * precision * recall) / (precision + recall)
     return fa







def lowerCamelCase__  (     _lowercase					,		_lowercase ):

     '''simple docstring'''


     return normalize_answer(_lowercase ) == normalize_answer(_lowercase )







def lowerCamelCase__  (     _lowercase					,		_lowercase ):

     '''simple docstring'''


     assert len(_lowercase ) == len(_lowercase )
     UpperCAmelCase_     :				Optional[int]  =     0
     for hypo, pred in zip(_lowercase					,		_lowercase ):
          em += exact_match_score(_lowercase					,		_lowercase )
     if len(_lowercase ) > 0:
          em /= len(_lowercase )
     return {"em": em}







def lowerCamelCase__  (     _lowercase ):

     '''simple docstring'''


     return model_prefix.startswith('''rag''' )







def lowerCamelCase__  (     _lowercase					,		_lowercase					,		_lowercase ):

     '''simple docstring'''


     UpperCAmelCase_     :				Optional[int]  =     {p: p for p in extra_params}
     # T5 models don't have `dropout` param, they have `dropout_rate` instead
     UpperCAmelCase_     :				Dict  =     '''dropout_rate'''
     for p in extra_params:
          if getattr(_lowercase					,		_lowercase					,		_lowercase ):
               if not hasattr(_lowercase					,		_lowercase ) and not hasattr(_lowercase					,		equivalent_param[p] ):
                    logger.info('''config doesn\'t have a `{}` attribute'''.format(_lowercase ) )
                    delattr(_lowercase					,		_lowercase )
                    continue
               UpperCAmelCase_     :				Union[str, Any]  =     p if hasattr(_lowercase					,		_lowercase ) else equivalent_param[p]
               setattr(_lowercase					,		_lowercase					,		getattr(_lowercase					,		_lowercase ) )
               delattr(_lowercase					,		_lowercase )
     return hparams, config







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     lowerCamelCase_					:







				def __init__(    self							,       __lowerCAmelCase							,       __lowerCAmelCase=1_3							,       __lowerCAmelCase=7							,       __lowerCAmelCase=True							,       __lowerCAmelCase=True							,       __lowerCAmelCase=True							,       __lowerCAmelCase=True							,       __lowerCAmelCase=9_9							,       __lowerCAmelCase=3_2							,       __lowerCAmelCase=2							,       __lowerCAmelCase=4							,       __lowerCAmelCase=3_7							,       __lowerCAmelCase="gelu"							,       __lowerCAmelCase=0.1							,       __lowerCAmelCase=0.1							,       __lowerCAmelCase=5_1_2							,       __lowerCAmelCase=1_6							,       __lowerCAmelCase=2							,       __lowerCAmelCase=0.02							,       __lowerCAmelCase=3							,       __lowerCAmelCase=4							,       __lowerCAmelCase=None							,       ):
								"""simple docstring"""
								__magic_name__		:Optional[int]   =   parent
								__magic_name__		:List[Any]   =   1_3
								__magic_name__		:Union[str, Any]   =   7
								__magic_name__		:Optional[Any]   =   True
								__magic_name__		:Tuple   =   True
								__magic_name__		:List[str]   =   True
								__magic_name__		:List[Any]   =   True
								__magic_name__		:int   =   9_9
								__magic_name__		:Any   =   3_2
								__magic_name__		:Union[str, Any]   =   2
								__magic_name__		:List[str]   =   4
								__magic_name__		:List[Any]   =   3_7
								__magic_name__		:Tuple   =   '''gelu'''
								__magic_name__		:Any   =   0.1
								__magic_name__		:str   =   0.1
								__magic_name__		:List[str]   =   5_1_2
								__magic_name__		:int   =   1_6
								__magic_name__		:Any   =   2
								__magic_name__		:List[Any]   =   0.02
								__magic_name__		:Optional[Any]   =   3
								__magic_name__		:Tuple   =   4
								__magic_name__		:Optional[Any]   =   None







				def       A						(    self  ):
								"""simple docstring"""
								__magic_name__		:Optional[int]   =   ids_tensor([self.batch_size, self.seq_length]							,       self.vocab_size  )

								__magic_name__		:str   =   None
								if self.use_input_mask:
												__magic_name__		:Optional[int]   =   random_attention_mask([self.batch_size, self.seq_length]  )

								__magic_name__		:str   =   None
								if self.use_token_type_ids:
												__magic_name__		:List[Any]   =   ids_tensor([self.batch_size, self.seq_length]							,       self.type_vocab_size  )

								__magic_name__		:Union[str, Any]   =   None
								__magic_name__		:Tuple   =   None
								__magic_name__		:str   =   None
								if self.use_labels:
												__magic_name__		:List[Any]   =   ids_tensor([self.batch_size]							,       self.type_sequence_label_size  )
												__magic_name__		:List[Any]   =   ids_tensor([self.batch_size, self.seq_length]							,       self.num_labels  )
												__magic_name__		:List[Any]   =   ids_tensor([self.batch_size]							,       self.num_choices  )

								__magic_name__		:str   =   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=__lowerCAmelCase							,       )

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







				def       A						(    self							,       __lowerCAmelCase							,       __lowerCAmelCase							,       __lowerCAmelCase							,       __lowerCAmelCase							,       __lowerCAmelCase							,       __lowerCAmelCase							,       __lowerCAmelCase  ):
								"""simple docstring"""
								__magic_name__		:int   =   TFRoFormerModel(config=__lowerCAmelCase  )
								__magic_name__		:Optional[Any]   =   {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids}

								__magic_name__		:List[str]   =   [input_ids, input_mask]
								__magic_name__		:Any   =   model(__lowerCAmelCase  )

								__magic_name__		:List[str]   =   model(__lowerCAmelCase  )

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







				def       A						(    self							,       __lowerCAmelCase							,       __lowerCAmelCase							,       __lowerCAmelCase							,       __lowerCAmelCase							,       __lowerCAmelCase							,       __lowerCAmelCase							,       __lowerCAmelCase  ):
								"""simple docstring"""
								__magic_name__		:Dict   =   True
								__magic_name__		:List[str]   =   TFRoFormerForCausalLM(config=__lowerCAmelCase  )
								__magic_name__		:str   =   {
								    '''input_ids''': input_ids,
								    '''attention_mask''': input_mask,
								    '''token_type_ids''': token_type_ids,
								}
								__magic_name__		:Optional[Any]   =   model(__lowerCAmelCase  )['''logits''']
								self.parent.assertListEqual(
								    list(prediction_scores.numpy().shape  )							,       [self.batch_size, self.seq_length, self.vocab_size]  )







				def       A						(    self							,       __lowerCAmelCase							,       __lowerCAmelCase							,       __lowerCAmelCase							,       __lowerCAmelCase							,       __lowerCAmelCase							,       __lowerCAmelCase							,       __lowerCAmelCase  ):
								"""simple docstring"""
								__magic_name__		:Optional[Any]   =   TFRoFormerForMaskedLM(config=__lowerCAmelCase  )
								__magic_name__		:Any   =   {
								    '''input_ids''': input_ids,
								    '''attention_mask''': input_mask,
								    '''token_type_ids''': token_type_ids,
								}
								__magic_name__		:Dict   =   model(__lowerCAmelCase  )
								self.parent.assertEqual(result.logits.shape							,       (self.batch_size, self.seq_length, self.vocab_size)  )







				def       A						(    self							,       __lowerCAmelCase							,       __lowerCAmelCase							,       __lowerCAmelCase							,       __lowerCAmelCase							,       __lowerCAmelCase							,       __lowerCAmelCase							,       __lowerCAmelCase  ):
								"""simple docstring"""
								__magic_name__		:int   =   self.num_labels
								__magic_name__		:str   =   TFRoFormerForSequenceClassification(config=__lowerCAmelCase  )
								__magic_name__		:Optional[int]   =   {
								    '''input_ids''': input_ids,
								    '''attention_mask''': input_mask,
								    '''token_type_ids''': token_type_ids,
								}

								__magic_name__		:str   =   model(__lowerCAmelCase  )
								self.parent.assertEqual(result.logits.shape							,       (self.batch_size, self.num_labels)  )







				def       A						(    self							,       __lowerCAmelCase							,       __lowerCAmelCase							,       __lowerCAmelCase							,       __lowerCAmelCase							,       __lowerCAmelCase							,       __lowerCAmelCase							,       __lowerCAmelCase  ):
								"""simple docstring"""
								__magic_name__		:Union[str, Any]   =   self.num_choices
								__magic_name__		:Tuple   =   TFRoFormerForMultipleChoice(config=__lowerCAmelCase  )
								__magic_name__		:int   =   tf.tile(tf.expand_dims(__lowerCAmelCase							,       1  )							,       (1, self.num_choices, 1)  )
								__magic_name__		:Optional[Any]   =   tf.tile(tf.expand_dims(__lowerCAmelCase							,       1  )							,       (1, self.num_choices, 1)  )
								__magic_name__		:Union[str, Any]   =   tf.tile(tf.expand_dims(__lowerCAmelCase							,       1  )							,       (1, self.num_choices, 1)  )
								__magic_name__		:str   =   {
								    '''input_ids''': multiple_choice_inputs_ids,
								    '''attention_mask''': multiple_choice_input_mask,
								    '''token_type_ids''': multiple_choice_token_type_ids,
								}
								__magic_name__		:Tuple   =   model(__lowerCAmelCase  )
								self.parent.assertEqual(result.logits.shape							,       (self.batch_size, self.num_choices)  )







				def       A						(    self							,       __lowerCAmelCase							,       __lowerCAmelCase							,       __lowerCAmelCase							,       __lowerCAmelCase							,       __lowerCAmelCase							,       __lowerCAmelCase							,       __lowerCAmelCase  ):
								"""simple docstring"""
								__magic_name__		:Optional[int]   =   self.num_labels
								__magic_name__		:Any   =   TFRoFormerForTokenClassification(config=__lowerCAmelCase  )
								__magic_name__		:str   =   {
								    '''input_ids''': input_ids,
								    '''attention_mask''': input_mask,
								    '''token_type_ids''': token_type_ids,
								}
								__magic_name__		:Dict   =   model(__lowerCAmelCase  )
								self.parent.assertEqual(result.logits.shape							,       (self.batch_size, self.seq_length, self.num_labels)  )







				def       A						(    self							,       __lowerCAmelCase							,       __lowerCAmelCase							,       __lowerCAmelCase							,       __lowerCAmelCase							,       __lowerCAmelCase							,       __lowerCAmelCase							,       __lowerCAmelCase  ):
								"""simple docstring"""
								__magic_name__		:List[str]   =   TFRoFormerForQuestionAnswering(config=__lowerCAmelCase  )
								__magic_name__		:List[str]   =   {
								    '''input_ids''': input_ids,
								    '''attention_mask''': input_mask,
								    '''token_type_ids''': token_type_ids,
								}

								__magic_name__		:Union[str, Any]   =   model(__lowerCAmelCase  )
								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  ):
								"""simple docstring"""
								__magic_name__		:Union[str, Any]   =   self.prepare_config_and_inputs()
								(
								    (
								    __magic_name__
								)  ,					(
								    __magic_name__
								)  ,					(
								    __magic_name__
								)  ,					(
								    __magic_name__
								)  ,					(
								    __magic_name__
								)  ,					(
								    __magic_name__
								)  ,					(
								    __magic_name__
								)  ,					
								)		:Union[str, Any]   =   config_and_inputs
								__magic_name__		:Optional[Any]   =   {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask}
								return config, inputs_dict







@require_tf
class     lowerCamelCase_					(   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							,       __lowerCAmelCase							,       __lowerCAmelCase							,       __lowerCAmelCase							,       __lowerCAmelCase							,       __lowerCAmelCase  ):
								"""simple docstring"""
								if pipeline_test_casse_name == "TextGenerationPipelineTests":
												return True

								return False







				def       A						(    self  ):
								"""simple docstring"""
								__magic_name__		:List[str]   =   TFRoFormerModelTester(self  )
								__magic_name__		:List[str]   =   ConfigTester(self							,       config_class=__lowerCAmelCase							,       hidden_size=3_7  )







				def       A						(    self  ):
								"""simple docstring"""
								self.config_tester.run_common_tests()







				def       A						(    self  ):
								"""simple docstring"""
								__magic_name__		:Optional[Any]   =   self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(*__lowerCAmelCase  )







				def       A						(    self  ):
								"""simple docstring"""
								__magic_name__		:Union[str, Any]   =   self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_masked_lm(*__lowerCAmelCase  )







				def       A						(    self  ):
								"""simple docstring"""
								__magic_name__		:Tuple   =   self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_lm_head(*__lowerCAmelCase  )







				def       A						(    self  ):
								"""simple docstring"""
								__magic_name__		:Optional[Any]   =   self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_multiple_choice(*__lowerCAmelCase  )







				def       A						(    self  ):
								"""simple docstring"""
								__magic_name__		:Tuple   =   self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_question_answering(*__lowerCAmelCase  )







				def       A						(    self  ):
								"""simple docstring"""
								__magic_name__		:Dict   =   self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_sequence_classification(*__lowerCAmelCase  )







				def       A						(    self  ):
								"""simple docstring"""
								__magic_name__		:Optional[int]   =   self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_token_classification(*__lowerCAmelCase  )







				@slow
				def       A						(    self  ):
								"""simple docstring"""
								__magic_name__		:Optional[Any]   =   TFRoFormerModel.from_pretrained('''junnyu/roformer_chinese_base'''  )
								self.assertIsNotNone(__lowerCAmelCase  )







@require_tf
class     lowerCamelCase_					(   unittest.TestCase			):







				@slow
				def       A						(    self  ):
								"""simple docstring"""
								__magic_name__		:int   =   TFRoFormerForMaskedLM.from_pretrained('''junnyu/roformer_chinese_base'''  )
								__magic_name__		:Dict   =   tf.constant([[0, 1, 2, 3, 4, 5]]  )
								__magic_name__		:Optional[Any]   =   model(__lowerCAmelCase  )[0]

								# TODO Replace vocab size
								__magic_name__		:int   =   5_0_0_0_0

								__magic_name__		:Tuple   =   [1, 6, vocab_size]
								self.assertEqual(output.shape							,       __lowerCAmelCase  )

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

								# TODO Replace values below with what was printed above.
								__magic_name__		:Any   =   tf.constant(
								    [
								        [
								            [-0.12053341, -1.0264901, 0.29221946],
								            [-1.5133783, 0.197433, 0.15190607],
								            [-5.0135403, -3.900256, -0.84038764],
								        ]
								    ]  )
								tf.debugging.assert_near(output[:, :3, :3]							,       __lowerCAmelCase							,       atol=1E-4  )







@require_tf
class     lowerCamelCase_					(   unittest.TestCase			):
				a__       							=	1e-4







				def       A						(    self  ):
								"""simple docstring"""
								__magic_name__		:Optional[int]   =   tf.constant([[4, 1_0]]  )
								__magic_name__		:Optional[int]   =   TFRoFormerSinusoidalPositionalEmbedding(num_positions=6							,       embedding_dim=6  )

								__magic_name__		:Optional[Any]   =   emba(input_ids.shape  )
								__magic_name__		:List[str]   =   tf.constant(
								    [[0.0000, 0.0000, 0.0000, 1.0000, 1.0000, 1.0000], [0.8415, 0.0464, 0.0022, 0.5403, 0.9989, 1.0000]]  )

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







				def       A						(    self  ):
								"""simple docstring"""
								__magic_name__		:Tuple   =   tf.constant(
								    [
								        [0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
								        [0.8415, 0.8219, 0.8020, 0.7819, 0.7617],
								        [0.9093, 0.9364, 0.9581, 0.9749, 0.9870],
								    ]  )
								__magic_name__		:Union[str, Any]   =   TFRoFormerSinusoidalPositionalEmbedding(num_positions=5_1_2							,       embedding_dim=5_1_2  )
								emba([2, 1_6, 5_1_2]  )
								__magic_name__		:Optional[int]   =   emba.weight[:3, :5]

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







@require_tf
class     lowerCamelCase_					(   unittest.TestCase			):
				a__       							=	1e-4







				def       A						(    self  ):
								"""simple docstring"""
								# 2,12,16,64
								__magic_name__		:int   =   tf.reshape(tf.range(2 * 1_2 * 1_6 * 6_4							,       dtype=tf.floataa  )							,       shape=(2, 1_2, 1_6, 6_4)  ) / 1_0_0

								__magic_name__		:str   =   -tf.reshape(tf.range(2 * 1_2 * 1_6 * 6_4							,       dtype=tf.floataa  )							,       shape=(2, 1_2, 1_6, 6_4)  ) / 1_0_0

								__magic_name__		:int   =   TFRoFormerSinusoidalPositionalEmbedding(num_positions=3_2							,       embedding_dim=6_4  )
								__magic_name__		:List[str]   =   embed_positions([2, 1_6, 7_6_8]  )[None, None, :, :]

								__magic_name__  ,					__magic_name__		:Union[str, Any]   =   TFRoFormerSelfAttention.apply_rotary_position_embeddings(
								    __lowerCAmelCase							,       __lowerCAmelCase							,       __lowerCAmelCase  )

								__magic_name__		:Tuple   =   tf.constant(
								    [
								        [0.0000, 0.0100, 0.0200, 0.0300, 0.0400, 0.0500, 0.0600, 0.0700],
								        [-0.2012, 0.8897, 0.0263, 0.9401, 0.2074, 0.9463, 0.3481, 0.9343],
								        [-1.7057, 0.6271, -1.2145, 1.3897, -0.6303, 1.7647, -0.1173, 1.8985],
								        [-2.1731, -1.6397, -2.7358, 0.2854, -2.1840, 1.7183, -1.3018, 2.4871],
								        [0.2717, -3.6173, -2.9206, -2.1988, -3.6638, 0.3858, -2.9155, 2.2980],
								        [3.9859, -2.1580, -0.7984, -4.4904, -4.1181, -2.0252, -4.4782, 1.1253],
								    ]  )
								__magic_name__		:List[str]   =   tf.constant(
								    [
								        [0.0000, -0.0100, -0.0200, -0.0300, -0.0400, -0.0500, -0.0600, -0.0700],
								        [0.2012, -0.8897, -0.0263, -0.9401, -0.2074, -0.9463, -0.3481, -0.9343],
								        [1.7057, -0.6271, 1.2145, -1.3897, 0.6303, -1.7647, 0.1173, -1.8985],
								        [2.1731, 1.6397, 2.7358, -0.2854, 2.1840, -1.7183, 1.3018, -2.4871],
								        [-0.2717, 3.6173, 2.9206, 2.1988, 3.6638, -0.3858, 2.9155, -2.2980],
								        [-3.9859, 2.1580, 0.7984, 4.4904, 4.1181, 2.0252, 4.4782, -1.1253],
								    ]  )

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






