



'''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_							:
      _lowerCAmelCase     :   List[Any]	     =				XGLMConfig
      _lowerCAmelCase     :   List[str]	     =				{}
      _lowerCAmelCase     :   Any	     =				'gelu'







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

             """simple docstring"""
             SCREAMING_SNAKE_CASE					:      Any     					=			parent
             SCREAMING_SNAKE_CASE					:      int     					=			batch_size
             SCREAMING_SNAKE_CASE					:      Any     					=			seq_length
             SCREAMING_SNAKE_CASE					:      Optional[int]     					=			is_training
             SCREAMING_SNAKE_CASE					:      int     					=			use_input_mask
             SCREAMING_SNAKE_CASE					:      int     					=			use_labels
             SCREAMING_SNAKE_CASE					:      Optional[int]     					=			vocab_size
             SCREAMING_SNAKE_CASE					:      int     					=			d_model
             SCREAMING_SNAKE_CASE					:      Tuple     					=			num_hidden_layers
             SCREAMING_SNAKE_CASE					:      List[Any]     					=			num_attention_heads
             SCREAMING_SNAKE_CASE					:      int     					=			ffn_dim
             SCREAMING_SNAKE_CASE					:      int     					=			activation_function
             SCREAMING_SNAKE_CASE					:      List[str]     					=			activation_dropout
             SCREAMING_SNAKE_CASE					:      Optional[Any]     					=			attention_dropout
             SCREAMING_SNAKE_CASE					:      List[Any]     					=			max_position_embeddings
             SCREAMING_SNAKE_CASE					:      Any     					=			initializer_range
             SCREAMING_SNAKE_CASE					:      Optional[Any]     					=			None
             SCREAMING_SNAKE_CASE					:      List[Any]     					=			0
             SCREAMING_SNAKE_CASE					:      Any     					=			2
             SCREAMING_SNAKE_CASE					:      Tuple     					=			1







      def 					__lowercase    (  self   :      str				):

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







      def 					__lowercase    (  self   :      Dict				):

             """simple docstring"""
             SCREAMING_SNAKE_CASE					:      Optional[int]     					=			tf.clip_by_value(
                 ids_tensor([self.batch_size, self.seq_length]				,    self.vocab_size				)				,    clip_value_min=0				,    clip_value_max=3				)

             SCREAMING_SNAKE_CASE					:      Tuple     					=			None
             if self.use_input_mask:
                    SCREAMING_SNAKE_CASE					:      Dict     					=			random_attention_mask([self.batch_size, self.seq_length]				)

             SCREAMING_SNAKE_CASE					:      int     					=			self.get_config()

             SCREAMING_SNAKE_CASE					:      Dict     					=			floats_tensor([self.num_hidden_layers, self.num_attention_heads]				,    2				)

             return (
                 config,
                 input_ids,
                 input_mask,
                 head_mask,
             )







      def 					__lowercase    (  self   :      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 					__lowercase    (  self   :      Dict				):

             """simple docstring"""
             SCREAMING_SNAKE_CASE					:      Any     					=			self.prepare_config_and_inputs()

             (
                 (
                 SCREAMING_SNAKE_CASE					
             )					,(
                 SCREAMING_SNAKE_CASE					
             )					,(
                 SCREAMING_SNAKE_CASE					
             )					,(
                 SCREAMING_SNAKE_CASE					
             )					,					
             )					:      int     					=			config_and_inputs

             SCREAMING_SNAKE_CASE					:      Optional[Any]     					=			{
                 '''input_ids''': input_ids,
                 '''head_mask''': head_mask,
             }

             return config, inputs_dict


@require_tf
class 	lowerCamelCase_							(					snake_case_    ,				snake_case_    ,				unittest.TestCase			):
      _lowerCAmelCase     :   Optional[Any]	     =				(TFXGLMModel, TFXGLMForCausalLM) if is_tf_available() else ()
      _lowerCAmelCase     :   int	     =				(TFXGLMForCausalLM,) if is_tf_available() else ()
      _lowerCAmelCase     :   List[str]	     =				(
          {'feature-extraction': TFXGLMModel, 'text-generation': TFXGLMForCausalLM} if is_tf_available() else {}
      )
      _lowerCAmelCase     :   Any	     =				False
      _lowerCAmelCase     :   Union[str, Any]	     =				False
      _lowerCAmelCase     :   Tuple	     =				False







      def 					__lowercase    (  self   :      Tuple				):

             """simple docstring"""
             SCREAMING_SNAKE_CASE					:      Union[str, Any]     					=			TFXGLMModelTester(self				)
             SCREAMING_SNAKE_CASE					:      str     					=			ConfigTester(self				,    config_class=_UpperCAmelCase				,    n_embd=37				)







      def 					__lowercase    (  self   :      Any				):

             """simple docstring"""
             self.config_tester.run_common_tests()







      @slow
      def 					__lowercase    (  self   :      List[str]				):

             """simple docstring"""




             for model_name in TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                    SCREAMING_SNAKE_CASE					:      int     					=			TFXGLMModel.from_pretrained(_UpperCAmelCase				)
                    self.assertIsNotNone(_UpperCAmelCase				)







      @unittest.skip(reason='''Currently, model embeddings are going to undergo a major refactor.'''				)
      def 					__lowercase    (  self   :      List[str]				):

             """simple docstring"""
             super().test_resize_token_embeddings()


@require_tf
class 	lowerCamelCase_							(					unittest.TestCase			):







      @slow
      def 					__lowercase    (  self   :      str				,    lowerCAmelCase__   :      List[Any]=True				):

             """simple docstring"""
             SCREAMING_SNAKE_CASE					:      Any     					=			TFXGLMForCausalLM.from_pretrained('''facebook/xglm-564M'''				)
             SCREAMING_SNAKE_CASE					:      List[Any]     					=			tf.convert_to_tensor([[2, 2_68, 98_65]]				,    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
             SCREAMING_SNAKE_CASE					:      str     					=			[2, 2_68, 98_65, 67, 11, 19_88, 5_72_52, 98_65, 5, 9_84, 67, 19_88, 21_38_38, 16_58, 53, 7_04_46, 33, 66_57, 2_78, 15_81]
             # fmt: on
             SCREAMING_SNAKE_CASE					:      Union[str, Any]     					=			model.generate(_UpperCAmelCase				,    do_sample=_UpperCAmelCase				,    num_beams=1				)
             if verify_outputs:
                    self.assertListEqual(output_ids[0].numpy().tolist()				,    _UpperCAmelCase				)







      @slow
      def 					__lowercase    (  self   :      str				):

             """simple docstring"""
             SCREAMING_SNAKE_CASE					:      Union[str, Any]     					=			XGLMTokenizer.from_pretrained('''facebook/xglm-564M'''				)
             SCREAMING_SNAKE_CASE					:      str     					=			TFXGLMForCausalLM.from_pretrained('''facebook/xglm-564M'''				)

             tf.random.set_seed(0				)
             SCREAMING_SNAKE_CASE					:      List[str]     					=			tokenizer('''Today is a nice day and'''				,    return_tensors='''tf'''				)
             SCREAMING_SNAKE_CASE					:      Optional[int]     					=			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'''				):
                    SCREAMING_SNAKE_CASE					:      Union[str, Any]     					=			model.generate(_UpperCAmelCase				,    do_sample=_UpperCAmelCase				,    seed=[7, 0]				)
             SCREAMING_SNAKE_CASE					:      int     					=			tokenizer.decode(output_ids[0]				,    skip_special_tokens=_UpperCAmelCase				)

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







      @slow
      def 					__lowercase    (  self   :      str				):

             """simple docstring"""
             SCREAMING_SNAKE_CASE					:      Tuple     					=			TFXGLMForCausalLM.from_pretrained('''facebook/xglm-564M'''				)
             SCREAMING_SNAKE_CASE					:      Optional[Any]     					=			XGLMTokenizer.from_pretrained('''facebook/xglm-564M'''				)

             SCREAMING_SNAKE_CASE					:      Optional[int]     					=			'''left'''

             # use different length sentences to test batching
             SCREAMING_SNAKE_CASE					:      Optional[int]     					=			[
                 '''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''',
             ]

             SCREAMING_SNAKE_CASE					:      Union[str, Any]     					=			tokenizer(_UpperCAmelCase				,    return_tensors='''tf'''				,    padding=_UpperCAmelCase				)
             SCREAMING_SNAKE_CASE					:      List[str]     					=			inputs['''input_ids''']

             SCREAMING_SNAKE_CASE					:      str     					=			model.generate(input_ids=_UpperCAmelCase				,    attention_mask=inputs['''attention_mask''']				,    max_new_tokens=12				)

             SCREAMING_SNAKE_CASE					:      List[Any]     					=			tokenizer(sentences[0]				,    return_tensors='''tf'''				).input_ids
             SCREAMING_SNAKE_CASE					:      Dict     					=			model.generate(input_ids=_UpperCAmelCase				,    max_new_tokens=12				)

             SCREAMING_SNAKE_CASE					:      Union[str, Any]     					=			tokenizer(sentences[1]				,    return_tensors='''tf'''				).input_ids
             SCREAMING_SNAKE_CASE					:      Union[str, Any]     					=			model.generate(input_ids=_UpperCAmelCase				,    max_new_tokens=12				)

             SCREAMING_SNAKE_CASE					:      Tuple     					=			tokenizer.batch_decode(_UpperCAmelCase				,    skip_special_tokens=_UpperCAmelCase				)
             SCREAMING_SNAKE_CASE					:      Dict     					=			tokenizer.decode(output_non_padded[0]				,    skip_special_tokens=_UpperCAmelCase				)
             SCREAMING_SNAKE_CASE					:      Optional[int]     					=			tokenizer.decode(output_padded[0]				,    skip_special_tokens=_UpperCAmelCase				)

             SCREAMING_SNAKE_CASE					:      Dict     					=			[
                 '''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 typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_sentencepiece_available,
    is_tokenizers_available,
    is_torch_available,
)


lowerCAmelCase_     :       str								=						{
    'configuration_llama': ['LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP', 'LlamaConfig'],
}

try:
							if not is_sentencepiece_available():
														raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
							pass
else:
							lowerCAmelCase_     :       Dict								=						['LlamaTokenizer']

try:
							if not is_tokenizers_available():
														raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
							pass
else:
							lowerCAmelCase_     :       str								=						['LlamaTokenizerFast']

try:
							if not is_torch_available():
														raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
							pass
else:
							lowerCAmelCase_     :       Optional[int]								=						[
							    'LlamaForCausalLM',
							    'LlamaModel',
							    'LlamaPreTrainedModel',
							    'LlamaForSequenceClassification',
							]


if TYPE_CHECKING:
							from .configuration_llama import LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP, LlamaConfig

							try:
														if not is_sentencepiece_available():
																					raise OptionalDependencyNotAvailable()
							except OptionalDependencyNotAvailable:
														pass
							else:
														from .tokenization_llama import LlamaTokenizer

							try:
														if not is_tokenizers_available():
																					raise OptionalDependencyNotAvailable()
							except OptionalDependencyNotAvailable:
														pass
							else:
														from .tokenization_llama_fast import LlamaTokenizerFast

							try:
														if not is_torch_available():
																					raise OptionalDependencyNotAvailable()
							except OptionalDependencyNotAvailable:
														pass
							else:
														from .modeling_llama import LlamaForCausalLM, LlamaForSequenceClassification, LlamaModel, LlamaPreTrainedModel


else:
							import sys

							lowerCAmelCase_     :       Optional[Any]								=						_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)




