



'''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     UpperCAmelCase_       :
    """simple docstring"""







    lowercase					=		XGLMConfig
    lowercase					=		{}
    lowercase					=		"gelu"




    def __init__(    self					:     Any ,     snake_case_					:     List[Any] ,     snake_case_					:     str=14 ,     snake_case_					:     List[Any]=7 ,     snake_case_					:     Optional[int]=True ,     snake_case_					:     Union[str, Any]=True ,     snake_case_					:     Union[str, Any]=True ,     snake_case_					:     Union[str, Any]=99 ,     snake_case_					:     Union[str, Any]=32 ,     snake_case_					:     int=2 ,     snake_case_					:     List[Any]=4 ,     snake_case_					:     int=37 ,     snake_case_					:     Dict="gelu" ,     snake_case_					:     Tuple=0.1 ,     snake_case_					:     List[Any]=0.1 ,     snake_case_					:     Tuple=512 ,     snake_case_					:     Union[str, Any]=0.02 ,     ):
          snake_case__  :    Union[str, Any]    						=      parent
          snake_case__  :    Optional[int]    						=      batch_size
          snake_case__  :    Optional[int]    						=      seq_length
          snake_case__  :    Tuple    						=      is_training
          snake_case__  :    List[Any]    						=      use_input_mask
          snake_case__  :    Tuple    						=      use_labels
          snake_case__  :    Tuple    						=      vocab_size
          snake_case__  :    Optional[Any]    						=      d_model
          snake_case__  :    Optional[Any]    						=      num_hidden_layers
          snake_case__  :    str    						=      num_attention_heads
          snake_case__  :    int    						=      ffn_dim
          snake_case__  :    Any    						=      activation_function
          snake_case__  :    Optional[int]    						=      activation_dropout
          snake_case__  :    int    						=      attention_dropout
          snake_case__  :    str    						=      max_position_embeddings
          snake_case__  :    Optional[Any]    						=      initializer_range
          snake_case__  :    Union[str, Any]    						=      None
          snake_case__  :    str    						=      0
          snake_case__  :    Dict    						=      2
          snake_case__  :    Optional[Any]    						=      1




    def lowerCamelCase       (    self					:     List[str]						):
          return XGLMConfig.from_pretrained("""facebook/xglm-564M"""						)




    def lowerCamelCase       (    self					:     str						):
          snake_case__  :    int    						=      tf.clip_by_value(
              ids_tensor([self.batch_size, self.seq_length] ,     self.vocab_size						) ,     clip_value_min=0 ,     clip_value_max=3						)

          snake_case__  :    Optional[Any]    						=      None
          if self.use_input_mask:
                snake_case__  :    List[Any]    						=      random_attention_mask([self.batch_size, self.seq_length]						)

          snake_case__  :    Tuple    						=      self.get_config()

          snake_case__  :    Optional[int]    						=      floats_tensor([self.num_hidden_layers, self.num_attention_heads] ,     2						)

          return (
              config,
              input_ids,
              input_mask,
              head_mask,
          )




    def lowerCamelCase       (    self					:     Optional[int]						):
          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=snake_case_ ,     bos_token_id=self.bos_token_id ,     eos_token_id=self.eos_token_id ,     pad_token_id=self.pad_token_id ,     return_dict=snake_case_ ,     )




    def lowerCamelCase       (    self					:     Dict						):
          snake_case__  :    Any    						=      self.prepare_config_and_inputs()

          (
              (
              snake_case__
          )						,				(
              snake_case__
          )						,				(
              snake_case__
          )						,				(
              snake_case__
          )						,				
          )  :    int    						=      config_and_inputs

          snake_case__  :    Any    						=      {
              """input_ids""": input_ids,
              """head_mask""": head_mask,
          }

          return config, inputs_dict







@require_tf
class     UpperCAmelCase_       (       _a		,		_a		,		unittest.TestCase	):
    """simple docstring"""







    lowercase					=		(TFXGLMModel, TFXGLMForCausalLM) if is_tf_available() else ()
    lowercase					=		(TFXGLMForCausalLM,) if is_tf_available() else ()
    lowercase					=		(
        {"feature-extraction": TFXGLMModel, "text-generation": TFXGLMForCausalLM} if is_tf_available() else {}
    )
    lowercase					=		False
    lowercase					=		False
    lowercase					=		False




    def lowerCamelCase       (    self					:     int						):
          snake_case__  :    int    						=      TFXGLMModelTester(self						)
          snake_case__  :    Dict    						=      ConfigTester(self ,     config_class=snake_case_ ,     n_embd=37						)




    def lowerCamelCase       (    self					:     Optional[Any]						):
          self.config_tester.run_common_tests()




    @slow
    def lowerCamelCase       (    self					:     str						):
          for model_name in TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                snake_case__  :    Any    						=      TFXGLMModel.from_pretrained(snake_case_						)
                self.assertIsNotNone(snake_case_						)




    @unittest.skip(reason="""Currently, model embeddings are going to undergo a major refactor."""						)
    def lowerCamelCase       (    self					:     Dict						):
          super().test_resize_token_embeddings()







@require_tf
class     UpperCAmelCase_       (       unittest.TestCase	):
    """simple docstring"""







    @slow
    def lowerCamelCase       (    self					:     List[str] ,     snake_case_					:     Union[str, Any]=True						):
          snake_case__  :    int    						=      TFXGLMForCausalLM.from_pretrained("""facebook/xglm-564M"""						)
          snake_case__  :    Dict    						=      tf.convert_to_tensor([[2, 268, 9_865]] ,     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
          snake_case__  :    int    						=      [2, 268, 9_865, 67, 11, 1_988, 57_252, 9_865, 5, 984, 67, 1_988, 213_838, 1_658, 53, 70_446, 33, 6_657, 278, 1_581]
          # fmt: on
          snake_case__  :    int    						=      model.generate(snake_case_ ,     do_sample=snake_case_ ,     num_beams=1						)
          if verify_outputs:
                self.assertListEqual(output_ids[0].numpy().tolist() ,     snake_case_						)




    @slow
    def lowerCamelCase       (    self					:     Tuple						):
          snake_case__  :    int    						=      XGLMTokenizer.from_pretrained("""facebook/xglm-564M"""						)
          snake_case__  :    Dict    						=      TFXGLMForCausalLM.from_pretrained("""facebook/xglm-564M"""						)

          tf.random.set_seed(0						)
          snake_case__  :    Optional[Any]    						=      tokenizer("""Today is a nice day and""" ,     return_tensors="""tf"""						)
          snake_case__  :    Tuple    						=      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"""						):
                snake_case__  :    str    						=      model.generate(snake_case_ ,     do_sample=snake_case_ ,     seed=[7, 0]						)
          snake_case__  :    Any    						=      tokenizer.decode(output_ids[0] ,     skip_special_tokens=snake_case_						)

          snake_case__  :    int    						=      (
              """Today is a nice day and warm evening here over Southern Alberta!! Today when they closed schools due"""
          )
          self.assertEqual(snake_case_ ,     snake_case_						)




    @slow
    def lowerCamelCase       (    self					:     List[Any]						):
          snake_case__  :    Union[str, Any]    						=      TFXGLMForCausalLM.from_pretrained("""facebook/xglm-564M"""						)
          snake_case__  :    List[str]    						=      XGLMTokenizer.from_pretrained("""facebook/xglm-564M"""						)

          snake_case__  :    List[Any]    						=      """left"""

          # use different length sentences to test batching
          snake_case__  :    Optional[Any]    						=      [
              """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""",
          ]

          snake_case__  :    Union[str, Any]    						=      tokenizer(snake_case_ ,     return_tensors="""tf""" ,     padding=snake_case_						)
          snake_case__  :    Tuple    						=      inputs["""input_ids"""]

          snake_case__  :    int    						=      model.generate(input_ids=snake_case_ ,     attention_mask=inputs["""attention_mask"""] ,     max_new_tokens=12						)

          snake_case__  :    Dict    						=      tokenizer(sentences[0] ,     return_tensors="""tf"""						).input_ids
          snake_case__  :    List[Any]    						=      model.generate(input_ids=snake_case_ ,     max_new_tokens=12						)

          snake_case__  :    List[str]    						=      tokenizer(sentences[1] ,     return_tensors="""tf"""						).input_ids
          snake_case__  :    Union[str, Any]    						=      model.generate(input_ids=snake_case_ ,     max_new_tokens=12						)

          snake_case__  :    Optional[Any]    						=      tokenizer.batch_decode(snake_case_ ,     skip_special_tokens=snake_case_						)
          snake_case__  :    Tuple    						=      tokenizer.decode(output_non_padded[0] ,     skip_special_tokens=snake_case_						)
          snake_case__  :    int    						=      tokenizer.decode(output_padded[0] ,     skip_special_tokens=snake_case_						)

          snake_case__  :    str    						=      [
              """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(snake_case_ ,     snake_case_						)
          self.assertListEqual(snake_case_ ,     [non_padded_sentence, padded_sentence]						)





'''simple docstring'''





from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available


__a          =		{
    "configuration_bloom": ["BLOOM_PRETRAINED_CONFIG_ARCHIVE_MAP", "BloomConfig", "BloomOnnxConfig"],
}
try:
       if not is_tokenizers_available():
              raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
       pass
else:
       __a          =		["BloomTokenizerFast"]

try:
       if not is_torch_available():
              raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
       pass
else:
       __a          =		[
           "BLOOM_PRETRAINED_MODEL_ARCHIVE_LIST",
           "BloomForCausalLM",
           "BloomModel",
           "BloomPreTrainedModel",
           "BloomForSequenceClassification",
           "BloomForTokenClassification",
           "BloomForQuestionAnswering",
       ]

if TYPE_CHECKING:
       from .configuration_bloom import BLOOM_PRETRAINED_CONFIG_ARCHIVE_MAP, BloomConfig, BloomOnnxConfig

       try:
              if not is_tokenizers_available():
                     raise OptionalDependencyNotAvailable()
       except OptionalDependencyNotAvailable:
              pass
       else:
              from .tokenization_bloom_fast import BloomTokenizerFast

       try:
              if not is_torch_available():
                     raise OptionalDependencyNotAvailable()
       except OptionalDependencyNotAvailable:
              pass
       else:
              from .modeling_bloom import (
                  BLOOM_PRETRAINED_MODEL_ARCHIVE_LIST,
                  BloomForCausalLM,
                  BloomForQuestionAnswering,
                  BloomForSequenceClassification,
                  BloomForTokenClassification,
                  BloomModel,
                  BloomPreTrainedModel,
              )

else:
       import sys

       __a          =		_LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
