






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     :

					'''simple docstring'''

					_A						:			int									=      XGLMConfig
					_A						:			Any									=      {}
					_A						:			Any									=      '''gelu'''



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


												"""simple docstring"""

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



					def       lowerCAmelCase				(  self				:	Optional[int]							)			->  str:


												"""simple docstring"""

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



					def       lowerCAmelCase				(  self				:	Optional[int]							)			->  List[str]:


												"""simple docstring"""

												__lowercase      :							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							)

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

												__lowercase      :							Optional[Any]				=     self.get_config()

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

												return (
												    config,
												    input_ids,
												    input_mask,
												    head_mask,
												)



					def       lowerCAmelCase				(  self				:	Optional[Any]							)			->  Tuple:


												"""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=__a		,     bos_token_id=self.bos_token_id		,     eos_token_id=self.eos_token_id		,     pad_token_id=self.pad_token_id		,     return_dict=__a		,     )



					def       lowerCAmelCase				(  self				:	Tuple							)			->  Dict:


												"""simple docstring"""

												__lowercase      :							int				=     self.prepare_config_and_inputs()

												(
												    (
												    __lowercase
												)			,			(
												    __lowercase
												)			,			(
												    __lowercase
												)			,			(
												    __lowercase
												)			,			
												)      :							Optional[int]				=     config_and_inputs

												__lowercase      :							Tuple				=     {
												    """input_ids""": input_ids,
												    """head_mask""": head_mask,
												}

												return config, inputs_dict







@require_tf
class 		lowerCAmelCase     ( __a      ,       __a      ,       unittest.TestCase			):

					'''simple docstring'''

					_A						:			Optional[Any]									=      (TFXGLMModel, TFXGLMForCausalLM) if is_tf_available() else ()
					_A						:			Dict									=      (TFXGLMForCausalLM,) if is_tf_available() else ()
					_A						:			int									=      (
					    {'''feature-extraction''': TFXGLMModel, '''text-generation''': TFXGLMForCausalLM} if is_tf_available() else {}
					)
					_A						:			Optional[Any]									=      False
					_A						:			Dict									=      False
					_A						:			Optional[Any]									=      False



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


												"""simple docstring"""

												__lowercase      :							List[str]				=     TFXGLMModelTester(self							)
												__lowercase      :							int				=     ConfigTester(self		,     config_class=__a		,     n_embd=37							)



					def       lowerCAmelCase				(  self				:	Optional[int]							)			->  Tuple:


												"""simple docstring"""

												self.config_tester.run_common_tests()



					@slow
					def       lowerCAmelCase				(  self				:	Union[str, Any]							)			->  str:


												"""simple docstring"""

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



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


												"""simple docstring"""

												super().test_resize_token_embeddings()







@require_tf
class 		lowerCAmelCase     ( unittest.TestCase			):

					'''simple docstring'''

					@slow
					def       lowerCAmelCase				(  self				:	List[Any]		,     __a				:	Optional[int]=True							)			->  int:


												"""simple docstring"""

												__lowercase      :							int				=     TFXGLMForCausalLM.from_pretrained("""facebook/xglm-564M"""							)
												__lowercase      :							Tuple				=     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
												__lowercase      :							Any				=     [2, 268, 9865, 67, 11, 1988, 57252, 9865, 5, 984, 67, 1988, 213838, 1658, 53, 70446, 33, 6657, 278, 1581]
												# fmt: on
												__lowercase      :							Union[str, Any]				=     model.generate(__a		,     do_sample=__a		,     num_beams=1							)
												if verify_outputs:
																			self.assertListEqual(output_ids[0].numpy().tolist()		,     __a							)



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


												"""simple docstring"""

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

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

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



					@slow
					def       lowerCAmelCase				(  self				:	List[str]							)			->  str:


												"""simple docstring"""

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

												__lowercase      :							Any				=     """left"""

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

												__lowercase      :							Any				=     tokenizer(__a		,     return_tensors="""tf"""		,     padding=__a							)
												__lowercase      :							Union[str, Any]				=     inputs["""input_ids"""]

												__lowercase      :							Tuple				=     model.generate(input_ids=__a		,     attention_mask=inputs["""attention_mask"""]		,     max_new_tokens=12							)

												__lowercase      :							Dict				=     tokenizer(sentences[0]		,     return_tensors="""tf"""							).input_ids
												__lowercase      :							int				=     model.generate(input_ids=__a		,     max_new_tokens=12							)

												__lowercase      :							int				=     tokenizer(sentences[1]		,     return_tensors="""tf"""							).input_ids
												__lowercase      :							Tuple				=     model.generate(input_ids=__a		,     max_new_tokens=12							)

												__lowercase      :							Union[str, Any]				=     tokenizer.batch_decode(__a		,     skip_special_tokens=__a							)
												__lowercase      :							Optional[Any]				=     tokenizer.decode(output_non_padded[0]		,     skip_special_tokens=__a							)
												__lowercase      :							List[str]				=     tokenizer.decode(output_padded[0]		,     skip_special_tokens=__a							)

												__lowercase      :							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 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(__a		,     __a							)
												self.assertListEqual(__a		,     [non_padded_sentence, padded_sentence]							)







lowerCamelCase : List[str]						   =       '''0.18.2'''

from .configuration_utils import ConfigMixin
from .utils import (
    OptionalDependencyNotAvailable,
    is_flax_available,
    is_inflect_available,
    is_invisible_watermark_available,
    is_k_diffusion_available,
    is_k_diffusion_version,
    is_librosa_available,
    is_note_seq_available,
    is_onnx_available,
    is_scipy_available,
    is_torch_available,
    is_torchsde_available,
    is_transformers_available,
    is_transformers_version,
    is_unidecode_available,
    logging,
)


try:
	if not is_onnx_available():
		raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
	from .utils.dummy_onnx_objects import *  # noqa F403
else:
	from .pipelines import OnnxRuntimeModel

try:
	if not is_torch_available():
		raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
	from .utils.dummy_pt_objects import *  # noqa F403
else:
	from .models import (
	    AutoencoderKL,
	    ControlNetModel,
	    ModelMixin,
	    PriorTransformer,
	    TaFilmDecoder,
	    TransformeraDModel,
	    UNetaDModel,
	    UNetaDConditionModel,
	    UNetaDModel,
	    UNetaDConditionModel,
	    VQModel,
	)
	from .optimization import (
	    get_constant_schedule,
	    get_constant_schedule_with_warmup,
	    get_cosine_schedule_with_warmup,
	    get_cosine_with_hard_restarts_schedule_with_warmup,
	    get_linear_schedule_with_warmup,
	    get_polynomial_decay_schedule_with_warmup,
	    get_scheduler,
	)
	from .pipelines import (
	    AudioPipelineOutput,
	    ConsistencyModelPipeline,
	    DanceDiffusionPipeline,
	    DDIMPipeline,
	    DDPMPipeline,
	    DiffusionPipeline,
	    DiTPipeline,
	    ImagePipelineOutput,
	    KarrasVePipeline,
	    LDMPipeline,
	    LDMSuperResolutionPipeline,
	    PNDMPipeline,
	    RePaintPipeline,
	    ScoreSdeVePipeline,
	)
	from .schedulers import (
	    CMStochasticIterativeScheduler,
	    DDIMInverseScheduler,
	    DDIMParallelScheduler,
	    DDIMScheduler,
	    DDPMParallelScheduler,
	    DDPMScheduler,
	    DEISMultistepScheduler,
	    DPMSolverMultistepInverseScheduler,
	    DPMSolverMultistepScheduler,
	    DPMSolverSinglestepScheduler,
	    EulerAncestralDiscreteScheduler,
	    EulerDiscreteScheduler,
	    HeunDiscreteScheduler,
	    IPNDMScheduler,
	    KarrasVeScheduler,
	    KDPMaAncestralDiscreteScheduler,
	    KDPMaDiscreteScheduler,
	    PNDMScheduler,
	    RePaintScheduler,
	    SchedulerMixin,
	    ScoreSdeVeScheduler,
	    UnCLIPScheduler,
	    UniPCMultistepScheduler,
	    VQDiffusionScheduler,
	)
	from .training_utils import EMAModel

try:
	if not (is_torch_available() and is_scipy_available()):
		raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
	from .utils.dummy_torch_and_scipy_objects import *  # noqa F403
else:
	from .schedulers import LMSDiscreteScheduler

try:
	if not (is_torch_available() and is_torchsde_available()):
		raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
	from .utils.dummy_torch_and_torchsde_objects import *  # noqa F403
else:
	from .schedulers import DPMSolverSDEScheduler

try:
	if not (is_torch_available() and is_transformers_available()):
		raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
	from .utils.dummy_torch_and_transformers_objects import *  # noqa F403
else:
	from .pipelines import (
	    AltDiffusionImgaImgPipeline,
	    AltDiffusionPipeline,
	    AudioLDMPipeline,
	    CycleDiffusionPipeline,
	    IFImgaImgPipeline,
	    IFImgaImgSuperResolutionPipeline,
	    IFInpaintingPipeline,
	    IFInpaintingSuperResolutionPipeline,
	    IFPipeline,
	    IFSuperResolutionPipeline,
	    ImageTextPipelineOutput,
	    KandinskyImgaImgPipeline,
	    KandinskyInpaintPipeline,
	    KandinskyPipeline,
	    KandinskyPriorPipeline,
	    KandinskyVaaControlnetImgaImgPipeline,
	    KandinskyVaaControlnetPipeline,
	    KandinskyVaaImgaImgPipeline,
	    KandinskyVaaInpaintPipeline,
	    KandinskyVaaPipeline,
	    KandinskyVaaPriorEmbaEmbPipeline,
	    KandinskyVaaPriorPipeline,
	    LDMTextToImagePipeline,
	    PaintByExamplePipeline,
	    SemanticStableDiffusionPipeline,
	    ShapEImgaImgPipeline,
	    ShapEPipeline,
	    StableDiffusionAttendAndExcitePipeline,
	    StableDiffusionControlNetImgaImgPipeline,
	    StableDiffusionControlNetInpaintPipeline,
	    StableDiffusionControlNetPipeline,
	    StableDiffusionDepthaImgPipeline,
	    StableDiffusionDiffEditPipeline,
	    StableDiffusionImageVariationPipeline,
	    StableDiffusionImgaImgPipeline,
	    StableDiffusionInpaintPipeline,
	    StableDiffusionInpaintPipelineLegacy,
	    StableDiffusionInstructPixaPixPipeline,
	    StableDiffusionLatentUpscalePipeline,
	    StableDiffusionLDMaDPipeline,
	    StableDiffusionModelEditingPipeline,
	    StableDiffusionPanoramaPipeline,
	    StableDiffusionParadigmsPipeline,
	    StableDiffusionPipeline,
	    StableDiffusionPipelineSafe,
	    StableDiffusionPixaPixZeroPipeline,
	    StableDiffusionSAGPipeline,
	    StableDiffusionUpscalePipeline,
	    StableUnCLIPImgaImgPipeline,
	    StableUnCLIPPipeline,
	    TextToVideoSDPipeline,
	    TextToVideoZeroPipeline,
	    UnCLIPImageVariationPipeline,
	    UnCLIPPipeline,
	    UniDiffuserModel,
	    UniDiffuserPipeline,
	    UniDiffuserTextDecoder,
	    VersatileDiffusionDualGuidedPipeline,
	    VersatileDiffusionImageVariationPipeline,
	    VersatileDiffusionPipeline,
	    VersatileDiffusionTextToImagePipeline,
	    VideoToVideoSDPipeline,
	    VQDiffusionPipeline,
	)

try:
	if not (is_torch_available() and is_transformers_available() and is_invisible_watermark_available()):
		raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
	from .utils.dummy_torch_and_transformers_and_invisible_watermark_objects import *  # noqa F403
else:
	from .pipelines import StableDiffusionXLImgaImgPipeline, StableDiffusionXLPipeline

try:
	if not (is_torch_available() and is_transformers_available() and is_k_diffusion_available()):
		raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
	from .utils.dummy_torch_and_transformers_and_k_diffusion_objects import *  # noqa F403
else:
	from .pipelines import StableDiffusionKDiffusionPipeline

try:
	if not (is_torch_available() and is_transformers_available() and is_onnx_available()):
		raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
	from .utils.dummy_torch_and_transformers_and_onnx_objects import *  # noqa F403
else:
	from .pipelines import (
	    OnnxStableDiffusionImgaImgPipeline,
	    OnnxStableDiffusionInpaintPipeline,
	    OnnxStableDiffusionInpaintPipelineLegacy,
	    OnnxStableDiffusionPipeline,
	    OnnxStableDiffusionUpscalePipeline,
	    StableDiffusionOnnxPipeline,
	)

try:
	if not (is_torch_available() and is_librosa_available()):
		raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
	from .utils.dummy_torch_and_librosa_objects import *  # noqa F403
else:
	from .pipelines import AudioDiffusionPipeline, Mel

try:
	if not (is_transformers_available() and is_torch_available() and is_note_seq_available()):
		raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
	from .utils.dummy_transformers_and_torch_and_note_seq_objects import *  # noqa F403
else:
	from .pipelines import SpectrogramDiffusionPipeline

try:
	if not is_flax_available():
		raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
	from .utils.dummy_flax_objects import *  # noqa F403
else:
	from .models.controlnet_flax import FlaxControlNetModel
	from .models.modeling_flax_utils import FlaxModelMixin
	from .models.unet_ad_condition_flax import FlaxUNetaDConditionModel
	from .models.vae_flax import FlaxAutoencoderKL
	from .pipelines import FlaxDiffusionPipeline
	from .schedulers import (
	    FlaxDDIMScheduler,
	    FlaxDDPMScheduler,
	    FlaxDPMSolverMultistepScheduler,
	    FlaxKarrasVeScheduler,
	    FlaxLMSDiscreteScheduler,
	    FlaxPNDMScheduler,
	    FlaxSchedulerMixin,
	    FlaxScoreSdeVeScheduler,
	)


try:
	if not (is_flax_available() and is_transformers_available()):
		raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
	from .utils.dummy_flax_and_transformers_objects import *  # noqa F403
else:
	from .pipelines import (
	    FlaxStableDiffusionControlNetPipeline,
	    FlaxStableDiffusionImgaImgPipeline,
	    FlaxStableDiffusionInpaintPipeline,
	    FlaxStableDiffusionPipeline,
	)

try:
	if not (is_note_seq_available()):
		raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
	from .utils.dummy_note_seq_objects import *  # noqa F403
else:
	from .pipelines import MidiProcessor