



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						,				_snake_case						,				_snake_case=13						,				_snake_case=7						,				_snake_case=True						,				_snake_case=False						,				_snake_case=99						,				_snake_case=32						,				_snake_case=2						,				_snake_case=4						,				_snake_case=37						,				_snake_case=0.1						,				_snake_case=0.1						,				_snake_case=40						,				_snake_case=2						,				_snake_case=1						,				_snake_case=0						,				):



									"""simple docstring"""





									_lowerCAmelCase						=    parent
									_lowerCAmelCase						=    batch_size
									_lowerCAmelCase						=    seq_length
									_lowerCAmelCase						=    is_training
									_lowerCAmelCase						=    use_labels
									_lowerCAmelCase						=    vocab_size
									_lowerCAmelCase						=    hidden_size
									_lowerCAmelCase						=    num_hidden_layers
									_lowerCAmelCase						=    num_attention_heads
									_lowerCAmelCase						=    intermediate_size

									_lowerCAmelCase						=    hidden_dropout_prob
									_lowerCAmelCase						=    attention_probs_dropout_prob
									_lowerCAmelCase						=    max_position_embeddings
									_lowerCAmelCase						=    eos_token_id
									_lowerCAmelCase						=    pad_token_id
									_lowerCAmelCase						=    bos_token_id




				def 							snake_case   (							self		):



									"""simple docstring"""





									_lowerCAmelCase						=    ids_tensor([self.batch_size, self.seq_length - 1]						,				self.vocab_size		)
									_lowerCAmelCase						=    tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size		)						,				1		)
									_lowerCAmelCase						=    tf.concat([input_ids, eos_tensor]						,				axis=1		)

									_lowerCAmelCase						=    ids_tensor([self.batch_size, self.seq_length]						,				self.vocab_size		)

									_lowerCAmelCase						=    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						,				)
									_lowerCAmelCase						=    prepare_pegasus_inputs_dict(_snake_case						,				_snake_case						,				_snake_case		)
									return config, inputs_dict




				def 							snake_case   (							self						,				_snake_case						,				_snake_case		):



									"""simple docstring"""





									_lowerCAmelCase						=    TFPegasusModel(config=_snake_case		).get_decoder()
									_lowerCAmelCase						=    inputs_dict["""input_ids"""]

									_lowerCAmelCase						=    input_ids[:1, :]
									_lowerCAmelCase						=    inputs_dict["""attention_mask"""][:1, :]
									_lowerCAmelCase						=    inputs_dict["""head_mask"""]
									_lowerCAmelCase						=    1

									# first forward pass
									_lowerCAmelCase						=    model(_snake_case						,				attention_mask=_snake_case						,				head_mask=_snake_case						,				use_cache=_snake_case		)

									_lowerCAmelCase	,	_lowerCAmelCase						=    outputs.to_tuple()

									# create hypothetical next token and extent to next_input_ids
									_lowerCAmelCase						=    ids_tensor((self.batch_size, 3)						,				config.vocab_size		)
									_lowerCAmelCase						=    tf.cast(ids_tensor((self.batch_size, 3)						,				2		)						,				tf.inta		)

									# append to next input_ids and
									_lowerCAmelCase						=    tf.concat([input_ids, next_tokens]						,				axis=-1		)
									_lowerCAmelCase						=    tf.concat([attention_mask, next_attn_mask]						,				axis=-1		)

									_lowerCAmelCase						=    model(_snake_case						,				attention_mask=_snake_case		)[0]
									_lowerCAmelCase						=    model(_snake_case						,				attention_mask=_snake_case						,				past_key_values=_snake_case		)[0]

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

									# select random slice
									_lowerCAmelCase						=    int(ids_tensor((1,)						,				output_from_past.shape[-1]		)		)
									_lowerCAmelCase						=    output_from_no_past[:, -3:, random_slice_idx]
									_lowerCAmelCase						=    output_from_past[:, :, random_slice_idx]

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


def 		_UpperCAmelCase				(      snake_case	,						snake_case	,						snake_case	,						snake_case=None	,						snake_case=None	,						snake_case=None	,						snake_case=None	,						snake_case=None	,						):





					"""simple docstring"""

					if attention_mask is None:
										_lowerCAmelCase						=    tf.cast(tf.math.not_equal(snake_case	,						config.pad_token_id			)	,						tf.inta			)
					if decoder_attention_mask is None:
										_lowerCAmelCase						=    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:
										_lowerCAmelCase						=    tf.ones((config.encoder_layers, config.encoder_attention_heads)			)
					if decoder_head_mask is None:
										_lowerCAmelCase						=    tf.ones((config.decoder_layers, config.decoder_attention_heads)			)
					if cross_attn_head_mask is None:
										_lowerCAmelCase						=    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 (     lowerCamelCase__       ,						lowerCamelCase__       ,						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 							snake_case   (							self		):



									"""simple docstring"""





									_lowerCAmelCase						=    TFPegasusModelTester(self		)
									_lowerCAmelCase						=    ConfigTester(self						,				config_class=_snake_case		)




				def 							snake_case   (							self		):



									"""simple docstring"""





									self.config_tester.run_common_tests()




				def 							snake_case   (							self		):



									"""simple docstring"""





									_lowerCAmelCase						=    self.model_tester.prepare_config_and_inputs_for_common()
									self.model_tester.check_decoder_model_past_large_inputs(*_snake_case		)





@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 							snake_case   (							self		):



									"""simple docstring"""





									return AutoTokenizer.from_pretrained(self.model_name		)




				@cached_property
				def 							snake_case   (							self		):



									"""simple docstring"""





									_lowerCAmelCase						=    TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name		)
									return model




				def 							snake_case   (							self						,				**_snake_case		):



									"""simple docstring"""





									_lowerCAmelCase						=    self.translate_src_text(**_snake_case		)
									assert self.expected_text == generated_words




				def 							snake_case   (							self						,				**_snake_case		):



									"""simple docstring"""





									_lowerCAmelCase						=    self.tokenizer(self.src_text						,				**_snake_case						,				padding=_snake_case						,				return_tensors="""tf"""		)
									_lowerCAmelCase						=    self.model.generate(
									    model_inputs.input_ids						,				attention_mask=model_inputs.attention_mask						,				num_beams=2						,				use_cache=_snake_case						,				)
									_lowerCAmelCase						=    self.tokenizer.batch_decode(generated_ids.numpy()						,				skip_special_tokens=_snake_case		)
									return generated_words




				@slow
				def 							snake_case   (							self		):



									"""simple docstring"""





									self._assert_generated_batch_equal_expected()











import gc
import unittest

import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer

from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEPipeline
from diffusers.pipelines.shap_e import ShapERenderer
from diffusers.utils import load_numpy, slow
from diffusers.utils.testing_utils import require_torch_gpu, torch_device

from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference






class 		lowercase_					(	lowercase ,  unittest.TestCase   ):






      '''simple docstring'''




      __snake_case       =  ShapEPipeline
      __snake_case       =  ['''prompt''']
      __snake_case       =  ['''prompt''']
      __snake_case       =  [
          '''num_images_per_prompt''',
          '''num_inference_steps''',
          '''generator''',
          '''latents''',
          '''guidance_scale''',
          '''frame_size''',
          '''output_type''',
          '''return_dict''',
      ]
      __snake_case       =  False







      @property
      def       __lowerCAmelCase					(      self      :						Union[str, Any]  )    ->Union[str, Any]:




       """simple docstring"""


       return 32







      @property
      def       __lowerCAmelCase					(      self      :						Optional[Any]  )    ->List[str]:




       """simple docstring"""


       return 32







      @property
      def       __lowerCAmelCase					(      self      :						Any  )    ->Tuple:




       """simple docstring"""


       return self.time_input_dim * 4







      @property
      def       __lowerCAmelCase					(      self      :						Tuple  )    ->Optional[Any]:




       """simple docstring"""


       return 8







      @property
      def       __lowerCAmelCase					(      self      :						Tuple  )    ->str:




       """simple docstring"""


       a		  =      CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''  )
       return tokenizer







      @property
      def       __lowerCAmelCase					(      self      :						Union[str, Any]  )    ->List[Any]:




       """simple docstring"""


       torch.manual_seed(0  )
       a		  =      CLIPTextConfig(
           bos_token_id=0 ,					eos_token_id=2 ,					hidden_size=self.text_embedder_hidden_size ,					projection_dim=self.text_embedder_hidden_size ,					intermediate_size=37 ,					layer_norm_eps=1e-0_5 ,					num_attention_heads=4 ,					num_hidden_layers=5 ,					pad_token_id=1 ,					vocab_size=1_000 ,					)
       return CLIPTextModelWithProjection(__UpperCAmelCase  )







      @property
      def       __lowerCAmelCase					(      self      :						Dict  )    ->Union[str, Any]:




       """simple docstring"""


       torch.manual_seed(0  )

       a		  =      {
           '''num_attention_heads''': 2,
           '''attention_head_dim''': 16,
           '''embedding_dim''': self.time_input_dim,
           '''num_embeddings''': 32,
           '''embedding_proj_dim''': self.text_embedder_hidden_size,
           '''time_embed_dim''': self.time_embed_dim,
           '''num_layers''': 1,
           '''clip_embed_dim''': self.time_input_dim * 2,
           '''additional_embeddings''': 0,
           '''time_embed_act_fn''': '''gelu''',
           '''norm_in_type''': '''layer''',
           '''encoder_hid_proj_type''': None,
           '''added_emb_type''': None,
       }

       a		  =      PriorTransformer(**__UpperCAmelCase  )
       return model







      @property
      def       __lowerCAmelCase					(      self      :						List[Any]  )    ->List[str]:




       """simple docstring"""


       torch.manual_seed(0  )

       a		  =      {
           '''param_shapes''': (
               (self.renderer_dim, 93),
               (self.renderer_dim, 8),
               (self.renderer_dim, 8),
               (self.renderer_dim, 8),
           ),
           '''d_latent''': self.time_input_dim,
           '''d_hidden''': self.renderer_dim,
           '''n_output''': 12,
           '''background''': (
               0.1,
               0.1,
               0.1,
           ),
       }
       a		  =      ShapERenderer(**__UpperCAmelCase  )
       return model







      def       __lowerCAmelCase					(      self      :						List[Any]  )    ->Any:




       """simple docstring"""


       a		  =      self.dummy_prior
       a		  =      self.dummy_text_encoder
       a		  =      self.dummy_tokenizer
       a		  =      self.dummy_renderer

       a		  =      HeunDiscreteScheduler(
           beta_schedule='''exp''' ,					num_train_timesteps=1_024 ,					prediction_type='''sample''' ,					use_karras_sigmas=__UpperCAmelCase ,					clip_sample=__UpperCAmelCase ,					clip_sample_range=1.0 ,					)
       a		  =      {
           '''prior''': prior,
           '''text_encoder''': text_encoder,
           '''tokenizer''': tokenizer,
           '''renderer''': renderer,
           '''scheduler''': scheduler,
       }

       return components







      def       __lowerCAmelCase					(      self      :						Tuple ,					__UpperCAmelCase      :						Optional[Any] ,					__UpperCAmelCase      :						str=0  )    ->Optional[int]:




       """simple docstring"""


       if str(__UpperCAmelCase  ).startswith('''mps'''  ):
        a		  =      torch.manual_seed(__UpperCAmelCase  )
       else:
        a		  =      torch.Generator(device=__UpperCAmelCase  ).manual_seed(__UpperCAmelCase  )
       a		  =      {
           '''prompt''': '''horse''',
           '''generator''': generator,
           '''num_inference_steps''': 1,
           '''frame_size''': 32,
           '''output_type''': '''np''',
       }
       return inputs







      def       __lowerCAmelCase					(      self      :						Dict  )    ->Optional[int]:




       """simple docstring"""


       a		  =      '''cpu'''

       a		  =      self.get_dummy_components()

       a		  =      self.pipeline_class(**__UpperCAmelCase  )
       a		  =      pipe.to(__UpperCAmelCase  )

       pipe.set_progress_bar_config(disable=__UpperCAmelCase  )

       a		  =      pipe(**self.get_dummy_inputs(__UpperCAmelCase  )  )
       a		  =      output.images[0]
       a		  =      image[0, -3:, -3:, -1]

       assert image.shape == (20, 32, 32, 3)

       a		  =      np.array(
           [
               0.00039216,
               0.00039216,
               0.00039216,
               0.00039216,
               0.00039216,
               0.00039216,
               0.00039216,
               0.00039216,
               0.00039216,
           ]  )

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







      def       __lowerCAmelCase					(      self      :						Dict  )    ->Optional[Any]:




       """simple docstring"""


       self._test_inference_batch_consistent(batch_sizes=[1, 2]  )







      def       __lowerCAmelCase					(      self      :						Optional[Any]  )    ->Tuple:




       """simple docstring"""


       a		  =      torch_device == '''cpu'''
       a		  =      True

       self._test_inference_batch_single_identical(
           batch_size=2 ,					test_max_difference=__UpperCAmelCase ,					relax_max_difference=__UpperCAmelCase ,					)







      def       __lowerCAmelCase					(      self      :						str  )    ->Optional[int]:




       """simple docstring"""


       a		  =      self.get_dummy_components()
       a		  =      self.pipeline_class(**__UpperCAmelCase  )
       a		  =      pipe.to(__UpperCAmelCase  )
       pipe.set_progress_bar_config(disable=__UpperCAmelCase  )

       a		  =      1
       a		  =      2

       a		  =      self.get_dummy_inputs(__UpperCAmelCase  )

       for key in inputs.keys():
        if key in self.batch_params:
         a		  =      batch_size * [inputs[key]]

       a		  =      pipe(**__UpperCAmelCase ,					num_images_per_prompt=__UpperCAmelCase  )[0]

       assert images.shape[0] == batch_size * num_images_per_prompt






@slow
@require_torch_gpu
class 		lowercase_					(	unittest.TestCase   ):






      '''simple docstring'''




      def       __lowerCAmelCase					(      self      :						int  )    ->Any:




       """simple docstring"""


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







      def       __lowerCAmelCase					(      self      :						List[Any]  )    ->Union[str, Any]:




       """simple docstring"""


       a		  =      load_numpy(
           '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
           '''/shap_e/test_shap_e_np_out.npy'''  )
       a		  =      ShapEPipeline.from_pretrained('''openai/shap-e'''  )
       a		  =      pipe.to(__UpperCAmelCase  )
       pipe.set_progress_bar_config(disable=__UpperCAmelCase  )

       a		  =      torch.Generator(device=__UpperCAmelCase  ).manual_seed(0  )

       a		  =      pipe(
           '''a shark''' ,					generator=__UpperCAmelCase ,					guidance_scale=15.0 ,					num_inference_steps=64 ,					frame_size=64 ,					output_type='''np''' ,					).images[0]

       assert images.shape == (20, 64, 64, 3)

       assert_mean_pixel_difference(__UpperCAmelCase ,					__UpperCAmelCase  )


