


'''simple docstring'''

from __future__ import annotations

import unittest

from transformers import XGLMConfig, XGLMTokenizer, is_tf_available
from transformers.testing_utils import require_tf, slow

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


if is_tf_available():
 import tensorflow as tf

 from transformers.models.xglm.modeling_tf_xglm import (
     TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST,
     TFXGLMForCausalLM,
     TFXGLMModel,
 )
@require_tf
class   __lowerCAmelCase						:





      '''simple docstring'''






      lowerCAmelCase__					:     Union[str, Any]  					=							XGLMConfig
      lowerCAmelCase__					:     Tuple  					=							{}
      lowerCAmelCase__					:     Optional[int]  					=							"""gelu"""



      def __init__(self    :    str   ,						UpperCamelCase    :    Dict   ,						UpperCamelCase    :    List[Any]=14   ,						UpperCamelCase    :    List[str]=7   ,						UpperCamelCase    :    int=True   ,						UpperCamelCase    :    int=True   ,						UpperCamelCase    :    Any=True   ,						UpperCamelCase    :    int=99   ,						UpperCamelCase    :    str=32   ,						UpperCamelCase    :    Optional[int]=2   ,						UpperCamelCase    :    str=4   ,						UpperCamelCase    :    Union[str, Any]=37   ,						UpperCamelCase    :    Optional[int]="gelu"   ,						UpperCamelCase    :    List[Any]=0.1   ,						UpperCamelCase    :    int=0.1   ,						UpperCamelCase    :    Union[str, Any]=512   ,						UpperCamelCase    :    Optional[Any]=0.02   ,						):

             '''simple docstring'''







             lowercase__      			= parent
             lowercase__      			= batch_size
             lowercase__      			= seq_length
             lowercase__      			= is_training
             lowercase__      			= use_input_mask
             lowercase__      			= use_labels
             lowercase__      			= vocab_size
             lowercase__      			= d_model
             lowercase__      			= num_hidden_layers
             lowercase__      			= num_attention_heads
             lowercase__      			= ffn_dim
             lowercase__      			= activation_function
             lowercase__      			= activation_dropout
             lowercase__      			= attention_dropout
             lowercase__      			= max_position_embeddings
             lowercase__      			= initializer_range
             lowercase__      			= None
             lowercase__      			= 0
             lowercase__      			= 2
             lowercase__      			= 1



      def       UpperCamelCase__		(self    :    List[str] ):

             '''simple docstring'''







             return XGLMConfig.from_pretrained('''facebook/xglm-564M''' )



      def       UpperCamelCase__		(self    :    int ):

             '''simple docstring'''







             lowercase__      			= tf.clip_by_value(
                 ids_tensor([self.batch_size, self.seq_length]   ,						self.vocab_size )   ,						clip_value_min=0   ,						clip_value_max=3 )

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

             lowercase__      			= self.get_config()

             lowercase__      			= floats_tensor([self.num_hidden_layers, self.num_attention_heads]   ,						2 )

             return (
                 config,
                 input_ids,
                 input_mask,
                 head_mask,
             )



      def       UpperCamelCase__		(self    :    Union[str, Any] ):

             '''simple docstring'''







             return XGLMConfig(
                 vocab_size=self.vocab_size   ,						d_model=self.hidden_size   ,						num_layers=self.num_hidden_layers   ,						attention_heads=self.num_attention_heads   ,						ffn_dim=self.ffn_dim   ,						activation_function=self.activation_function   ,						activation_dropout=self.activation_dropout   ,						attention_dropout=self.attention_dropout   ,						max_position_embeddings=self.max_position_embeddings   ,						initializer_range=self.initializer_range   ,						use_cache=UpperCamelCase   ,						bos_token_id=self.bos_token_id   ,						eos_token_id=self.eos_token_id   ,						pad_token_id=self.pad_token_id   ,						return_dict=UpperCamelCase   ,						)






      def       UpperCamelCase__		(self    :    Dict ):

             '''simple docstring'''







             lowercase__      			= self.prepare_config_and_inputs()

             (
                 (
                 lowercase__
             )			,(
                 lowercase__
             )			,(
                 lowercase__
             )			,(
                 lowercase__
             )			,
             )      			= config_and_inputs

             lowercase__      			= {
                 '''input_ids''': input_ids,
                 '''head_mask''': head_mask,
             }

             return config, inputs_dict






@require_tf
class   __lowerCAmelCase						(lowercase_  ,     lowercase_  ,     unittest.TestCase     ):





      '''simple docstring'''






      lowerCAmelCase__					:     Tuple  					=							(TFXGLMModel, TFXGLMForCausalLM) if is_tf_available() else ()
      lowerCAmelCase__					:     List[str]  					=							(TFXGLMForCausalLM,) if is_tf_available() else ()
      lowerCAmelCase__					:     Union[str, Any]  					=							(
          {"""feature-extraction""": TFXGLMModel, """text-generation""": TFXGLMForCausalLM} if is_tf_available() else {}
      )
      lowerCAmelCase__					:     Dict  					=							False
      lowerCAmelCase__					:     Optional[int]  					=							False
      lowerCAmelCase__					:     Optional[int]  					=							False



      def       UpperCamelCase__		(self    :    int ):

             '''simple docstring'''







             lowercase__      			= TFXGLMModelTester(self )
             lowercase__      			= ConfigTester(self   ,						config_class=UpperCamelCase   ,						n_embd=37 )



      def       UpperCamelCase__		(self    :    Tuple ):

             '''simple docstring'''







             self.config_tester.run_common_tests()



      @slow
      def       UpperCamelCase__		(self    :    Optional[Any] ):

             '''simple docstring'''







             for model_name in TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                    lowercase__      			= TFXGLMModel.from_pretrained(UpperCamelCase )
                    self.assertIsNotNone(UpperCamelCase )






      @unittest.skip(reason='''Currently, model embeddings are going to undergo a major refactor.''' )
      def       UpperCamelCase__		(self    :    Any ):

             '''simple docstring'''







             super().test_resize_token_embeddings()






@require_tf
class   __lowerCAmelCase						(unittest.TestCase     ):





      '''simple docstring'''






      @slow
      def       UpperCamelCase__		(self    :    Dict   ,						UpperCamelCase    :    Optional[Any]=True ):

             '''simple docstring'''







             lowercase__      			= TFXGLMForCausalLM.from_pretrained('''facebook/xglm-564M''' )
             lowercase__      			= tf.convert_to_tensor([[2, 268, 9865]]   ,						dtype=tf.intaa )  # The dog
             # </s> The dog is a very friendly dog. He is very affectionate and loves to play with other
             # fmt: off
             lowercase__      			= [2, 268, 9865, 67, 11, 1988, 57252, 9865, 5, 984, 67, 1988, 213838, 1658, 53, 70446, 33, 6657, 278, 1581]
             # fmt: on
             lowercase__      			= model.generate(UpperCamelCase   ,						do_sample=UpperCamelCase   ,						num_beams=1 )
             if verify_outputs:
                    self.assertListEqual(output_ids[0].numpy().tolist()   ,						UpperCamelCase )



      @slow
      def       UpperCamelCase__		(self    :    List[Any] ):

             '''simple docstring'''







             lowercase__      			= XGLMTokenizer.from_pretrained('''facebook/xglm-564M''' )
             lowercase__      			= TFXGLMForCausalLM.from_pretrained('''facebook/xglm-564M''' )

             tf.random.set_seed(0 )
             lowercase__      			= tokenizer('''Today is a nice day and'''   ,						return_tensors='''tf''' )
             lowercase__      			= tokenized.input_ids
             # forces the generation to happen on CPU, to avoid GPU-related quirks (and assure same output regardless of the available devices)
             with tf.device(''':/CPU:0''' ):
                    lowercase__      			= model.generate(UpperCamelCase   ,						do_sample=UpperCamelCase   ,						seed=[7, 0] )
             lowercase__      			= tokenizer.decode(output_ids[0]   ,						skip_special_tokens=UpperCamelCase )

             lowercase__      			= (
                 '''Today is a nice day and warm evening here over Southern Alberta!! Today when they closed schools due'''
             )
             self.assertEqual(UpperCamelCase   ,						UpperCamelCase )






      @slow
      def       UpperCamelCase__		(self    :    Dict ):

             '''simple docstring'''







             lowercase__      			= TFXGLMForCausalLM.from_pretrained('''facebook/xglm-564M''' )
             lowercase__      			= XGLMTokenizer.from_pretrained('''facebook/xglm-564M''' )

             lowercase__      			= '''left'''

             # use different length sentences to test batching
             lowercase__      			= [
                 '''This is an extremelly long sentence that only exists to test the ability of the model to cope with '''
                 '''left-padding, such as in batched generation. The output for the sequence below should be the same '''
                 '''regardless of whether left padding is applied or not. When''',
                 '''Hello, my dog is a little''',
             ]

             lowercase__      			= tokenizer(UpperCamelCase   ,						return_tensors='''tf'''   ,						padding=UpperCamelCase )
             lowercase__      			= inputs['''input_ids''']

             lowercase__      			= model.generate(input_ids=UpperCamelCase   ,						attention_mask=inputs['''attention_mask''']   ,						max_new_tokens=12 )

             lowercase__      			= tokenizer(sentences[0]   ,						return_tensors='''tf''' ).input_ids
             lowercase__      			= model.generate(input_ids=UpperCamelCase   ,						max_new_tokens=12 )

             lowercase__      			= tokenizer(sentences[1]   ,						return_tensors='''tf''' ).input_ids
             lowercase__      			= model.generate(input_ids=UpperCamelCase   ,						max_new_tokens=12 )

             lowercase__      			= tokenizer.batch_decode(UpperCamelCase   ,						skip_special_tokens=UpperCamelCase )
             lowercase__      			= tokenizer.decode(output_non_padded[0]   ,						skip_special_tokens=UpperCamelCase )
             lowercase__      			= tokenizer.decode(output_padded[0]   ,						skip_special_tokens=UpperCamelCase )

             lowercase__      			= [
                 '''This is an extremelly long sentence that only exists to test the ability of the model to cope with '''
                 '''left-padding, such as in batched generation. The output for the sequence below should be the same '''
                 '''regardless of whether left padding is applied or not. When left padding is applied, the sequence will be '''
                 '''a single''',
                 '''Hello, my dog is a little bit of a shy one, but he is very friendly''',
             ]
             self.assertListEqual(UpperCamelCase   ,						UpperCamelCase )
             self.assertListEqual(UpperCamelCase   ,						[non_padded_sentence, padded_sentence] )








'''simple docstring'''

from ...configuration_utils import PretrainedConfig
from ...utils import logging


lowerCamelCase							:   int  						=	logging.get_logger(__name__)

lowerCamelCase							:   List[Any]  						=	{
    'google/realm-cc-news-pretrained-embedder': (
        'https://huggingface.co/google/realm-cc-news-pretrained-embedder/resolve/main/config.json'
    ),
    'google/realm-cc-news-pretrained-encoder': (
        'https://huggingface.co/google/realm-cc-news-pretrained-encoder/resolve/main/config.json'
    ),
    'google/realm-cc-news-pretrained-scorer': (
        'https://huggingface.co/google/realm-cc-news-pretrained-scorer/resolve/main/config.json'
    ),
    'google/realm-cc-news-pretrained-openqa': (
        'https://huggingface.co/google/realm-cc-news-pretrained-openqa/aresolve/main/config.json'
    ),
    'google/realm-orqa-nq-openqa': 'https://huggingface.co/google/realm-orqa-nq-openqa/resolve/main/config.json',
    'google/realm-orqa-nq-reader': 'https://huggingface.co/google/realm-orqa-nq-reader/resolve/main/config.json',
    'google/realm-orqa-wq-openqa': 'https://huggingface.co/google/realm-orqa-wq-openqa/resolve/main/config.json',
    'google/realm-orqa-wq-reader': 'https://huggingface.co/google/realm-orqa-wq-reader/resolve/main/config.json',
    # See all REALM models at https://huggingface.co/models?filter=realm
}
class   __lowerCAmelCase						(lowercase_     ):





      '''simple docstring'''






      lowerCAmelCase__					:     Optional[int]  					=							"""realm"""



      def __init__(self    :    str   ,						UpperCamelCase    :    List[Any]=30522   ,						UpperCamelCase    :    List[Any]=768   ,						UpperCamelCase    :    int=128   ,						UpperCamelCase    :    Any=12   ,						UpperCamelCase    :    Tuple=12   ,						UpperCamelCase    :    List[Any]=8   ,						UpperCamelCase    :    Union[str, Any]=3072   ,						UpperCamelCase    :    List[str]="gelu_new"   ,						UpperCamelCase    :    Any=0.1   ,						UpperCamelCase    :    List[str]=0.1   ,						UpperCamelCase    :    Dict=512   ,						UpperCamelCase    :    Dict=2   ,						UpperCamelCase    :    List[Any]=0.02   ,						UpperCamelCase    :    List[Any]=1E-12   ,						UpperCamelCase    :    Dict=256   ,						UpperCamelCase    :    Union[str, Any]=10   ,						UpperCamelCase    :    Optional[int]=1E-3   ,						UpperCamelCase    :    Tuple=5   ,						UpperCamelCase    :    Optional[int]=320   ,						UpperCamelCase    :    List[str]=13353718   ,						UpperCamelCase    :    Optional[Any]=5000   ,						UpperCamelCase    :    str=1   ,						UpperCamelCase    :    Union[str, Any]=0   ,						UpperCamelCase    :    List[Any]=2   ,						**UpperCamelCase    :    int   ,						):

             '''simple docstring'''







             super().__init__(pad_token_id=UpperCamelCase   ,						bos_token_id=UpperCamelCase   ,						eos_token_id=UpperCamelCase   ,						**UpperCamelCase )

             # Common config
             lowercase__      			= vocab_size
             lowercase__      			= max_position_embeddings
             lowercase__      			= hidden_size
             lowercase__      			= retriever_proj_size
             lowercase__      			= num_hidden_layers
             lowercase__      			= num_attention_heads
             lowercase__      			= num_candidates
             lowercase__      			= intermediate_size
             lowercase__      			= hidden_act
             lowercase__      			= hidden_dropout_prob
             lowercase__      			= attention_probs_dropout_prob
             lowercase__      			= initializer_range
             lowercase__      			= type_vocab_size
             lowercase__      			= layer_norm_eps

             # Reader config
             lowercase__      			= span_hidden_size
             lowercase__      			= max_span_width
             lowercase__      			= reader_layer_norm_eps
             lowercase__      			= reader_beam_size
             lowercase__      			= reader_seq_len

             # Retrieval config
             lowercase__      			= num_block_records
             lowercase__      			= searcher_beam_size




