
# Copyright 2023 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import TYPE_CHECKING

# rely on isort to merge the imports
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available


UpperCAmelCase       =					{
    '''configuration_efficientnet''': [
        '''EFFICIENTNET_PRETRAINED_CONFIG_ARCHIVE_MAP''',
        '''EfficientNetConfig''',
        '''EfficientNetOnnxConfig''',
    ]
}

try:
	if not is_vision_available():
		raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
	pass
else:
	UpperCAmelCase       =					['''EfficientNetImageProcessor''']

try:
	if not is_torch_available():
		raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
	pass
else:
	UpperCAmelCase       =					[
	    '''EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST''',
	    '''EfficientNetForImageClassification''',
	    '''EfficientNetModel''',
	    '''EfficientNetPreTrainedModel''',
	]

if TYPE_CHECKING:
	from .configuration_efficientnet import (
	    EFFICIENTNET_PRETRAINED_CONFIG_ARCHIVE_MAP,
	    EfficientNetConfig,
	    EfficientNetOnnxConfig,
	)

	try:
		if not is_vision_available():
			raise OptionalDependencyNotAvailable()
	except OptionalDependencyNotAvailable:
		pass
	else:
		from .image_processing_efficientnet import EfficientNetImageProcessor

	try:
		if not is_torch_available():
			raise OptionalDependencyNotAvailable()
	except OptionalDependencyNotAvailable:
		pass
	else:
		from .modeling_efficientnet import (
		    EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST,
		    EfficientNetForImageClassification,
		    EfficientNetModel,
		    EfficientNetPreTrainedModel,
		)

else:
	import sys

	UpperCAmelCase       =					_LazyModule(__name__, globals()['''__file__'''], _import_structure)


"""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    a_   :
					UpperCamelCase_			:						Any      =     XGLMConfig
					UpperCamelCase_			:						int      =     {}
					UpperCamelCase_			:						Tuple      =     "gelu"




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




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




					def     _SCREAMING_SNAKE_CASE    (						self    :  Dict  ):
							lowerCAmelCase__   = tf.clip_by_value(
							    ids_tensor([self.batch_size, self.seq_length]	,    self.vocab_size  )	,    clip_value_min=0	,    clip_value_max=3  )

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

							lowerCAmelCase__   = self.get_config()

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

							return (
							    config,
							    input_ids,
							    input_mask,
							    head_mask,
							)




					def     _SCREAMING_SNAKE_CASE    (						self    :  Dict  ):
							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     _SCREAMING_SNAKE_CASE    (						self    :  str  ):
							lowerCAmelCase__   = self.prepare_config_and_inputs()

							(
							    (
							    lowerCAmelCase__
							) ,       (
							    lowerCAmelCase__
							) ,       (
							    lowerCAmelCase__
							) ,       (
							    lowerCAmelCase__
							) ,       
							)   = config_and_inputs

							lowerCAmelCase__   = {
							    """input_ids""": input_ids,
							    """head_mask""": head_mask,
							}

							return config, inputs_dict

@require_tf
class    a_   (  __UpperCamelCase			,		__UpperCamelCase			,		unittest.TestCase      ):
					UpperCamelCase_			:						str      =     (TFXGLMModel, TFXGLMForCausalLM) if is_tf_available() else ()
					UpperCamelCase_			:						Union[str, Any]      =     (TFXGLMForCausalLM,) if is_tf_available() else ()
					UpperCamelCase_			:						Tuple      =     (
					    {"feature-extraction": TFXGLMModel, "text-generation": TFXGLMForCausalLM} if is_tf_available() else {}
					)
					UpperCamelCase_			:						List[Any]      =     False
					UpperCamelCase_			:						Optional[Any]      =     False
					UpperCamelCase_			:						str      =     False




					def     _SCREAMING_SNAKE_CASE    (						self    :  Optional[Any]  ):
							lowerCAmelCase__   = TFXGLMModelTester(self  )
							lowerCAmelCase__   = ConfigTester(self	,    config_class=snake_case__	,    n_embd=37  )




					def     _SCREAMING_SNAKE_CASE    (						self    :  Dict  ):
							self.config_tester.run_common_tests()




					@slow
					def     _SCREAMING_SNAKE_CASE    (						self    :  int  ):
							for model_name in TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
									lowerCAmelCase__   = TFXGLMModel.from_pretrained(snake_case__  )
									self.assertIsNotNone(snake_case__  )




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

@require_tf
class    a_   (  unittest.TestCase      ):




					@slow
					def     _SCREAMING_SNAKE_CASE    (						self    :  int	,    snake_case__    :  Optional[int]=True  ):
							lowerCAmelCase__   = TFXGLMForCausalLM.from_pretrained("""facebook/xglm-564M"""  )
							lowerCAmelCase__   = 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__   = [2, 268, 9865, 67, 11, 1988, 57252, 9865, 5, 984, 67, 1988, 213838, 1658, 53, 70446, 33, 6657, 278, 1581]
							# fmt: on
							lowerCAmelCase__   = 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     _SCREAMING_SNAKE_CASE    (						self    :  Tuple  ):
							lowerCAmelCase__   = XGLMTokenizer.from_pretrained("""facebook/xglm-564M"""  )
							lowerCAmelCase__   = TFXGLMForCausalLM.from_pretrained("""facebook/xglm-564M"""  )

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

							lowerCAmelCase__   = (
							    """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     _SCREAMING_SNAKE_CASE    (						self    :  List[str]  ):
							lowerCAmelCase__   = TFXGLMForCausalLM.from_pretrained("""facebook/xglm-564M"""  )
							lowerCAmelCase__   = XGLMTokenizer.from_pretrained("""facebook/xglm-564M"""  )

							lowerCAmelCase__   = """left"""

							# use different length sentences to test batching
							lowerCAmelCase__   = [
							    """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__   = tokenizer(snake_case__	,    return_tensors="""tf"""	,    padding=snake_case__  )
							lowerCAmelCase__   = inputs["""input_ids"""]

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

							lowerCAmelCase__   = tokenizer(sentences[0]	,    return_tensors="""tf"""  ).input_ids
							lowerCAmelCase__   = model.generate(input_ids=snake_case__	,    max_new_tokens=12  )

							lowerCAmelCase__   = tokenizer(sentences[1]	,    return_tensors="""tf"""  ).input_ids
							lowerCAmelCase__   = model.generate(input_ids=snake_case__	,    max_new_tokens=12  )

							lowerCAmelCase__   = tokenizer.batch_decode(snake_case__	,    skip_special_tokens=snake_case__  )
							lowerCAmelCase__   = tokenizer.decode(output_non_padded[0]	,    skip_special_tokens=snake_case__  )
							lowerCAmelCase__   = tokenizer.decode(output_padded[0]	,    skip_special_tokens=snake_case__  )

							lowerCAmelCase__   = [
							    """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]  )




