






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

       '''simple docstring'''
       lowerCamelCase				:					Tuple								=			XGLMConfig
       lowerCamelCase				:					int								=			{}
       lowerCamelCase				:					str								=			"""gelu"""



       def __init__(				self      ,    a__      ,    a__=14      ,    a__=7      ,    a__=True      ,    a__=True      ,    a__=True      ,    a__=99      ,    a__=32      ,    a__=2      ,    a__=4      ,    a__=37      ,    a__="gelu"      ,    a__=0.1      ,    a__=0.1      ,    a__=5_12      ,    a__=0.02      ,    )			->   Union[str, Any]:






            '''simple docstring'''





            __snake_case      :Union[str, Any] 							=    parent
            __snake_case      :Tuple 							=    batch_size
            __snake_case      :str 							=    seq_length
            __snake_case      :int 							=    is_training
            __snake_case      :Tuple 							=    use_input_mask
            __snake_case      :Optional[int] 							=    use_labels
            __snake_case      :int 							=    vocab_size
            __snake_case      :Optional[int] 							=    d_model
            __snake_case      :Any 							=    num_hidden_layers
            __snake_case      :Dict 							=    num_attention_heads
            __snake_case      :Any 							=    ffn_dim
            __snake_case      :Any 							=    activation_function
            __snake_case      :Dict 							=    activation_dropout
            __snake_case      :Any 							=    attention_dropout
            __snake_case      :Optional[Any] 							=    max_position_embeddings
            __snake_case      :Optional[int] 							=    initializer_range
            __snake_case      :Optional[Any] 							=    None
            __snake_case      :Any 							=    0
            __snake_case      :str 							=    2
            __snake_case      :Any 							=    1



       def        __lowercase    (				self     )			->   str:






            '''simple docstring'''





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



       def        __lowercase    (				self     )			->   Any:






            '''simple docstring'''





            __snake_case      :Union[str, Any] 							=    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      :List[str] 							=    None
            if self.use_input_mask:
                 __snake_case      :List[str] 							=    random_attention_mask([self.batch_size, self.seq_length]     )

            __snake_case      :Dict 							=    self.get_config()

            __snake_case      :List[Any] 							=    floats_tensor([self.num_hidden_layers, self.num_attention_heads]      ,    2     )

            return (
                config,
                input_ids,
                input_mask,
                head_mask,
            )



       def        __lowercase    (				self     )			->   Optional[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=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        __lowercase    (				self     )			->   Tuple:






            '''simple docstring'''





            __snake_case      :Tuple 							=    self.prepare_config_and_inputs()

            (
                __snake_case		
            )      :Tuple 							=    config_and_inputs

            __snake_case      :int 							=    {
                """input_ids""": input_ids,
                """head_mask""": head_mask,
            }

            return config, inputs_dict




@require_tf
class       snake_case__ (				lowerCamelCase__						,     lowerCamelCase__						,     unittest.TestCase):

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



       def        __lowercase    (				self     )			->   List[Any]:






            '''simple docstring'''





            __snake_case      :Any 							=    TFXGLMModelTester(self     )
            __snake_case      :Any 							=    ConfigTester(self      ,    config_class=snake_case__      ,    n_embd=37     )



       def        __lowercase    (				self     )			->   Union[str, Any]:






            '''simple docstring'''





            self.config_tester.run_common_tests()



       @slow
       def        __lowercase    (				self     )			->   Optional[Any]:






            '''simple docstring'''





            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        __lowercase    (				self     )			->   Optional[int]:






            '''simple docstring'''





            super().test_resize_token_embeddings()




@require_tf
class       snake_case__ (				unittest.TestCase):

       '''simple docstring'''



       @slow
       def        __lowercase    (				self      ,    a__=True     )			->   Optional[int]:






            '''simple docstring'''





            __snake_case      :int 							=    TFXGLMForCausalLM.from_pretrained("""facebook/xglm-564M"""     )
            __snake_case      :Dict 							=    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
            __snake_case      :List[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
            __snake_case      :List[str] 							=    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        __lowercase    (				self     )			->   List[str]:






            '''simple docstring'''





            __snake_case      :Optional[Any] 							=    XGLMTokenizer.from_pretrained("""facebook/xglm-564M"""     )
            __snake_case      :List[str] 							=    TFXGLMForCausalLM.from_pretrained("""facebook/xglm-564M"""     )

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

            __snake_case      :Optional[Any] 							=    (
                """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        __lowercase    (				self     )			->   Tuple:






            '''simple docstring'''





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

            __snake_case      :int 							=    """left"""

            # use different length sentences to test batching
            __snake_case      :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""",
            ]

            __snake_case      :Optional[int] 							=    tokenizer(snake_case__      ,    return_tensors="""tf"""      ,    padding=snake_case__     )
            __snake_case      :List[str] 							=    inputs["""input_ids"""]

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

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

            __snake_case      :Optional[int] 							=    tokenizer(sentences[1]      ,    return_tensors="""tf"""     ).input_ids
            __snake_case      :List[str] 							=    model.generate(input_ids=snake_case__      ,    max_new_tokens=12     )

            __snake_case      :List[Any] 							=    tokenizer.batch_decode(snake_case__      ,    skip_special_tokens=snake_case__     )
            __snake_case      :Any 							=    tokenizer.decode(output_non_padded[0]      ,    skip_special_tokens=snake_case__     )
            __snake_case      :List[Any] 							=    tokenizer.decode(output_padded[0]      ,    skip_special_tokens=snake_case__     )

            __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 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]     )









import pytest
import requests

from datasets.utils.file_utils import http_head

from .utils import OfflineSimulationMode, RequestWouldHangIndefinitelyError, offline





@pytest.mark.integration
def  __magic_name__  (				)				-> Union[str, Any]:

							"""simple docstring"""



							with offline(OfflineSimulationMode.CONNECTION_TIMES_OUT				):
														with pytest.raises(lowercase				):
																					requests.request("""GET"""				,       """https://huggingface.co"""				)
														with pytest.raises(requests.exceptions.ConnectTimeout				):
																					requests.request("""GET"""				,       """https://huggingface.co"""				,       timeout=1.0				)





@pytest.mark.integration
def  __magic_name__  (				)				-> Union[str, Any]:

							"""simple docstring"""



							with offline(OfflineSimulationMode.CONNECTION_FAILS				):
														with pytest.raises(requests.exceptions.ConnectionError				):
																					requests.request("""GET"""				,       """https://huggingface.co"""				)





def  __magic_name__  (				)				-> Dict:

							"""simple docstring"""



							with offline(OfflineSimulationMode.HF_DATASETS_OFFLINE_SET_TO_1				):
														with pytest.raises(lowercase				):
																					http_head("""https://huggingface.co"""				)