


'''simple docstring'''







import gc
import tempfile
import unittest

import numpy as np
import torch

from diffusers import VersatileDiffusionTextToImagePipeline
from diffusers.utils.testing_utils import nightly, require_torch_gpu, torch_device


lowerCAmelCase     :  str											=    False
class 						UpperCamelCase__       (			unittest.TestCase						):



     """simple docstring"""






     pass
@nightly
@require_torch_gpu
class 						UpperCamelCase__       (			unittest.TestCase						):



     """simple docstring"""






     def a						(			self ):

            '''simple docstring'''

            super().tearDown()
            gc.collect()
            torch.cuda.empty_cache()







     def a						(			self ):

            '''simple docstring'''

            _lowerCAmelCase     :				List[str]       =							VersatileDiffusionTextToImagePipeline.from_pretrained('shi-labs/versatile-diffusion' )
            # remove text_unet
            pipe.remove_unused_weights()
            pipe.to(snake_case__ )
            pipe.set_progress_bar_config(disable=snake_case__ )

            _lowerCAmelCase     :				Any       =							'A painting of a squirrel eating a burger '
            _lowerCAmelCase     :				List[Any]       =							torch.manual_seed(0 )
            _lowerCAmelCase     :				Any       =							pipe(
                prompt=snake_case__   ,						generator=snake_case__   ,						guidance_scale=7.5   ,						num_inference_steps=2   ,						output_type='numpy' ).images

            with tempfile.TemporaryDirectory() as tmpdirname:
                   pipe.save_pretrained(snake_case__ )
                   _lowerCAmelCase     :				Any       =							VersatileDiffusionTextToImagePipeline.from_pretrained(snake_case__ )
            pipe.to(snake_case__ )
            pipe.set_progress_bar_config(disable=snake_case__ )

            _lowerCAmelCase     :				Optional[int]       =							generator.manual_seed(0 )
            _lowerCAmelCase     :				Tuple       =							pipe(
                prompt=snake_case__   ,						generator=snake_case__   ,						guidance_scale=7.5   ,						num_inference_steps=2   ,						output_type='numpy' ).images

            assert np.abs(image - new_image ).sum() < 1E-5, "Models don't have the same forward pass"







     def a						(			self ):

            '''simple docstring'''

            _lowerCAmelCase     :				Union[str, Any]       =							VersatileDiffusionTextToImagePipeline.from_pretrained(
                'shi-labs/versatile-diffusion'   ,						torch_dtype=torch.floataa )
            pipe.to(snake_case__ )
            pipe.set_progress_bar_config(disable=snake_case__ )

            _lowerCAmelCase     :				Dict       =							'A painting of a squirrel eating a burger '
            _lowerCAmelCase     :				Any       =							torch.manual_seed(0 )
            _lowerCAmelCase     :				int       =							pipe(
                prompt=snake_case__   ,						generator=snake_case__   ,						guidance_scale=7.5   ,						num_inference_steps=50   ,						output_type='numpy' ).images

            _lowerCAmelCase     :				Optional[int]       =							image[0, 253:256, 253:256, -1]

            assert image.shape == (1, 512, 512, 3)
            _lowerCAmelCase     :				Dict       =							np.array([0.3367, 0.3169, 0.2656, 0.3870, 0.4790, 0.3796, 0.4009, 0.4878, 0.4778] )

            assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2





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

