





'''simple docstring'''




from __future__ import annotations

import unittest

from transformers import FunnelConfig, is_tf_available
from transformers.testing_utils import require_tf

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 import (
      TFFunnelBaseModel,
      TFFunnelForMaskedLM,
      TFFunnelForMultipleChoice,
      TFFunnelForPreTraining,
      TFFunnelForQuestionAnswering,
      TFFunnelForSequenceClassification,
      TFFunnelForTokenClassification,
      TFFunnelModel,
  )







class   A_	:




 def __init__(					self       :    List[Any]	,			snake_case_       :    List[str]	,			snake_case_       :    Tuple=1_3	,			snake_case_       :    Any=7	,			snake_case_       :    Optional[int]=True	,			snake_case_       :    Optional[int]=True	,			snake_case_       :    int=True	,			snake_case_       :    List[Any]=True	,			snake_case_       :    List[Any]=9_9	,			snake_case_       :    Optional[Any]=[1, 1, 2]	,			snake_case_       :    Any=1	,			snake_case_       :    List[Any]=3_2	,			snake_case_       :    str=4	,			snake_case_       :    Union[str, Any]=8	,			snake_case_       :    str=3_7	,			snake_case_       :    Union[str, Any]="gelu_new"	,			snake_case_       :    Optional[Any]=0.1	,			snake_case_       :    Optional[Any]=0.1	,			snake_case_       :    str=0.0	,			snake_case_       :    int=5_1_2	,			snake_case_       :    Tuple=3	,			snake_case_       :    str=0.0_2	,			snake_case_       :    Dict=3	,			snake_case_       :    str=4	,			snake_case_       :    Dict=None	,			snake_case_       :    str=False	,			):
      _UpperCAmelCase     							=   parent
      _UpperCAmelCase     							=   batch_size
      _UpperCAmelCase     							=   seq_length
      _UpperCAmelCase     							=   is_training
      _UpperCAmelCase     							=   use_input_mask
      _UpperCAmelCase     							=   use_token_type_ids
      _UpperCAmelCase     							=   use_labels
      _UpperCAmelCase     							=   vocab_size
      _UpperCAmelCase     							=   block_sizes
      _UpperCAmelCase     							=   num_decoder_layers
      _UpperCAmelCase     							=   d_model
      _UpperCAmelCase     							=   n_head
      _UpperCAmelCase     							=   d_head
      _UpperCAmelCase     							=   d_inner
      _UpperCAmelCase     							=   hidden_act
      _UpperCAmelCase     							=   hidden_dropout
      _UpperCAmelCase     							=   attention_dropout
      _UpperCAmelCase     							=   activation_dropout
      _UpperCAmelCase     							=   max_position_embeddings
      _UpperCAmelCase     							=   type_vocab_size
      _UpperCAmelCase     							=   2
      _UpperCAmelCase     							=   num_labels
      _UpperCAmelCase     							=   num_choices
      _UpperCAmelCase     							=   scope
      _UpperCAmelCase     							=   initializer_std

      # Used in the tests to check the size of the first attention layer
      _UpperCAmelCase     							=   n_head
      # Used in the tests to check the size of the first hidden state
      _UpperCAmelCase     							=   self.d_model
      # Used in the tests to check the number of output hidden states/attentions
      _UpperCAmelCase     							=   sum(self.block_sizes    ) + (0 if base else self.num_decoder_layers)
      # FunnelModel adds two hidden layers: input embeddings and the sum of the upsampled encoder hidden state with
      # the last hidden state of the first block (which is the first hidden state of the decoder).
      if not base:
           _UpperCAmelCase     							=   self.num_hidden_layers + 2




 def      lowercase	(					self       :    Tuple    ):
      _UpperCAmelCase     							=   ids_tensor([self.batch_size, self.seq_length]	,			self.vocab_size    )

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

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

      _UpperCAmelCase     							=   None
      _UpperCAmelCase     							=   None
      _UpperCAmelCase     							=   None
      if self.use_labels:
           _UpperCAmelCase     							=   ids_tensor([self.batch_size]	,			self.type_sequence_label_size    )
           _UpperCAmelCase     							=   ids_tensor([self.batch_size, self.seq_length]	,			self.num_labels    )
           _UpperCAmelCase     							=   ids_tensor([self.batch_size]	,			self.num_choices    )

      _UpperCAmelCase     							=   FunnelConfig(
          vocab_size=self.vocab_size	,			block_sizes=self.block_sizes	,			num_decoder_layers=self.num_decoder_layers	,			d_model=self.d_model	,			n_head=self.n_head	,			d_head=self.d_head	,			d_inner=self.d_inner	,			hidden_act=self.hidden_act	,			hidden_dropout=self.hidden_dropout	,			attention_dropout=self.attention_dropout	,			activation_dropout=self.activation_dropout	,			max_position_embeddings=self.max_position_embeddings	,			type_vocab_size=self.type_vocab_size	,			initializer_std=self.initializer_std	,			)

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




 def      lowercase	(					self       :    List[Any]	,			snake_case_       :    Optional[Any]	,			snake_case_       :    List[str]	,			snake_case_       :    List[str]	,			snake_case_       :    Union[str, Any]	,			snake_case_       :    Dict	,			snake_case_       :    Union[str, Any]	,			snake_case_       :    str	,			):
      _UpperCAmelCase     							=   TFFunnelModel(config=snake_case_    )
      _UpperCAmelCase     							=   {'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids}
      _UpperCAmelCase     							=   model(snake_case_    )

      _UpperCAmelCase     							=   [input_ids, input_mask]
      _UpperCAmelCase     							=   model(snake_case_    )

      _UpperCAmelCase     							=   model(snake_case_    )
      self.parent.assertEqual(result.last_hidden_state.shape	,			(self.batch_size, self.seq_length, self.d_model)    )

      _UpperCAmelCase     							=   False
      _UpperCAmelCase     							=   TFFunnelModel(config=snake_case_    )
      _UpperCAmelCase     							=   model(snake_case_    )
      self.parent.assertEqual(result.last_hidden_state.shape	,			(self.batch_size, self.seq_length, self.d_model)    )

      _UpperCAmelCase     							=   False
      _UpperCAmelCase     							=   TFFunnelModel(config=snake_case_    )
      _UpperCAmelCase     							=   model(snake_case_    )
      self.parent.assertEqual(result.last_hidden_state.shape	,			(self.batch_size, self.seq_length, self.d_model)    )




 def      lowercase	(					self       :    List[Any]	,			snake_case_       :    Optional[int]	,			snake_case_       :    Tuple	,			snake_case_       :    Dict	,			snake_case_       :    Any	,			snake_case_       :    Optional[int]	,			snake_case_       :    int	,			snake_case_       :    Optional[Any]	,			):
      _UpperCAmelCase     							=   TFFunnelBaseModel(config=snake_case_    )
      _UpperCAmelCase     							=   {'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids}
      _UpperCAmelCase     							=   model(snake_case_    )

      _UpperCAmelCase     							=   [input_ids, input_mask]
      _UpperCAmelCase     							=   model(snake_case_    )

      _UpperCAmelCase     							=   model(snake_case_    )
      self.parent.assertEqual(result.last_hidden_state.shape	,			(self.batch_size, 2, self.d_model)    )

      _UpperCAmelCase     							=   False
      _UpperCAmelCase     							=   TFFunnelBaseModel(config=snake_case_    )
      _UpperCAmelCase     							=   model(snake_case_    )
      self.parent.assertEqual(result.last_hidden_state.shape	,			(self.batch_size, 3, self.d_model)    )

      _UpperCAmelCase     							=   False
      _UpperCAmelCase     							=   TFFunnelBaseModel(config=snake_case_    )
      _UpperCAmelCase     							=   model(snake_case_    )
      self.parent.assertEqual(result.last_hidden_state.shape	,			(self.batch_size, 2, self.d_model)    )




 def      lowercase	(					self       :    Dict	,			snake_case_       :    Any	,			snake_case_       :    int	,			snake_case_       :    List[str]	,			snake_case_       :    Union[str, Any]	,			snake_case_       :    List[Any]	,			snake_case_       :    Tuple	,			snake_case_       :    List[str]	,			):
      _UpperCAmelCase     							=   TFFunnelForPreTraining(config=snake_case_    )
      _UpperCAmelCase     							=   {'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids}
      _UpperCAmelCase     							=   model(snake_case_    )
      self.parent.assertEqual(result.logits.shape	,			(self.batch_size, self.seq_length)    )




 def      lowercase	(					self       :    Dict	,			snake_case_       :    Union[str, Any]	,			snake_case_       :    List[str]	,			snake_case_       :    int	,			snake_case_       :    int	,			snake_case_       :    Dict	,			snake_case_       :    List[Any]	,			snake_case_       :    Optional[int]	,			):
      _UpperCAmelCase     							=   TFFunnelForMaskedLM(config=snake_case_    )
      _UpperCAmelCase     							=   {'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids}
      _UpperCAmelCase     							=   model(snake_case_    )
      self.parent.assertEqual(result.logits.shape	,			(self.batch_size, self.seq_length, self.vocab_size)    )




 def      lowercase	(					self       :    int	,			snake_case_       :    Tuple	,			snake_case_       :    Optional[int]	,			snake_case_       :    Optional[Any]	,			snake_case_       :    int	,			snake_case_       :    Any	,			snake_case_       :    Optional[Any]	,			snake_case_       :    Dict	,			):
      _UpperCAmelCase     							=   self.num_labels
      _UpperCAmelCase     							=   TFFunnelForSequenceClassification(config=snake_case_    )
      _UpperCAmelCase     							=   {'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids}
      _UpperCAmelCase     							=   model(snake_case_    )
      self.parent.assertEqual(result.logits.shape	,			(self.batch_size, self.num_labels)    )




 def      lowercase	(					self       :    str	,			snake_case_       :    int	,			snake_case_       :    Optional[int]	,			snake_case_       :    Optional[Any]	,			snake_case_       :    str	,			snake_case_       :    str	,			snake_case_       :    Tuple	,			snake_case_       :    Dict	,			):
      _UpperCAmelCase     							=   self.num_choices
      _UpperCAmelCase     							=   TFFunnelForMultipleChoice(config=snake_case_    )
      _UpperCAmelCase     							=   tf.tile(tf.expand_dims(snake_case_	,			1    )	,			(1, self.num_choices, 1)    )
      _UpperCAmelCase     							=   tf.tile(tf.expand_dims(snake_case_	,			1    )	,			(1, self.num_choices, 1)    )
      _UpperCAmelCase     							=   tf.tile(tf.expand_dims(snake_case_	,			1    )	,			(1, self.num_choices, 1)    )
      _UpperCAmelCase     							=   {
          'input_ids': multiple_choice_inputs_ids,
          'attention_mask': multiple_choice_input_mask,
          'token_type_ids': multiple_choice_token_type_ids,
      }
      _UpperCAmelCase     							=   model(snake_case_    )
      self.parent.assertEqual(result.logits.shape	,			(self.batch_size, self.num_choices)    )




 def      lowercase	(					self       :    Optional[Any]	,			snake_case_       :    str	,			snake_case_       :    Union[str, Any]	,			snake_case_       :    Optional[int]	,			snake_case_       :    Optional[Any]	,			snake_case_       :    Any	,			snake_case_       :    Any	,			snake_case_       :    int	,			):
      _UpperCAmelCase     							=   self.num_labels
      _UpperCAmelCase     							=   TFFunnelForTokenClassification(config=snake_case_    )
      _UpperCAmelCase     							=   {'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids}
      _UpperCAmelCase     							=   model(snake_case_    )
      self.parent.assertEqual(result.logits.shape	,			(self.batch_size, self.seq_length, self.num_labels)    )




 def      lowercase	(					self       :    Optional[int]	,			snake_case_       :    Dict	,			snake_case_       :    Optional[Any]	,			snake_case_       :    Optional[Any]	,			snake_case_       :    int	,			snake_case_       :    int	,			snake_case_       :    Optional[int]	,			snake_case_       :    str	,			):
      _UpperCAmelCase     							=   TFFunnelForQuestionAnswering(config=snake_case_    )
      _UpperCAmelCase     							=   {'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids}
      _UpperCAmelCase     							=   model(snake_case_    )
      self.parent.assertEqual(result.start_logits.shape	,			(self.batch_size, self.seq_length)    )
      self.parent.assertEqual(result.end_logits.shape	,			(self.batch_size, self.seq_length)    )




 def      lowercase	(					self       :    Optional[Any]    ):
      _UpperCAmelCase     							=   self.prepare_config_and_inputs()
      (
          _UpperCAmelCase    
      )     							=   config_and_inputs
      _UpperCAmelCase     							=   {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask}
      return config, inputs_dict







@require_tf
class   A_	(  __lowerCAmelCase							,						__lowerCAmelCase							,						unittest.TestCase			):
 _lowerCamelCase  : Union[str, Any]           =							(
     (
         TFFunnelModel,
         TFFunnelForMaskedLM,
         TFFunnelForPreTraining,
         TFFunnelForQuestionAnswering,
         TFFunnelForTokenClassification,
     )
     if is_tf_available()
     else ()
 )
 _lowerCamelCase  : int           =							(
     {
         """feature-extraction""": (TFFunnelBaseModel, TFFunnelModel),
         """fill-mask""": TFFunnelForMaskedLM,
         """question-answering""": TFFunnelForQuestionAnswering,
         """text-classification""": TFFunnelForSequenceClassification,
         """token-classification""": TFFunnelForTokenClassification,
         """zero-shot""": TFFunnelForSequenceClassification,
     }
     if is_tf_available()
     else {}
 )
 _lowerCamelCase  : Union[str, Any]           =							False
 _lowerCamelCase  : Union[str, Any]           =							False




 def      lowercase	(					self       :    Optional[int]    ):
      _UpperCAmelCase     							=   TFFunnelModelTester(self    )
      _UpperCAmelCase     							=   ConfigTester(self	,			config_class=snake_case_    )




 def      lowercase	(					self       :    Union[str, Any]    ):
      self.config_tester.run_common_tests()




 def      lowercase	(					self       :    Dict    ):
      _UpperCAmelCase     							=   self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*snake_case_    )




 def      lowercase	(					self       :    Union[str, Any]    ):
      _UpperCAmelCase     							=   self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_pretraining(*snake_case_    )




 def      lowercase	(					self       :    str    ):
      _UpperCAmelCase     							=   self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_masked_lm(*snake_case_    )




 def      lowercase	(					self       :    Optional[int]    ):
      _UpperCAmelCase     							=   self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_token_classification(*snake_case_    )




 def      lowercase	(					self       :    Union[str, Any]    ):
      _UpperCAmelCase     							=   self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_question_answering(*snake_case_    )







@require_tf
class   A_	(  __lowerCAmelCase							,						unittest.TestCase			):
 _lowerCamelCase  : Tuple           =							(
     (TFFunnelBaseModel, TFFunnelForMultipleChoice, TFFunnelForSequenceClassification) if is_tf_available() else ()
 )
 _lowerCamelCase  : Optional[Any]           =							False
 _lowerCamelCase  : Optional[Any]           =							False




 def      lowercase	(					self       :    Optional[Any]    ):
      _UpperCAmelCase     							=   TFFunnelModelTester(self	,			base=snake_case_    )
      _UpperCAmelCase     							=   ConfigTester(self	,			config_class=snake_case_    )




 def      lowercase	(					self       :    str    ):
      self.config_tester.run_common_tests()




 def      lowercase	(					self       :    Optional[int]    ):
      _UpperCAmelCase     							=   self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_base_model(*snake_case_    )




 def      lowercase	(					self       :    List[str]    ):
      _UpperCAmelCase     							=   self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_sequence_classification(*snake_case_    )




 def      lowercase	(					self       :    List[Any]    ):
      _UpperCAmelCase     							=   self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_multiple_choice(*snake_case_    )





"""simple docstring"""
from typing import List, Optional, Tuple, Union

import PIL
import torch
from torchvision import transforms

from diffusers.pipeline_utils import DiffusionPipeline, ImagePipelineOutput
from diffusers.schedulers import DDIMScheduler
from diffusers.utils import randn_tensor


lowercase__					       =	transforms.Compose(
    [
        transforms.Resize((256, 256)),
        transforms.ToTensor(),
        transforms.Normalize([0.5], [0.5]),
    ]
)







def 						__a   (	_SCREAMING_SNAKE_CASE   )	->Any:
  if isinstance(_SCREAMING_SNAKE_CASE		,     torch.Tensor   ):
    return image
  elif isinstance(_SCREAMING_SNAKE_CASE		,     PIL.Image.Image   ):
    a__:     Optional[int]										=	[image]

  a__:     str										=	[trans(img.convert('RGB'   )   ) for img in image]
  a__:     Any										=	torch.stack(_SCREAMING_SNAKE_CASE   )
  return image




class    __snake_case       (     __lowerCAmelCase				):



      def __init__(						self    ,			lowercase    ,			lowercase)	->			Optional[int]:





        '''simple docstring'''





        super().__init__()

        # make sure scheduler can always be converted to DDIM
        a__:     Dict										=	DDIMScheduler.from_config(scheduler.config)

        self.register_modules(unet=lowercase    ,			scheduler=lowercase)



      def   lowerCamelCase_   (						self    ,			lowercase)	->			int:





        '''simple docstring'''





        if strength < 0 or strength > 1:
          raise ValueError(f'The value of strength should in [0.0, 1.0] but is {strength}')



      def   lowerCamelCase_   (						self    ,			lowercase    ,			lowercase    ,			lowercase)	->			Dict:





        '''simple docstring'''





        a__:     int										=	min(int(num_inference_steps * strength)    ,			lowercase)

        a__:     Any										=	max(num_inference_steps - init_timestep    ,			0)
        a__:     Union[str, Any]										=	self.scheduler.timesteps[t_start:]

        return timesteps, num_inference_steps - t_start



      def   lowerCamelCase_   (						self    ,			lowercase    ,			lowercase    ,			lowercase    ,			lowercase    ,			lowercase    ,			lowercase=None)	->			List[Any]:





        '''simple docstring'''





        if not isinstance(lowercase    ,			(torch.Tensor, PIL.Image.Image, list)):
          raise ValueError(
              f'`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(lowercase)}')

        a__:     Tuple										=	image.to(device=lowercase    ,			dtype=lowercase)

        if isinstance(lowercase    ,			lowercase) and len(lowercase) != batch_size:
          raise ValueError(
              f'You have passed a list of generators of length {len(lowercase)}, but requested an effective batch'
              f' size of {batch_size}. Make sure the batch size matches the length of the generators.')

        a__:     List[str]										=	init_latents.shape
        a__:     List[Any]										=	randn_tensor(lowercase    ,			generator=lowercase    ,			device=lowercase    ,			dtype=lowercase)

        # get latents
        print('add noise to latents at timestep'    ,			lowercase)
        a__:     int										=	self.scheduler.add_noise(lowercase    ,			lowercase    ,			lowercase)
        a__:     Dict										=	init_latents

        return latents



      @torch.no_grad()
      def __call__(						self    ,			lowercase = None    ,			lowercase = 0.8    ,			lowercase = 1    ,			lowercase = None    ,			lowercase = 0.0    ,			lowercase = 50    ,			lowercase = None    ,			lowercase = "pil"    ,			lowercase = True    ,			)	->			Union[ImagePipelineOutput, Tuple]:





        '''simple docstring'''





        self.check_inputs(lowercase)

        # 2. Preprocess image
        a__:     Tuple										=	preprocess(lowercase)

        # 3. set timesteps
        self.scheduler.set_timesteps(lowercase    ,			device=self.device)
        a__							,    a__:     Union[str, Any]										=	self.get_timesteps(lowercase    ,			lowercase    ,			self.device)
        a__:     Optional[int]										=	timesteps[:1].repeat(lowercase)

        # 4. Prepare latent variables
        a__:     Union[str, Any]										=	self.prepare_latents(lowercase    ,			lowercase    ,			lowercase    ,			self.unet.dtype    ,			self.device    ,			lowercase)
        a__:     Optional[Any]										=	latents

        # 5. Denoising loop
        for t in self.progress_bar(lowercase):
          # 1. predict noise model_output
          a__:     Dict										=	self.unet(lowercase    ,			lowercase).sample

          # 2. predict previous mean of image x_t-1 and add variance depending on eta
          # eta corresponds to η in paper and should be between [0, 1]
          # do x_t -> x_t-1
          a__:     Optional[Any]										=	self.scheduler.step(
              lowercase    ,			lowercase    ,			lowercase    ,			eta=lowercase    ,			use_clipped_model_output=lowercase    ,			generator=lowercase    ,			).prev_sample

        a__:     Union[str, Any]										=	(image / 2 + 0.5).clamp(0    ,			1)
        a__:     Optional[int]										=	image.cpu().permute(0    ,			2    ,			3    ,			1).numpy()
        if output_type == "pil":
          a__:     Dict										=	self.numpy_to_pil(lowercase)

        if not return_dict:
          return (image, latent_timestep.item())

        return ImagePipelineOutput(images=lowercase)


