



'''simple docstring'''






from __future__ import annotations

import unittest

from transformers import CTRLConfig, is_tf_available
from transformers.testing_utils import require_tf, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
   import tensorflow as tf

   from transformers.models.ctrl.modeling_tf_ctrl import (
       TF_CTRL_PRETRAINED_MODEL_ARCHIVE_LIST,
       TFCTRLForSequenceClassification,
       TFCTRLLMHeadModel,
       TFCTRLModel,
   )



class 				lowercase			(    _lowerCamelCase							):


 """simple docstring"""


 def __init__(				self    ,a_    ,)						->  Tuple:
        _UpperCAmelCase    :		str     	=					parent
        _UpperCAmelCase    :		int     	=					13
        _UpperCAmelCase    :		Union[str, Any]     	=					7
        _UpperCAmelCase    :		Any     	=					True
        _UpperCAmelCase    :		Optional[int]     	=					True
        _UpperCAmelCase    :		Union[str, Any]     	=					True
        _UpperCAmelCase    :		List[Any]     	=					True
        _UpperCAmelCase    :		Any     	=					True
        _UpperCAmelCase    :		str     	=					99
        _UpperCAmelCase    :		List[str]     	=					32
        _UpperCAmelCase    :		str     	=					2
        _UpperCAmelCase    :		Optional[Any]     	=					4
        _UpperCAmelCase    :		List[str]     	=					37
        _UpperCAmelCase    :		Union[str, Any]     	=					"""gelu"""
        _UpperCAmelCase    :		Any     	=					0.1
        _UpperCAmelCase    :		int     	=					0.1
        _UpperCAmelCase    :		Optional[Any]     	=					512
        _UpperCAmelCase    :		List[Any]     	=					16
        _UpperCAmelCase    :		List[str]     	=					2
        _UpperCAmelCase    :		List[str]     	=					0.02
        _UpperCAmelCase    :		List[Any]     	=					3
        _UpperCAmelCase    :		Any     	=					4
        _UpperCAmelCase    :		List[str]     	=					None
        _UpperCAmelCase    :		Optional[int]     	=					self.vocab_size - 1







 def _snake_case					(				self				)						->  List[Any]:
        _UpperCAmelCase    :		str     	=					ids_tensor([self.batch_size, self.seq_length]    ,self.vocab_size				)

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

        _UpperCAmelCase    :		str     	=					None
        if self.use_token_type_ids:
               _UpperCAmelCase    :		Optional[Any]     	=					ids_tensor([self.batch_size, self.seq_length]    ,self.type_vocab_size				)

        _UpperCAmelCase    :		List[Any]     	=					None
        if self.use_mc_token_ids:
               _UpperCAmelCase    :		int     	=					ids_tensor([self.batch_size, self.num_choices]    ,self.seq_length				)

        _UpperCAmelCase    :		int     	=					None
        _UpperCAmelCase    :		Any     	=					None
        _UpperCAmelCase    :		Any     	=					None
        if self.use_labels:
               _UpperCAmelCase    :		List[str]     	=					ids_tensor([self.batch_size]    ,self.type_sequence_label_size				)
               _UpperCAmelCase    :		Any     	=					ids_tensor([self.batch_size, self.seq_length]    ,self.num_labels				)
               _UpperCAmelCase    :		Optional[Any]     	=					ids_tensor([self.batch_size]    ,self.num_choices				)

        _UpperCAmelCase    :		Optional[int]     	=					CTRLConfig(
            vocab_size=self.vocab_size    ,n_embd=self.hidden_size    ,n_layer=self.num_hidden_layers    ,n_head=self.num_attention_heads    ,n_positions=self.max_position_embeddings    ,pad_token_id=self.pad_token_id    ,)

        _UpperCAmelCase    :		str     	=					ids_tensor([self.num_hidden_layers, self.num_attention_heads]    ,2				)

        return (
            config,
            input_ids,
            input_mask,
            head_mask,
            token_type_ids,
            mc_token_ids,
            sequence_labels,
            token_labels,
            choice_labels,
        )







 def _snake_case					(				self    ,a_    ,a_    ,a_    ,a_    ,a_    ,*a_				)						->  List[str]:
        _UpperCAmelCase    :		int     	=					TFCTRLModel(config=a_				)
        _UpperCAmelCase    :		Tuple     	=					{"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids}
        _UpperCAmelCase    :		Tuple     	=					model(a_				)

        _UpperCAmelCase    :		str     	=					[input_ids, None, input_mask]  # None is the input for 'past'
        _UpperCAmelCase    :		List[Any]     	=					model(a_				)

        _UpperCAmelCase    :		Union[str, Any]     	=					model(a_				)

        self.parent.assertEqual(result.last_hidden_state.shape    ,(self.batch_size, self.seq_length, self.hidden_size)				)







 def _snake_case					(				self    ,a_    ,a_    ,a_    ,a_    ,a_    ,*a_				)						->  List[str]:
        _UpperCAmelCase    :		str     	=					TFCTRLLMHeadModel(config=a_				)
        _UpperCAmelCase    :		Optional[Any]     	=					{"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids}
        _UpperCAmelCase    :		Union[str, Any]     	=					model(a_				)
        self.parent.assertEqual(result.logits.shape    ,(self.batch_size, self.seq_length, self.vocab_size)				)







 def _snake_case					(				self    ,a_    ,a_    ,a_    ,a_    ,a_    ,*a_				)						->  Union[str, Any]:
        _UpperCAmelCase    :		Any     	=					self.num_labels
        _UpperCAmelCase    :		int     	=					ids_tensor([self.batch_size]    ,self.type_sequence_label_size				)
        _UpperCAmelCase    :		int     	=					{
            """input_ids""": input_ids,
            """token_type_ids""": token_type_ids,
            """labels""": sequence_labels,
        }
        _UpperCAmelCase    :		str     	=					TFCTRLForSequenceClassification(a_				)
        _UpperCAmelCase    :		Tuple     	=					model(a_				)
        self.parent.assertEqual(result.logits.shape    ,(self.batch_size, self.num_labels)				)







 def _snake_case					(				self				)						->  List[str]:
        _UpperCAmelCase    :		Dict     	=					self.prepare_config_and_inputs()

        (
            (
            _UpperCAmelCase
        )	,(
            _UpperCAmelCase
        )	,(
            _UpperCAmelCase
        )	,(
            _UpperCAmelCase
        )	,(
            _UpperCAmelCase
        )	,(
            _UpperCAmelCase
        )	,(
            _UpperCAmelCase
        )	,(
            _UpperCAmelCase
        )	,(
            _UpperCAmelCase
        )	,
        )    :		List[Any]     	=					config_and_inputs

        _UpperCAmelCase    :		Optional[int]     	=					{"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask}
        return config, inputs_dict







@require_tf
class 				lowercase			(    _lowerCamelCase   ,   _lowerCamelCase   ,   unittest.TestCase							):


 """simple docstring"""


 UpperCAmelCase		      =    (TFCTRLModel, TFCTRLLMHeadModel, TFCTRLForSequenceClassification) if is_tf_available() else ()
 UpperCAmelCase		      =    (TFCTRLLMHeadModel,) if is_tf_available() else ()
 UpperCAmelCase		      =    (
     {
         """feature-extraction""": TFCTRLModel,
         """text-classification""": TFCTRLForSequenceClassification,
         """text-generation""": TFCTRLLMHeadModel,
         """zero-shot""": TFCTRLForSequenceClassification,
     }
     if is_tf_available()
     else {}
 )
 UpperCAmelCase		      =    False
 UpperCAmelCase		      =    False







 def _snake_case					(				self    ,a_    ,a_    ,a_    ,a_    ,a_				)						->  List[str]:
        if pipeline_test_casse_name == "ZeroShotClassificationPipelineTests":
               # Get `tokenizer does not have a padding token` error for both fast/slow tokenizers.
               # `CTRLConfig` was never used in pipeline tests, either because of a missing checkpoint or because a tiny
               # config could not be created.
               return True

        return False







 def _snake_case					(				self				)						->  Optional[int]:
        _UpperCAmelCase    :		Union[str, Any]     	=					TFCTRLModelTester(self				)
        _UpperCAmelCase    :		Any     	=					ConfigTester(self    ,config_class=a_    ,n_embd=37				)







 def _snake_case					(				self				)						->  List[str]:
        self.config_tester.run_common_tests()







 def _snake_case					(				self				)						->  List[str]:
        _UpperCAmelCase    :		List[str]     	=					self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_ctrl_model(*a_				)







 def _snake_case					(				self				)						->  Dict:
        _UpperCAmelCase    :		List[str]     	=					self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_ctrl_lm_head(*a_				)







 def _snake_case					(				self				)						->  str:
        _UpperCAmelCase    :		List[Any]     	=					self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_ctrl_for_sequence_classification(*a_				)







 def _snake_case					(				self				)						->  List[Any]:
        _UpperCAmelCase	,_UpperCAmelCase    :		Tuple     	=					self.model_tester.prepare_config_and_inputs_for_common()
        _UpperCAmelCase    :		Union[str, Any]     	=					[TFCTRLLMHeadModel]
        _UpperCAmelCase    :		Optional[Any]     	=					[TFCTRLForSequenceClassification]

        for model_class in self.all_model_classes:
               _UpperCAmelCase    :		List[Any]     	=					model_class(a_				)
               model.build()  # may be needed for the get_bias() call below
               assert isinstance(model.get_input_embeddings()    ,tf.keras.layers.Layer				)

               if model_class in list_lm_models:
                      _UpperCAmelCase    :		List[Any]     	=					model.get_output_embeddings()
                      assert isinstance(a_    ,tf.keras.layers.Layer				)
                      _UpperCAmelCase    :		Tuple     	=					model.get_bias()
                      assert isinstance(a_    ,a_				)
                      for k, v in name.items():
                             assert isinstance(a_    ,tf.Variable				)
               elif model_class in list_other_models_with_output_ebd:
                      _UpperCAmelCase    :		Tuple     	=					model.get_output_embeddings()
                      assert isinstance(a_    ,tf.keras.layers.Layer				)
                      _UpperCAmelCase    :		Union[str, Any]     	=					model.get_bias()
                      assert name is None
               else:
                      _UpperCAmelCase    :		Any     	=					model.get_output_embeddings()
                      assert x is None
                      _UpperCAmelCase    :		Any     	=					model.get_bias()
                      assert name is None







 @slow
 def _snake_case					(				self				)						->  List[str]:
        for model_name in TF_CTRL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
               _UpperCAmelCase    :		List[str]     	=					TFCTRLModel.from_pretrained(a_				)
               self.assertIsNotNone(a_				)







@require_tf
class 				lowercase			(    unittest.TestCase							):


 """simple docstring"""


 @slow
 def _snake_case					(				self				)						->  Any:
        _UpperCAmelCase    :		Dict     	=					TFCTRLLMHeadModel.from_pretrained("""ctrl"""				)
        _UpperCAmelCase    :		str     	=					tf.convert_to_tensor([[11_859, 0, 1_611, 8]]    ,dtype=tf.intaa				)  # Legal the president is
        _UpperCAmelCase    :		Tuple     	=					[
            11_859,
            0,
            1_611,
            8,
            5,
            150,
            26_449,
            2,
            19,
            348,
            469,
            3,
            2_595,
            48,
            20_740,
            246_533,
            246_533,
            19,
            30,
            5,
        ]  # Legal the president is a good guy and I don't want to lose my job. \n \n I have a

        _UpperCAmelCase    :		List[Any]     	=					model.generate(a_    ,do_sample=a_				)
        self.assertListEqual(output_ids[0].numpy().tolist()    ,a_				)







"""simple docstring"""






import gc
import tempfile
import unittest

import numpy as np
import torch

from diffusers import VersatileDiffusionDualGuidedPipeline
from diffusers.utils.testing_utils import load_image, nightly, require_torch_gpu, torch_device


__snake_case												=							False


@nightly
@require_torch_gpu
class      __lowerCamelCase	(       unittest.TestCase					):

     '''simple docstring'''


     def 				_UpperCAmelCase   (   self				)							->				Tuple:
          # clean up the VRAM after each test
          super().tearDown()
          gc.collect()
          torch.cuda.empty_cache()


     def 				_UpperCAmelCase   (   self				)							->				List[str]:
          _a     						=					VersatileDiffusionDualGuidedPipeline.from_pretrained('''shi-labs/versatile-diffusion'''				)
          # remove text_unet
          pipe.remove_unused_weights()
          pipe.to(__UpperCAmelCase				)
          pipe.set_progress_bar_config(disable=__UpperCAmelCase				)

          _a     						=					load_image(
              '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg'''				)

          _a     						=					torch.manual_seed(0				)
          _a     						=					pipe(
              prompt='''first prompt'''     ,					image=__UpperCAmelCase     ,					text_to_image_strength=0.75     ,					generator=__UpperCAmelCase     ,					guidance_scale=7.5     ,					num_inference_steps=2     ,					output_type='''numpy'''     ,					).images

          with tempfile.TemporaryDirectory() as tmpdirname:
               pipe.save_pretrained(__UpperCAmelCase				)
               _a     						=					VersatileDiffusionDualGuidedPipeline.from_pretrained(__UpperCAmelCase				)

          pipe.to(__UpperCAmelCase				)
          pipe.set_progress_bar_config(disable=__UpperCAmelCase				)

          _a     						=					generator.manual_seed(0				)
          _a     						=					pipe(
              prompt='''first prompt'''     ,					image=__UpperCAmelCase     ,					text_to_image_strength=0.75     ,					generator=__UpperCAmelCase     ,					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 				_UpperCAmelCase   (   self				)							->				Dict:
          _a     						=					VersatileDiffusionDualGuidedPipeline.from_pretrained('''shi-labs/versatile-diffusion'''				)
          pipe.remove_unused_weights()
          pipe.to(__UpperCAmelCase				)
          pipe.set_progress_bar_config(disable=__UpperCAmelCase				)

          _a     						=					'''cyberpunk 2077'''
          _a     						=					load_image(
              '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg'''				)
          _a     						=					torch.manual_seed(0				)
          _a     						=					pipe(
              prompt=__UpperCAmelCase     ,					image=__UpperCAmelCase     ,					text_to_image_strength=0.75     ,					generator=__UpperCAmelCase     ,					guidance_scale=7.5     ,					num_inference_steps=50     ,					output_type='''numpy'''     ,					).images

          _a     						=					image[0, 253:256, 253:256, -1]

          assert image.shape == (1, 512, 512, 3)
          _a     						=					np.array([0.0787, 0.0849, 0.0826, 0.0812, 0.0807, 0.0795, 0.0818, 0.0798, 0.0779]				)

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