


from importlib import import_module

from .logging import get_logger


_snake_case	:						Tuple         =							get_logger(__name__)

class 							a						:




							"""simple docstring"""


							def __init__(				self			:    str       ,      lowerCamelCase			:    str       ,      lowerCamelCase			:    Dict=None							)      ->       int:
														__snake_case						:     Dict									=  attrs or []
														if module is not None:
																					for key in module.__dict__:
																												if key in attrs or not key.startswith("__"							):
																																			setattr(self       ,      lowerCamelCase       ,      getattr(lowerCamelCase       ,      lowerCamelCase							)							)
														__snake_case						:     List[Any]									=  module._original_module if isinstance(lowerCamelCase       ,      _PatchedModuleObj							) else module

class 							a						:




							"""simple docstring"""


							__UpperCAmelCase       :				str	    =    []

							def __init__(				self			:    Dict       ,      lowerCamelCase			:    str       ,      lowerCamelCase			:    str       ,      lowerCamelCase			:    List[str]       ,      lowerCamelCase			:    Any=None							)      ->       Optional[Any]:
														__snake_case						:     str									=  obj
														__snake_case						:     str									=  target
														__snake_case						:     Dict									=  new
														__snake_case						:     Union[str, Any]									=  target.split("."							)[0]
														__snake_case						:     Any									=  {}
														__snake_case						:     str									=  attrs or []

							def __enter__(				self			:    Dict							)      ->       Optional[int]:
														*__snake_case					,     __snake_case						:     Union[str, Any]									=  self.target.split("."							)

														# Patch modules:
														# it's used to patch attributes of submodules like "os.path.join";
														# in this case we need to patch "os" and "os.path"

														for i in range(len(lowerCamelCase							)							):
																					try:
																												__snake_case						:     int									=  import_module(".".join(submodules[: i + 1]							)							)
																					except ModuleNotFoundError:
																												continue
																					# We iterate over all the globals in self.obj in case we find "os" or "os.path"
																					for attr in self.obj.__dir__():
																												__snake_case						:     Tuple									=  getattr(self.obj       ,      lowerCamelCase							)
																												# We don't check for the name of the global, but rather if its value *is* "os" or "os.path".
																												# This allows to patch renamed modules like "from os import path as ospath".
																												if obj_attr is submodule or (
																												    (isinstance(lowerCamelCase       ,      _PatchedModuleObj							) and obj_attr._original_module is submodule)
																												):
																																			__snake_case						:     Optional[Any]									=  obj_attr
																																			# patch at top level
																																			setattr(self.obj       ,      lowerCamelCase       ,      _PatchedModuleObj(lowerCamelCase       ,      attrs=self.attrs							)							)
																																			__snake_case						:     Union[str, Any]									=  getattr(self.obj       ,      lowerCamelCase							)
																																			# construct lower levels patches
																																			for key in submodules[i + 1 :]:
																																										setattr(lowerCamelCase       ,      lowerCamelCase       ,      _PatchedModuleObj(getattr(lowerCamelCase       ,      lowerCamelCase       ,      lowerCamelCase							)       ,      attrs=self.attrs							)							)
																																										__snake_case						:     Dict									=  getattr(lowerCamelCase       ,      lowerCamelCase							)
																																			# finally set the target attribute
																																			setattr(lowerCamelCase       ,      lowerCamelCase       ,      self.new							)

        # Patch attribute itself:
        # it's used for builtins like "open",
        # and also to patch "os.path.join" we may also need to patch "join"
        # itself if it was imported as "from os.path import join".

														if submodules:  # if it's an attribute of a submodule like "os.path.join"
																					try:
																												__snake_case						:     List[Any]									=  getattr(import_module(".".join(lowerCamelCase							)							)       ,      lowerCamelCase							)
																					except (AttributeError, ModuleNotFoundError):
																												return
																					# We iterate over all the globals in self.obj in case we find "os.path.join"
																					for attr in self.obj.__dir__():
																												# We don't check for the name of the global, but rather if its value *is* "os.path.join".
																												# This allows to patch renamed attributes like "from os.path import join as pjoin".
																												if getattr(self.obj       ,      lowerCamelCase							) is attr_value:
																																			__snake_case						:     Dict									=  getattr(self.obj       ,      lowerCamelCase							)
																																			setattr(self.obj       ,      lowerCamelCase       ,      self.new							)
														elif target_attr in globals()["__builtins__"]:  # if it'a s builtin like "open"
																					__snake_case						:     Tuple									=  globals()["__builtins__"][target_attr]
																					setattr(self.obj       ,      lowerCamelCase       ,      self.new							)
														else:
																					raise RuntimeError(F'Tried to patch attribute {target_attr} instead of a submodule.'							)

							def __exit__(				self			:    Optional[int]       ,      *lowerCamelCase			:    Optional[Any]							)      ->       Dict:
														for attr in list(self.original							):
																					setattr(self.obj       ,      lowerCamelCase       ,      self.original.pop(lowerCamelCase							)							)

							def        __snake_case   (				self			:    Any							)      ->       Optional[int]:
														self.__enter__()
														self._active_patches.append(self							)






							def        __snake_case   (				self			:    List[str]							)      ->       Tuple:
														try:
																					self._active_patches.remove(self							)
														except ValueError:
																					# If the patch hasn't been started this will fail
																					return None

														return self.__exit__()





'''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"""






     __magic_name__           =     XGLMConfig
     __magic_name__           =     {}
     __magic_name__           =     "gelu"







     def __init__(			self   ,						snake_case__   ,						snake_case__=14   ,						snake_case__=7   ,						snake_case__=True   ,						snake_case__=True   ,						snake_case__=True   ,						snake_case__=99   ,						snake_case__=32   ,						snake_case__=2   ,						snake_case__=4   ,						snake_case__=37   ,						snake_case__="gelu"   ,						snake_case__=0.1   ,						snake_case__=0.1   ,						snake_case__=512   ,						snake_case__=0.02   ,						):

            '''simple docstring'''

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







     def a						(			self ):

            '''simple docstring'''

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







     def a						(			self ):

            '''simple docstring'''

            _lowerCAmelCase     :				Optional[Any]       =							tf.clip_by_value(
                ids_tensor([self.batch_size, self.seq_length]   ,						self.vocab_size )   ,						clip_value_min=0   ,						clip_value_max=3 )

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

            _lowerCAmelCase     :				str       =							self.get_config()

            _lowerCAmelCase     :				Union[str, Any]       =							floats_tensor([self.num_hidden_layers, self.num_attention_heads]   ,						2 )

            return (
                config,
                input_ids,
                input_mask,
                head_mask,
            )







     def a						(			self ):

            '''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 a						(			self ):

            '''simple docstring'''

            _lowerCAmelCase     :				int       =							self.prepare_config_and_inputs()

            (
                (
                _lowerCAmelCase
            )      ,  (
                _lowerCAmelCase
            )      ,  (
                _lowerCAmelCase
            )      ,  (
                _lowerCAmelCase
            )      ,  
            )     :				Dict       =							config_and_inputs

            _lowerCAmelCase     :				Optional[int]       =							{
                'input_ids': input_ids,
                'head_mask': head_mask,
            }

            return config, inputs_dict
@require_tf
class 						UpperCamelCase__       (			SCREAMING_SNAKE_CASE_     ,       SCREAMING_SNAKE_CASE_     ,       unittest.TestCase						):



     """simple docstring"""






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







     def a						(			self ):

            '''simple docstring'''

            _lowerCAmelCase     :				Dict       =							TFXGLMModelTester(self )
            _lowerCAmelCase     :				Dict       =							ConfigTester(self   ,						config_class=snake_case__   ,						n_embd=37 )







     def a						(			self ):

            '''simple docstring'''

            self.config_tester.run_common_tests()







     @slow
     def a						(			self ):

            '''simple docstring'''

            for model_name in TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                   _lowerCAmelCase     :				Optional[Any]       =							TFXGLMModel.from_pretrained(snake_case__ )
                   self.assertIsNotNone(snake_case__ )







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

            '''simple docstring'''

            super().test_resize_token_embeddings()
@require_tf
class 						UpperCamelCase__       (			unittest.TestCase						):



     """simple docstring"""






     @slow
     def a						(			self   ,						snake_case__=True ):

            '''simple docstring'''

            _lowerCAmelCase     :				str       =							TFXGLMForCausalLM.from_pretrained('facebook/xglm-564M' )
            _lowerCAmelCase     :				str       =							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
            _lowerCAmelCase     :				str       =							[2, 268, 9865, 67, 11, 1988, 5_7252, 9865, 5, 984, 67, 1988, 21_3838, 1658, 53, 7_0446, 33, 6657, 278, 1581]
            # fmt: on
            _lowerCAmelCase     :				Optional[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 a						(			self ):

            '''simple docstring'''

            _lowerCAmelCase     :				int       =							XGLMTokenizer.from_pretrained('facebook/xglm-564M' )
            _lowerCAmelCase     :				int       =							TFXGLMForCausalLM.from_pretrained('facebook/xglm-564M' )

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

            _lowerCAmelCase     :				Tuple       =							(
                '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 a						(			self ):

            '''simple docstring'''

            _lowerCAmelCase     :				Any       =							TFXGLMForCausalLM.from_pretrained('facebook/xglm-564M' )
            _lowerCAmelCase     :				int       =							XGLMTokenizer.from_pretrained('facebook/xglm-564M' )

            _lowerCAmelCase     :				Tuple       =							'left'

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

            _lowerCAmelCase     :				Tuple       =							tokenizer(snake_case__   ,						return_tensors='tf'   ,						padding=snake_case__ )
            _lowerCAmelCase     :				Any       =							inputs['input_ids']

            _lowerCAmelCase     :				Any       =							model.generate(input_ids=snake_case__   ,						attention_mask=inputs['attention_mask']   ,						max_new_tokens=12 )

            _lowerCAmelCase     :				Dict       =							tokenizer(sentences[0]   ,						return_tensors='tf' ).input_ids
            _lowerCAmelCase     :				Union[str, Any]       =							model.generate(input_ids=snake_case__   ,						max_new_tokens=12 )

            _lowerCAmelCase     :				int       =							tokenizer(sentences[1]   ,						return_tensors='tf' ).input_ids
            _lowerCAmelCase     :				Optional[Any]       =							model.generate(input_ids=snake_case__   ,						max_new_tokens=12 )

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

            _lowerCAmelCase     :				List[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 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] )

