
'''simple docstring'''

import random
import unittest

import torch

from diffusers import IFSuperResolutionPipeline
from diffusers.utils import floats_tensor
from diffusers.utils.import_utils import is_xformers_available
from diffusers.utils.testing_utils import skip_mps, torch_device

from ..pipeline_params import TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS
from ..test_pipelines_common import PipelineTesterMixin
from . import IFPipelineTesterMixin


@skip_mps
class 		_a     (							SCREAMING_SNAKE_CASE			,    SCREAMING_SNAKE_CASE			,    unittest.TestCase  ):







   """simple docstring"""




   A		= IFSuperResolutionPipeline
   A		= TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'width', 'height'}
   A		= TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS
   A		= PipelineTesterMixin.required_optional_params - {'latents'}






   def 					__a			(       self      ):
    return self._get_superresolution_dummy_components()






   def 					__a			(       self    ,__SCREAMING_SNAKE_CASE    ,__SCREAMING_SNAKE_CASE=0      ):
    if str(__SCREAMING_SNAKE_CASE      ).startswith('mps'      ):
     SCREAMING_SNAKE_CASE  :  Union[str, Any]								=		torch.manual_seed(__SCREAMING_SNAKE_CASE      )
    else:
     SCREAMING_SNAKE_CASE  :  Union[str, Any]								=		torch.Generator(device=__SCREAMING_SNAKE_CASE      ).manual_seed(__SCREAMING_SNAKE_CASE      )

    SCREAMING_SNAKE_CASE  :  List[Any]								=		floats_tensor((1, 3, 32, 32)    ,rng=random.Random(__SCREAMING_SNAKE_CASE      )      ).to(__SCREAMING_SNAKE_CASE      )

    SCREAMING_SNAKE_CASE  :  Optional[Any]								=		{
        'prompt': 'A painting of a squirrel eating a burger',
        'image': image,
        'generator': generator,
        'num_inference_steps': 2,
        'output_type': 'numpy',
    }

    return inputs






   @unittest.skipIf(
       torch_device != 'cuda' or not is_xformers_available()    ,reason='XFormers attention is only available with CUDA and `xformers` installed'    ,)
   def 					__a			(       self      ):
    self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3      )






   def 					__a			(       self      ):
    self._test_save_load_optional_components()






   @unittest.skipIf(torch_device != 'cuda'    ,reason='float16 requires CUDA'      )
   def 					__a			(       self      ):
    # Due to non-determinism in save load of the hf-internal-testing/tiny-random-t5 text encoder
    super().test_save_load_floataa(expected_max_diff=1e-1      )






   def 					__a			(       self      ):
    self._test_attention_slicing_forward_pass(expected_max_diff=1e-2      )






   def 					__a			(       self      ):
    self._test_save_load_local()






   def 					__a			(       self      ):
    self._test_inference_batch_single_identical(
        expected_max_diff=1e-2    ,)




'''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 		_a     (							SCREAMING_SNAKE_CASE  ):







   """simple docstring"""




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






   def 					__a			(       self      ):
    SCREAMING_SNAKE_CASE  :  Any								=		ids_tensor([self.batch_size, self.seq_length]    ,self.vocab_size      )

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

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

    SCREAMING_SNAKE_CASE  :  int								=		None
    if self.use_mc_token_ids:
     SCREAMING_SNAKE_CASE  :  Union[str, Any]								=		ids_tensor([self.batch_size, self.num_choices]    ,self.seq_length      )

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

    SCREAMING_SNAKE_CASE  :  Dict								=		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    ,)

    SCREAMING_SNAKE_CASE  :  Tuple								=		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 					__a			(       self    ,__SCREAMING_SNAKE_CASE    ,__SCREAMING_SNAKE_CASE    ,__SCREAMING_SNAKE_CASE    ,__SCREAMING_SNAKE_CASE    ,__SCREAMING_SNAKE_CASE    ,*__SCREAMING_SNAKE_CASE      ):
    SCREAMING_SNAKE_CASE  :  int								=		TFCTRLModel(config=__SCREAMING_SNAKE_CASE      )
    SCREAMING_SNAKE_CASE  :  Union[str, Any]								=		{'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids}
    SCREAMING_SNAKE_CASE  :  Union[str, Any]								=		model(__SCREAMING_SNAKE_CASE      )

    SCREAMING_SNAKE_CASE  :  Union[str, Any]								=		[input_ids, None, input_mask]  # None is the input for 'past'
    SCREAMING_SNAKE_CASE  :  Union[str, Any]								=		model(__SCREAMING_SNAKE_CASE      )

    SCREAMING_SNAKE_CASE  :  Tuple								=		model(__SCREAMING_SNAKE_CASE      )

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






   def 					__a			(       self    ,__SCREAMING_SNAKE_CASE    ,__SCREAMING_SNAKE_CASE    ,__SCREAMING_SNAKE_CASE    ,__SCREAMING_SNAKE_CASE    ,__SCREAMING_SNAKE_CASE    ,*__SCREAMING_SNAKE_CASE      ):
    SCREAMING_SNAKE_CASE  :  Optional[int]								=		TFCTRLLMHeadModel(config=__SCREAMING_SNAKE_CASE      )
    SCREAMING_SNAKE_CASE  :  Any								=		{'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids}
    SCREAMING_SNAKE_CASE  :  Any								=		model(__SCREAMING_SNAKE_CASE      )
    self.parent.assertEqual(result.logits.shape    ,(self.batch_size, self.seq_length, self.vocab_size)      )






   def 					__a			(       self    ,__SCREAMING_SNAKE_CASE    ,__SCREAMING_SNAKE_CASE    ,__SCREAMING_SNAKE_CASE    ,__SCREAMING_SNAKE_CASE    ,__SCREAMING_SNAKE_CASE    ,*__SCREAMING_SNAKE_CASE      ):
    SCREAMING_SNAKE_CASE  :  Tuple								=		self.num_labels
    SCREAMING_SNAKE_CASE  :  Any								=		ids_tensor([self.batch_size]    ,self.type_sequence_label_size      )
    SCREAMING_SNAKE_CASE  :  Dict								=		{
        'input_ids': input_ids,
        'token_type_ids': token_type_ids,
        'labels': sequence_labels,
    }
    SCREAMING_SNAKE_CASE  :  Union[str, Any]								=		TFCTRLForSequenceClassification(__SCREAMING_SNAKE_CASE      )
    SCREAMING_SNAKE_CASE  :  str								=		model(__SCREAMING_SNAKE_CASE      )
    self.parent.assertEqual(result.logits.shape    ,(self.batch_size, self.num_labels)      )






   def 					__a			(       self      ):
    SCREAMING_SNAKE_CASE  :  str								=		self.prepare_config_and_inputs()

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

    SCREAMING_SNAKE_CASE  :  int								=		{'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask}
    return config, inputs_dict



@require_tf
class 		_a     (							SCREAMING_SNAKE_CASE			,    SCREAMING_SNAKE_CASE			,    unittest.TestCase  ):







   """simple docstring"""




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






   def 					__a			(       self    ,__SCREAMING_SNAKE_CASE    ,__SCREAMING_SNAKE_CASE    ,__SCREAMING_SNAKE_CASE    ,__SCREAMING_SNAKE_CASE    ,__SCREAMING_SNAKE_CASE      ):
    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 					__a			(       self      ):
    SCREAMING_SNAKE_CASE  :  List[Any]								=		TFCTRLModelTester(self      )
    SCREAMING_SNAKE_CASE  :  Dict								=		ConfigTester(self    ,config_class=__SCREAMING_SNAKE_CASE    ,n_embd=37      )






   def 					__a			(       self      ):
    self.config_tester.run_common_tests()






   def 					__a			(       self      ):
    SCREAMING_SNAKE_CASE  :  Tuple								=		self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_ctrl_model(*__SCREAMING_SNAKE_CASE      )






   def 					__a			(       self      ):
    SCREAMING_SNAKE_CASE  :  str								=		self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_ctrl_lm_head(*__SCREAMING_SNAKE_CASE      )






   def 					__a			(       self      ):
    SCREAMING_SNAKE_CASE  :  Optional[Any]								=		self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_ctrl_for_sequence_classification(*__SCREAMING_SNAKE_CASE      )






   def 					__a			(       self      ):
    SCREAMING_SNAKE_CASE				, SCREAMING_SNAKE_CASE  :  Tuple								=		self.model_tester.prepare_config_and_inputs_for_common()
    SCREAMING_SNAKE_CASE  :  Any								=		[TFCTRLLMHeadModel]
    SCREAMING_SNAKE_CASE  :  str								=		[TFCTRLForSequenceClassification]

    for model_class in self.all_model_classes:
     SCREAMING_SNAKE_CASE  :  List[str]								=		model_class(__SCREAMING_SNAKE_CASE      )
     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:
      SCREAMING_SNAKE_CASE  :  Dict								=		model.get_output_embeddings()
      assert isinstance(__SCREAMING_SNAKE_CASE    ,tf.keras.layers.Layer      )
      SCREAMING_SNAKE_CASE  :  Any								=		model.get_bias()
      assert isinstance(__SCREAMING_SNAKE_CASE    ,__SCREAMING_SNAKE_CASE      )
      for k, v in name.items():
       assert isinstance(__SCREAMING_SNAKE_CASE    ,tf.Variable      )
     elif model_class in list_other_models_with_output_ebd:
      SCREAMING_SNAKE_CASE  :  Any								=		model.get_output_embeddings()
      assert isinstance(__SCREAMING_SNAKE_CASE    ,tf.keras.layers.Layer      )
      SCREAMING_SNAKE_CASE  :  str								=		model.get_bias()
      assert name is None
     else:
      SCREAMING_SNAKE_CASE  :  List[Any]								=		model.get_output_embeddings()
      assert x is None
      SCREAMING_SNAKE_CASE  :  int								=		model.get_bias()
      assert name is None






   @slow
   def 					__a			(       self      ):
    for model_name in TF_CTRL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
     SCREAMING_SNAKE_CASE  :  List[str]								=		TFCTRLModel.from_pretrained(__SCREAMING_SNAKE_CASE      )
     self.assertIsNotNone(__SCREAMING_SNAKE_CASE      )



@require_tf
class 		_a     (							unittest.TestCase  ):







   """simple docstring"""




   @slow
   def 					__a			(       self      ):
    SCREAMING_SNAKE_CASE  :  Union[str, Any]								=		TFCTRLLMHeadModel.from_pretrained('ctrl'      )
    SCREAMING_SNAKE_CASE  :  Any								=		tf.convert_to_tensor([[11859, 0, 1611, 8]]    ,dtype=tf.intaa      )  # Legal the president is
    SCREAMING_SNAKE_CASE  :  Optional[Any]								=		[
        11859,
        0,
        1611,
        8,
        5,
        150,
        26449,
        2,
        19,
        348,
        469,
        3,
        2595,
        48,
        20740,
        246533,
        246533,
        19,
        30,
        5,
    ]  # Legal the president is a good guy and I don't want to lose my job. \n \n I have a

    SCREAMING_SNAKE_CASE  :  Union[str, Any]								=		model.generate(__SCREAMING_SNAKE_CASE    ,do_sample=__SCREAMING_SNAKE_CASE      )
    self.assertListEqual(output_ids[0].numpy().tolist()    ,__SCREAMING_SNAKE_CASE      )


