


'''simple docstring'''
from __future__ import annotations

import unittest

from transformers import AutoTokenizer, PegasusConfig, is_tf_available
from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow
from transformers.utils import cached_property

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


if is_tf_available():
  import tensorflow as tf

  from transformers import TFAutoModelForSeqaSeqLM, TFPegasusForConditionalGeneration, TFPegasusModel




@require_tf
class 			lowerCamelCase_   :
      lowerCAmelCase__		     =     PegasusConfig
      lowerCAmelCase__		     =     {}
      lowerCAmelCase__		     =     'gelu'






      def __init__(					self				:    Union[str, Any]						,						_A				:    List[Any]						,						_A				:    Dict=13						,						_A				:    Tuple=7						,						_A				:    Union[str, Any]=True						,						_A				:    Optional[Any]=False						,						_A				:    Union[str, Any]=99						,						_A				:    Union[str, Any]=32						,						_A				:    Any=2						,						_A				:    Union[str, Any]=4						,						_A				:    Optional[Any]=37						,						_A				:    Union[str, Any]=0.1						,						_A				:    Any=0.1						,						_A				:    List[str]=40						,						_A				:    Optional[int]=2						,						_A				:    List[Any]=1						,						_A				:    List[Any]=0						,						):


          '''simple docstring'''


          UpperCAmelCase__			:		str													=				parent
          UpperCAmelCase__			:		Any													=				batch_size
          UpperCAmelCase__			:		List[Any]													=				seq_length
          UpperCAmelCase__			:		Dict													=				is_training
          UpperCAmelCase__			:		Any													=				use_labels
          UpperCAmelCase__			:		List[Any]													=				vocab_size
          UpperCAmelCase__			:		Union[str, Any]													=				hidden_size
          UpperCAmelCase__			:		Tuple													=				num_hidden_layers
          UpperCAmelCase__			:		List[str]													=				num_attention_heads
          UpperCAmelCase__			:		List[Any]													=				intermediate_size

          UpperCAmelCase__			:		str													=				hidden_dropout_prob
          UpperCAmelCase__			:		str													=				attention_probs_dropout_prob
          UpperCAmelCase__			:		int													=				max_position_embeddings
          UpperCAmelCase__			:		List[Any]													=				eos_token_id
          UpperCAmelCase__			:		Union[str, Any]													=				pad_token_id
          UpperCAmelCase__			:		Dict													=				bos_token_id






      def lowercase_							(					self				:    List[str] ):


          '''simple docstring'''


          UpperCAmelCase__			:		Dict													=				ids_tensor([self.batch_size, self.seq_length - 1]						,						self.vocab_size )
          UpperCAmelCase__			:		int													=				tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size )						,						1 )
          UpperCAmelCase__			:		Optional[Any]													=				tf.concat([input_ids, eos_tensor]						,						axis=1 )

          UpperCAmelCase__			:		int													=				ids_tensor([self.batch_size, self.seq_length]						,						self.vocab_size )

          UpperCAmelCase__			:		List[Any]													=				self.config_cls(
              vocab_size=self.vocab_size						,						d_model=self.hidden_size						,						encoder_layers=self.num_hidden_layers						,						decoder_layers=self.num_hidden_layers						,						encoder_attention_heads=self.num_attention_heads						,						decoder_attention_heads=self.num_attention_heads						,						encoder_ffn_dim=self.intermediate_size						,						decoder_ffn_dim=self.intermediate_size						,						dropout=self.hidden_dropout_prob						,						attention_dropout=self.attention_probs_dropout_prob						,						max_position_embeddings=self.max_position_embeddings						,						eos_token_ids=[2]						,						bos_token_id=self.bos_token_id						,						pad_token_id=self.pad_token_id						,						decoder_start_token_id=self.pad_token_id						,						**self.config_updates						,						)
          UpperCAmelCase__			:		Dict													=				prepare_pegasus_inputs_dict(_A						,						_A						,						_A )
          return config, inputs_dict






      def lowercase_							(					self				:    str						,						_A				:    Optional[Any]						,						_A				:    Optional[Any] ):


          '''simple docstring'''


          UpperCAmelCase__			:		Dict													=				TFPegasusModel(config=_A ).get_decoder()
          UpperCAmelCase__			:		str													=				inputs_dict['''input_ids''']

          UpperCAmelCase__			:		List[str]													=				input_ids[:1, :]
          UpperCAmelCase__			:		Any													=				inputs_dict['''attention_mask'''][:1, :]
          UpperCAmelCase__			:		Union[str, Any]													=				inputs_dict['''head_mask''']
          UpperCAmelCase__			:		Any													=				1

          # first forward pass
          UpperCAmelCase__			:		List[str]													=				model(_A						,						attention_mask=_A						,						head_mask=_A						,						use_cache=_A )

          UpperCAmelCase__						,						UpperCAmelCase__			:		str													=				outputs.to_tuple()

          # create hypothetical next token and extent to next_input_ids
          UpperCAmelCase__			:		List[str]													=				ids_tensor((self.batch_size, 3)						,						config.vocab_size )
          UpperCAmelCase__			:		List[Any]													=				tf.cast(ids_tensor((self.batch_size, 3)						,						2 )						,						tf.inta )

          # append to next input_ids and
          UpperCAmelCase__			:		Optional[Any]													=				tf.concat([input_ids, next_tokens]						,						axis=-1 )
          UpperCAmelCase__			:		Optional[int]													=				tf.concat([attention_mask, next_attn_mask]						,						axis=-1 )

          UpperCAmelCase__			:		Optional[int]													=				model(_A						,						attention_mask=_A )[0]
          UpperCAmelCase__			:		Any													=				model(_A						,						attention_mask=_A						,						past_key_values=_A )[0]

          self.parent.assertEqual(next_tokens.shape[1]						,						output_from_past.shape[1] )

          # select random slice
          UpperCAmelCase__			:		Tuple													=				int(ids_tensor((1,)						,						output_from_past.shape[-1] ) )
          UpperCAmelCase__			:		Any													=				output_from_no_past[:, -3:, random_slice_idx]
          UpperCAmelCase__			:		List[str]													=				output_from_past[:, :, random_slice_idx]

          # test that outputs are equal for slice
          tf.debugging.assert_near(_A						,						_A						,						rtol=1e-3 )





def 					a__       (					lowerCAmelCase__  ,					lowerCAmelCase__  ,					lowerCAmelCase__  ,					lowerCAmelCase__=None  ,					lowerCAmelCase__=None  ,					lowerCAmelCase__=None  ,					lowerCAmelCase__=None  ,					lowerCAmelCase__=None  ,					)    ->	int:
    if attention_mask is None:
        UpperCAmelCase__			:		str													=				tf.cast(tf.math.not_equal(__lowerCamelCase  ,					config.pad_token_id						)  ,					tf.inta						)
    if decoder_attention_mask is None:
        UpperCAmelCase__			:		Dict													=				tf.concat(
            [
                tf.ones(decoder_input_ids[:, :1].shape  ,					dtype=tf.inta						),
                tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:]  ,					config.pad_token_id						)  ,					tf.inta						),
            ]  ,					axis=-1  ,					)
    if head_mask is None:
        UpperCAmelCase__			:		str													=				tf.ones((config.encoder_layers, config.encoder_attention_heads)						)
    if decoder_head_mask is None:
        UpperCAmelCase__			:		Any													=				tf.ones((config.decoder_layers, config.decoder_attention_heads)						)
    if cross_attn_head_mask is None:
        UpperCAmelCase__			:		Tuple													=				tf.ones((config.decoder_layers, config.decoder_attention_heads)						)
    return {
        "input_ids": input_ids,
        "decoder_input_ids": decoder_input_ids,
        "attention_mask": attention_mask,
        "decoder_attention_mask": decoder_attention_mask,
        "head_mask": head_mask,
        "decoder_head_mask": decoder_head_mask,
        "cross_attn_head_mask": cross_attn_head_mask,
    }




@require_tf
class 			lowerCamelCase_   (	snake_case_     ,       snake_case_     ,       unittest.TestCase      ):
      lowerCAmelCase__		     =     (TFPegasusForConditionalGeneration, TFPegasusModel) if is_tf_available() else ()
      lowerCAmelCase__		     =     (TFPegasusForConditionalGeneration,) if is_tf_available() else ()
      lowerCAmelCase__		     =     (
          {
              'conversational': TFPegasusForConditionalGeneration,
              'feature-extraction': TFPegasusModel,
              'summarization': TFPegasusForConditionalGeneration,
              'text2text-generation': TFPegasusForConditionalGeneration,
              'translation': TFPegasusForConditionalGeneration,
          }
          if is_tf_available()
          else {}
      )
      lowerCAmelCase__		     =     True
      lowerCAmelCase__		     =     False
      lowerCAmelCase__		     =     False






      def lowercase_							(					self				:    str ):


          '''simple docstring'''


          UpperCAmelCase__			:		List[str]													=				TFPegasusModelTester(self )
          UpperCAmelCase__			:		int													=				ConfigTester(self						,						config_class=_A )






      def lowercase_							(					self				:    int ):


          '''simple docstring'''


          self.config_tester.run_common_tests()






      def lowercase_							(					self				:    Dict ):


          '''simple docstring'''


          UpperCAmelCase__			:		Union[str, Any]													=				self.model_tester.prepare_config_and_inputs_for_common()
          self.model_tester.check_decoder_model_past_large_inputs(*_A )




@require_sentencepiece
@require_tokenizers
@require_tf
class 			lowerCamelCase_   (	unittest.TestCase      ):
      lowerCAmelCase__		     =     [
          ' PG&E stated it scheduled the blackouts in response to forecasts for high winds amid dry conditions. The aim is to reduce the risk of wildfires. Nearly 800 thousand customers were scheduled to be affected by the shutoffs which were expected to last through at least midday tomorrow.',
          ' The London trio are up for best UK act and best album, as well as getting two nominations in the best song category."We got told like this morning \'Oh I think you\'re nominated\'", said Dappy."And I was like \'Oh yeah, which one?\' And now we\'ve got nominated for four awards. I mean, wow!"Bandmate Fazer added: "We thought it\'s best of us to come down and mingle with everyone and say hello to the cameras. And now we find we\'ve got four nominations."The band have two shots at the best song prize, getting the nod for their Tynchy Stryder collaboration Number One, and single Strong Again.Their album Uncle B will also go up against records by the likes of Beyonce and Kanye West.N-Dubz picked up the best newcomer Mobo in 2007, but female member Tulisa said they wouldn\'t be too disappointed if they didn\'t win this time around."At the end of the day we\'re grateful to be where we are in our careers."If it don\'t happen then it don\'t happen - live to fight another day and keep on making albums and hits for the fans."Dappy also revealed they could be performing live several times on the night.The group will be doing Number One and also a possible rendition of the War Child single, I Got Soul.The charity song is a  re-working of The Killers\' All These Things That I\'ve Done and is set to feature artists like Chipmunk, Ironik and Pixie Lott.This year\'s Mobos will be held outside of London for the first time, in Glasgow on 30 September.N-Dubz said they were looking forward to performing for their Scottish fans and boasted about their recent shows north of the border."We just done Edinburgh the other day," said Dappy."We smashed up an N-Dubz show over there. We done Aberdeen about three or four months ago - we smashed up that show over there! Everywhere we go we smash it up!" ',
      ]
      lowerCAmelCase__		     =     [
          'California\'s largest electricity provider has cut power to hundreds of thousands of customers in an effort to'
          ' reduce the risk of wildfires.',
          'N-Dubz have revealed they\'re "grateful" to have been nominated for four Mobo Awards.',
      ]  # differs slightly from pytorch, likely due to numerical differences in linear layers
      lowerCAmelCase__		     =     'google/pegasus-xsum'






      @cached_property
      def lowercase_							(					self				:    List[str] ):


          '''simple docstring'''


          return AutoTokenizer.from_pretrained(self.model_name )






      @cached_property
      def lowercase_							(					self				:    str ):


          '''simple docstring'''


          UpperCAmelCase__			:		Union[str, Any]													=				TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name )
          return model






      def lowercase_							(					self				:    Optional[Any]						,						**_A				:    str ):


          '''simple docstring'''


          UpperCAmelCase__			:		int													=				self.translate_src_text(**_A )
          assert self.expected_text == generated_words






      def lowercase_							(					self				:    Dict						,						**_A				:    Dict ):


          '''simple docstring'''


          UpperCAmelCase__			:		List[str]													=				self.tokenizer(self.src_text						,						**_A						,						padding=_A						,						return_tensors='''tf''' )
          UpperCAmelCase__			:		str													=				self.model.generate(
              model_inputs.input_ids						,						attention_mask=model_inputs.attention_mask						,						num_beams=2						,						use_cache=_A						,						)
          UpperCAmelCase__			:		str													=				self.tokenizer.batch_decode(generated_ids.numpy()						,						skip_special_tokens=_A )
          return generated_words






      @slow
      def lowercase_							(					self				:    str ):


          '''simple docstring'''


          self._assert_generated_batch_equal_expected()







'''simple docstring'''

from typing import List, Optional, Union

import torch

from ...models import UNetaDConditionModel, VQModel
from ...pipelines import DiffusionPipeline
from ...pipelines.pipeline_utils import ImagePipelineOutput
from ...schedulers import DDPMScheduler
from ...utils import (
    is_accelerate_available,
    is_accelerate_version,
    logging,
    randn_tensor,
    replace_example_docstring,
)


lowercase_					= logging.get_logger(__name__)  # pylint: disable=invalid-name

lowercase_					= """
    Examples:
        ```py
        >>> from diffusers import KandinskyV22Pipeline, KandinskyV22PriorPipeline
        >>> import torch

        >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained(\"kandinsky-community/kandinsky-2-2-prior\")
        >>> pipe_prior.to(\"cuda\")
        >>> prompt = \"red cat, 4k photo\"
        >>> out = pipe_prior(prompt)
        >>> image_emb = out.image_embeds
        >>> zero_image_emb = out.negative_image_embeds
        >>> pipe = KandinskyV22Pipeline.from_pretrained(\"kandinsky-community/kandinsky-2-2-decoder\")
        >>> pipe.to(\"cuda\")
        >>> image = pipe(
        ...     image_embeds=image_emb,
        ...     negative_image_embeds=zero_image_emb,
        ...     height=768,
        ...     width=768,
        ...     num_inference_steps=50,
        ... ).images
        >>> image[0].save(\"cat.png\")
        ```
"""





def lowerCamelCase						(     __lowerCamelCase :    str					,       __lowerCamelCase :    Optional[Any]					,       __lowerCamelCase :    List[Any]=8    )						->Tuple:
    _SCREAMING_SNAKE_CASE									=			height // scale_factor**2
    if height % scale_factor**2 != 0:
        new_height += 1
    _SCREAMING_SNAKE_CASE									=			width // scale_factor**2
    if width % scale_factor**2 != 0:
        new_width += 1
    return new_height * scale_factor, new_width * scale_factor






class 					a_     (				snake_case_       ):

    '''simple docstring'''


    def __init__(		self ,		A ,		A ,		A ,		)		->   Union[str, Any]:
        super().__init__()

        self.register_modules(
            unet=A ,		scheduler=A ,		movq=A ,		)
        _SCREAMING_SNAKE_CASE									=			2 ** (len(self.movq.config.block_out_channels       ) - 1)


    def 			snake_case_(		self ,		A ,		A ,		A ,		A ,		A ,		A       )		->   Union[str, Any]:
        if latents is None:
            _SCREAMING_SNAKE_CASE									=			randn_tensor(A ,		generator=A ,		device=A ,		dtype=A       )
        else:
            if latents.shape != shape:
                raise ValueError(f'Unexpected latents shape, got {latents.shape}, expected {shape}'       )
            _SCREAMING_SNAKE_CASE									=			latents.to(A       )

        _SCREAMING_SNAKE_CASE									=			latents * scheduler.init_noise_sigma
        return latents


    def 			snake_case_(		self ,		A=0       )		->   Dict:
        if is_accelerate_available():
            from accelerate import cpu_offload
        else:
            raise ImportError("""Please install accelerate via `pip install accelerate`"""       )

        _SCREAMING_SNAKE_CASE									=			torch.device(f'cuda:{gpu_id}'       )

        _SCREAMING_SNAKE_CASE									=			[
            self.unet,
            self.movq,
        ]
        for cpu_offloaded_model in models:
            if cpu_offloaded_model is not None:
                cpu_offload(A ,		A       )


    def 			snake_case_(		self ,		A=0       )		->   str:
        if is_accelerate_available() and is_accelerate_version(""">=""" ,		"""0.17.0.dev0"""       ):
            from accelerate import cpu_offload_with_hook
        else:
            raise ImportError("""`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher."""       )

        _SCREAMING_SNAKE_CASE									=			torch.device(f'cuda:{gpu_id}'       )

        if self.device.type != "cpu":
            self.to("""cpu""" ,		silence_dtype_warnings=A       )
            torch.cuda.empty_cache()  # otherwise we don't see the memory savings (but they probably exist)

        _SCREAMING_SNAKE_CASE									=			None
        for cpu_offloaded_model in [self.unet, self.movq]:
            _SCREAMING_SNAKE_CASE				,       _SCREAMING_SNAKE_CASE									=			cpu_offload_with_hook(A ,		A ,		prev_module_hook=A       )

        # We'll offload the last model manually.
        _SCREAMING_SNAKE_CASE									=			hook


    @property
    # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device
    def 			snake_case_(		self       )		->   Tuple:
        if not hasattr(self.unet ,		"""_hf_hook"""       ):
            return self.device
        for module in self.unet.modules():
            if (
                hasattr(A ,		"""_hf_hook"""       )
                and hasattr(module._hf_hook ,		"""execution_device"""       )
                and module._hf_hook.execution_device is not None
            ):
                return torch.device(module._hf_hook.execution_device       )
        return self.device





    @torch.no_grad()
    @replace_example_docstring(A       )
    def __call__(		self ,		A ,		A ,		A = 512 ,		A = 512 ,		A = 100 ,		A = 4.0 ,		A = 1 ,		A = None ,		A = None ,		A = "pil" ,		A = True ,		)		->   List[str]:
        _SCREAMING_SNAKE_CASE									=			self._execution_device

        _SCREAMING_SNAKE_CASE									=			guidance_scale > 1.0

        if isinstance(A ,		A       ):
            _SCREAMING_SNAKE_CASE									=			torch.cat(A ,		dim=0       )
        _SCREAMING_SNAKE_CASE									=			image_embeds.shape[0] * num_images_per_prompt
        if isinstance(A ,		A       ):
            _SCREAMING_SNAKE_CASE									=			torch.cat(A ,		dim=0       )

        if do_classifier_free_guidance:
            _SCREAMING_SNAKE_CASE									=			image_embeds.repeat_interleave(A ,		dim=0       )
            _SCREAMING_SNAKE_CASE									=			negative_image_embeds.repeat_interleave(A ,		dim=0       )

        _SCREAMING_SNAKE_CASE									=			torch.cat([negative_image_embeds, image_embeds] ,		dim=0       ).to(dtype=self.unet.dtype ,		device=A       )

        self.scheduler.set_timesteps(A ,		device=A       )
        _SCREAMING_SNAKE_CASE									=			self.scheduler.timesteps

        _SCREAMING_SNAKE_CASE									=			self.unet.config.in_channels

        _SCREAMING_SNAKE_CASE				,       _SCREAMING_SNAKE_CASE									=			downscale_height_and_width(A ,		A ,		self.movq_scale_factor       )

        # create initial latent
        _SCREAMING_SNAKE_CASE									=			self.prepare_latents(
            (batch_size, num_channels_latents, height, width) ,		image_embeds.dtype ,		A ,		A ,		A ,		self.scheduler ,		)

        for i, t in enumerate(self.progress_bar(A       )       ):
            # expand the latents if we are doing classifier free guidance
            _SCREAMING_SNAKE_CASE									=			torch.cat([latents] * 2       ) if do_classifier_free_guidance else latents

            _SCREAMING_SNAKE_CASE									=			{"""image_embeds""": image_embeds}
            _SCREAMING_SNAKE_CASE									=			self.unet(
                sample=A ,		timestep=A ,		encoder_hidden_states=A ,		added_cond_kwargs=A ,		return_dict=A ,		)[0]

            if do_classifier_free_guidance:
                _SCREAMING_SNAKE_CASE				,       _SCREAMING_SNAKE_CASE									=			noise_pred.split(latents.shape[1] ,		dim=1       )
                _SCREAMING_SNAKE_CASE				,       _SCREAMING_SNAKE_CASE									=			noise_pred.chunk(2       )
                _SCREAMING_SNAKE_CASE				,       _SCREAMING_SNAKE_CASE									=			variance_pred.chunk(2       )
                _SCREAMING_SNAKE_CASE									=			noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
                _SCREAMING_SNAKE_CASE									=			torch.cat([noise_pred, variance_pred_text] ,		dim=1       )

            if not (
                hasattr(self.scheduler.config ,		"""variance_type"""       )
                and self.scheduler.config.variance_type in ["learned", "learned_range"]
            ):
                _SCREAMING_SNAKE_CASE				,       _SCREAMING_SNAKE_CASE									=			noise_pred.split(latents.shape[1] ,		dim=1       )

            # compute the previous noisy sample x_t -> x_t-1
            _SCREAMING_SNAKE_CASE									=			self.scheduler.step(
                A ,		A ,		A ,		generator=A ,		)[0]
        # post-processing
        _SCREAMING_SNAKE_CASE									=			self.movq.decode(A ,		force_not_quantize=A       )["""sample"""]

        if output_type not in ["pt", "np", "pil"]:
            raise ValueError(f'Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}'       )

        if output_type in ["np", "pil"]:
            _SCREAMING_SNAKE_CASE									=			image * 0.5 + 0.5
            _SCREAMING_SNAKE_CASE									=			image.clamp(0 ,		1       )
            _SCREAMING_SNAKE_CASE									=			image.cpu().permute(0 ,		2 ,		3 ,		1       ).float().numpy()

        if output_type == "pil":
            _SCREAMING_SNAKE_CASE									=			self.numpy_to_pil(A       )

        if not return_dict:
            return (image,)

        return ImagePipelineOutput(images=A       )



