

import gc
import random
import tempfile
import unittest

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

from diffusers import AutoencoderKL, DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel
from diffusers.pipelines.stable_diffusion_safe import StableDiffusionPipelineSafe as StableDiffusionPipeline
from diffusers.utils import floats_tensor, nightly, torch_device
from diffusers.utils.testing_utils import require_torch_gpu



class SCREAMING_SNAKE_CASE     (  unittest.TestCase			):
  """simple docstring"""






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






     """simple docstring"""







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







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






     """simple docstring"""







     __lowerCAmelCase  :      str    =						1
     __lowerCAmelCase  :      int    =						3
     __lowerCAmelCase  :      int    =						(32, 32)

     __lowerCAmelCase  :      str    =						floats_tensor((batch_size, num_channels) + sizes	,							rng=random.Random(0   )   ).to(_a   )
     return image







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






     """simple docstring"""







     torch.manual_seed(0   )
     __lowerCAmelCase  :      Any    =						UNetaDConditionModel(
         block_out_channels=(32, 64)	,							layers_per_block=2	,							sample_size=32	,							in_channels=4	,							out_channels=4	,							down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""")	,							up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""")	,							cross_attention_dim=32	,							)
     return model







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






     """simple docstring"""







     torch.manual_seed(0   )
     __lowerCAmelCase  :      Any    =						AutoencoderKL(
         block_out_channels=[32, 64]	,							in_channels=3	,							out_channels=3	,							down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""]	,							up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""]	,							latent_channels=4	,							)
     return model







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






     """simple docstring"""







     torch.manual_seed(0   )
     __lowerCAmelCase  :      int    =						CLIPTextConfig(
         bos_token_id=0	,							eos_token_id=2	,							hidden_size=32	,							intermediate_size=37	,							layer_norm_eps=1e-05	,							num_attention_heads=4	,							num_hidden_layers=5	,							pad_token_id=1	,							vocab_size=10_00	,							)
     return CLIPTextModel(_a   )







  @property
  def 	SCREAMING_SNAKE_CASE   (      self			:   str   )							->     Optional[int]:






     """simple docstring"""







     def extract(*lowerCAmelCase			:   Union[str, Any]	,							**lowerCAmelCase			:   Union[str, Any]   ):



        class SCREAMING_SNAKE_CASE     :
          """simple docstring"""






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






             """simple docstring"""







             __lowerCAmelCase  :      Union[str, Any]    =						torch.ones([0]   )







          def 	SCREAMING_SNAKE_CASE   (      self			:   List[Any]	,							lowerCAmelCase			:   Optional[Any]   )							->     Any:






             """simple docstring"""







             self.pixel_values.to(_a   )
             return self






        return Out()

     return extract







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






     """simple docstring"""







     __lowerCAmelCase  :      Any    =						'''cpu'''  # ensure determinism for the device-dependent torch.Generator
     __lowerCAmelCase  :      int    =						self.dummy_cond_unet
     __lowerCAmelCase  :      int    =						DDIMScheduler(
         beta_start=0.0_0085	,							beta_end=0.012	,							beta_schedule="""scaled_linear"""	,							clip_sample=_a	,							set_alpha_to_one=_a	,							)

     __lowerCAmelCase  :      List[Any]    =						self.dummy_vae
     __lowerCAmelCase  :      Dict    =						self.dummy_text_encoder
     __lowerCAmelCase  :      List[str]    =						CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""   )

     # make sure here that pndm scheduler skips prk
     __lowerCAmelCase  :      Tuple    =						StableDiffusionPipeline(
         unet=_a	,							scheduler=_a	,							vae=_a	,							text_encoder=_a	,							tokenizer=_a	,							safety_checker=_a	,							feature_extractor=self.dummy_extractor	,							)
     __lowerCAmelCase  :      List[Any]    =						sd_pipe.to(_a   )
     sd_pipe.set_progress_bar_config(disable=_a   )

     __lowerCAmelCase  :      Optional[int]    =						'''A painting of a squirrel eating a burger'''

     __lowerCAmelCase  :      Union[str, Any]    =						torch.Generator(device=_a   ).manual_seed(0   )
     __lowerCAmelCase  :      Dict    =						sd_pipe([prompt]	,							generator=_a	,							guidance_scale=6.0	,							num_inference_steps=2	,							output_type="""np"""   )
     __lowerCAmelCase  :      Union[str, Any]    =						output.images

     __lowerCAmelCase  :      Optional[int]    =						torch.Generator(device=_a   ).manual_seed(0   )
     __lowerCAmelCase  :      int    =						sd_pipe(
         [prompt]	,							generator=_a	,							guidance_scale=6.0	,							num_inference_steps=2	,							output_type="""np"""	,							return_dict=_a	,							)[0]

     __lowerCAmelCase  :      Dict    =						image[0, -3:, -3:, -1]
     __lowerCAmelCase  :      Optional[int]    =						image_from_tuple[0, -3:, -3:, -1]

     assert image.shape == (1, 64, 64, 3)
     __lowerCAmelCase  :      Union[str, Any]    =						np.array([0.5756, 0.6118, 0.5005, 0.5041, 0.5471, 0.4726, 0.4976, 0.4865, 0.4864]   )

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







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






     """simple docstring"""







     __lowerCAmelCase  :      Dict    =						'''cpu'''  # ensure determinism for the device-dependent torch.Generator
     __lowerCAmelCase  :      int    =						self.dummy_cond_unet
     __lowerCAmelCase  :      int    =						PNDMScheduler(skip_prk_steps=_a   )
     __lowerCAmelCase  :      Dict    =						self.dummy_vae
     __lowerCAmelCase  :      int    =						self.dummy_text_encoder
     __lowerCAmelCase  :      Union[str, Any]    =						CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""   )

     # make sure here that pndm scheduler skips prk
     __lowerCAmelCase  :      Tuple    =						StableDiffusionPipeline(
         unet=_a	,							scheduler=_a	,							vae=_a	,							text_encoder=_a	,							tokenizer=_a	,							safety_checker=_a	,							feature_extractor=self.dummy_extractor	,							)
     __lowerCAmelCase  :      List[Any]    =						sd_pipe.to(_a   )
     sd_pipe.set_progress_bar_config(disable=_a   )

     __lowerCAmelCase  :      Tuple    =						'''A painting of a squirrel eating a burger'''
     __lowerCAmelCase  :      List[Any]    =						torch.Generator(device=_a   ).manual_seed(0   )
     __lowerCAmelCase  :      List[Any]    =						sd_pipe([prompt]	,							generator=_a	,							guidance_scale=6.0	,							num_inference_steps=2	,							output_type="""np"""   )

     __lowerCAmelCase  :      int    =						output.images

     __lowerCAmelCase  :      int    =						torch.Generator(device=_a   ).manual_seed(0   )
     __lowerCAmelCase  :      Optional[Any]    =						sd_pipe(
         [prompt]	,							generator=_a	,							guidance_scale=6.0	,							num_inference_steps=2	,							output_type="""np"""	,							return_dict=_a	,							)[0]

     __lowerCAmelCase  :      Union[str, Any]    =						image[0, -3:, -3:, -1]
     __lowerCAmelCase  :      List[Any]    =						image_from_tuple[0, -3:, -3:, -1]

     assert image.shape == (1, 64, 64, 3)
     __lowerCAmelCase  :      List[str]    =						np.array([0.5125, 0.5716, 0.4828, 0.5060, 0.5650, 0.4768, 0.5185, 0.4895, 0.4993]   )

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







  def 	SCREAMING_SNAKE_CASE   (      self			:   List[str]   )							->     List[str]:






     """simple docstring"""







     __lowerCAmelCase  :      int    =						StableDiffusionPipeline.from_pretrained(
         """hf-internal-testing/tiny-stable-diffusion-lms-pipe"""	,							safety_checker=_a   )
     assert isinstance(_a	,							_a   )
     assert isinstance(pipe.scheduler	,							_a   )
     assert pipe.safety_checker is None

     __lowerCAmelCase  :      Union[str, Any]    =						pipe("""example prompt"""	,							num_inference_steps=2   ).images[0]
     assert image is not None

     # check that there's no error when saving a pipeline with one of the models being None
     with tempfile.TemporaryDirectory() as tmpdirname:
        pipe.save_pretrained(_a   )
        __lowerCAmelCase  :      List[str]    =						StableDiffusionPipeline.from_pretrained(_a   )

     # sanity check that the pipeline still works
     assert pipe.safety_checker is None
     __lowerCAmelCase  :      List[str]    =						pipe("""example prompt"""	,							num_inference_steps=2   ).images[0]
     assert image is not None







  @unittest.skipIf(torch_device != """cuda"""	,							"""This test requires a GPU"""   )
  def 	SCREAMING_SNAKE_CASE   (      self			:   Tuple   )							->     List[str]:






     """simple docstring"""







     __lowerCAmelCase  :      Optional[int]    =						self.dummy_cond_unet
     __lowerCAmelCase  :      Dict    =						PNDMScheduler(skip_prk_steps=_a   )
     __lowerCAmelCase  :      List[Any]    =						self.dummy_vae
     __lowerCAmelCase  :      str    =						self.dummy_text_encoder
     __lowerCAmelCase  :      List[Any]    =						CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""   )

     # put models in fp16
     __lowerCAmelCase  :      Union[str, Any]    =						unet.half()
     __lowerCAmelCase  :      Optional[int]    =						vae.half()
     __lowerCAmelCase  :      Optional[int]    =						bert.half()

     # make sure here that pndm scheduler skips prk
     __lowerCAmelCase  :      List[Any]    =						StableDiffusionPipeline(
         unet=_a	,							scheduler=_a	,							vae=_a	,							text_encoder=_a	,							tokenizer=_a	,							safety_checker=_a	,							feature_extractor=self.dummy_extractor	,							)
     __lowerCAmelCase  :      Union[str, Any]    =						sd_pipe.to(_a   )
     sd_pipe.set_progress_bar_config(disable=_a   )

     __lowerCAmelCase  :      Optional[int]    =						'''A painting of a squirrel eating a burger'''
     __lowerCAmelCase  :      str    =						sd_pipe([prompt]	,							num_inference_steps=2	,							output_type="""np"""   ).images

     assert image.shape == (1, 64, 64, 3)






@nightly
@require_torch_gpu
class SCREAMING_SNAKE_CASE     (  unittest.TestCase			):
  """simple docstring"""






  def 	SCREAMING_SNAKE_CASE   (      self			:   str   )							->     List[str]:






     """simple docstring"""







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







  def 	SCREAMING_SNAKE_CASE   (      self			:   Optional[Any]   )							->     Any:






     """simple docstring"""







     __lowerCAmelCase  :      int    =						StableDiffusionPipeline.from_pretrained("""runwayml/stable-diffusion-v1-5"""	,							safety_checker=_a   )
     __lowerCAmelCase  :      Union[str, Any]    =						LMSDiscreteScheduler.from_config(sd_pipe.scheduler.config   )
     __lowerCAmelCase  :      Union[str, Any]    =						sd_pipe.to(_a   )
     sd_pipe.set_progress_bar_config(disable=_a   )

     __lowerCAmelCase  :      Optional[Any]    =						(
         '''portrait of girl with smokey eyes makeup in abandoned hotel, grange clothes, redshift, wide high angle'''
         ''' coloured polaroid photograph with flash, kodak film, hyper real, stunning moody cinematography, with'''
         ''' anamorphic lenses, by maripol, fallen angels by wong kar - wai, style of suspiria and neon demon and'''
         ''' children from bahnhof zoo, detailed '''
     )
     __lowerCAmelCase  :      Any    =						40_03_66_03_46
     __lowerCAmelCase  :      Tuple    =						7

     # without safety guidance (sld_guidance_scale = 0)
     __lowerCAmelCase  :      Any    =						torch.manual_seed(_a   )
     __lowerCAmelCase  :      Any    =						sd_pipe(
         [prompt]	,							generator=_a	,							guidance_scale=_a	,							num_inference_steps=50	,							output_type="""np"""	,							width=5_12	,							height=5_12	,							sld_guidance_scale=0	,							)

     __lowerCAmelCase  :      Optional[int]    =						output.images
     __lowerCAmelCase  :      Optional[int]    =						image[0, -3:, -3:, -1]
     __lowerCAmelCase  :      List[Any]    =						[0.2278, 0.2231, 0.2249, 0.2333, 0.2303, 0.1885, 0.2273, 0.2144, 0.2176]

     assert image.shape == (1, 5_12, 5_12, 3)

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

     # without safety guidance (strong configuration)
     __lowerCAmelCase  :      List[Any]    =						torch.manual_seed(_a   )
     __lowerCAmelCase  :      List[str]    =						sd_pipe(
         [prompt]	,							generator=_a	,							guidance_scale=_a	,							num_inference_steps=50	,							output_type="""np"""	,							width=5_12	,							height=5_12	,							sld_guidance_scale=20_00	,							sld_warmup_steps=7	,							sld_threshold=0.025	,							sld_momentum_scale=0.5	,							sld_mom_beta=0.7	,							)

     __lowerCAmelCase  :      List[str]    =						output.images
     __lowerCAmelCase  :      Dict    =						image[0, -3:, -3:, -1]
     __lowerCAmelCase  :      Dict    =						[0.2383, 0.2276, 0.236, 0.2192, 0.2186, 0.2053, 0.1971, 0.1901, 0.1719]

     assert image.shape == (1, 5_12, 5_12, 3)

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







  def 	SCREAMING_SNAKE_CASE   (      self			:   List[Any]   )							->     Optional[int]:






     """simple docstring"""







     __lowerCAmelCase  :      Any    =						StableDiffusionPipeline.from_pretrained("""runwayml/stable-diffusion-v1-5"""	,							safety_checker=_a   )
     __lowerCAmelCase  :      List[str]    =						LMSDiscreteScheduler.from_config(sd_pipe.scheduler.config   )
     __lowerCAmelCase  :      Any    =						sd_pipe.to(_a   )
     sd_pipe.set_progress_bar_config(disable=_a   )

     __lowerCAmelCase  :      Tuple    =						'''padme amidala taking a bath artwork, safe for work, no nudity'''
     __lowerCAmelCase  :      Union[str, Any]    =						27_34_97_17_55
     __lowerCAmelCase  :      int    =						7

     __lowerCAmelCase  :      Optional[Any]    =						torch.manual_seed(_a   )
     __lowerCAmelCase  :      str    =						sd_pipe(
         [prompt]	,							generator=_a	,							guidance_scale=_a	,							num_inference_steps=50	,							output_type="""np"""	,							width=5_12	,							height=5_12	,							sld_guidance_scale=0	,							)

     __lowerCAmelCase  :      str    =						output.images
     __lowerCAmelCase  :      Optional[int]    =						image[0, -3:, -3:, -1]
     __lowerCAmelCase  :      List[str]    =						[0.3502, 0.3622, 0.3396, 0.3642, 0.3478, 0.3318, 0.35, 0.3348, 0.3297]

     assert image.shape == (1, 5_12, 5_12, 3)

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

     __lowerCAmelCase  :      Union[str, Any]    =						torch.manual_seed(_a   )
     __lowerCAmelCase  :      Any    =						sd_pipe(
         [prompt]	,							generator=_a	,							guidance_scale=_a	,							num_inference_steps=50	,							output_type="""np"""	,							width=5_12	,							height=5_12	,							sld_guidance_scale=20_00	,							sld_warmup_steps=7	,							sld_threshold=0.025	,							sld_momentum_scale=0.5	,							sld_mom_beta=0.7	,							)

     __lowerCAmelCase  :      List[str]    =						output.images
     __lowerCAmelCase  :      Optional[Any]    =						image[0, -3:, -3:, -1]
     __lowerCAmelCase  :      Optional[int]    =						[0.5531, 0.5206, 0.4895, 0.5156, 0.5182, 0.4751, 0.4802, 0.4803, 0.4443]

     assert image.shape == (1, 5_12, 5_12, 3)

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







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






     """simple docstring"""







     __lowerCAmelCase  :      Union[str, Any]    =						StableDiffusionPipeline.from_pretrained("""runwayml/stable-diffusion-v1-5"""   )
     __lowerCAmelCase  :      Any    =						sd_pipe.to(_a   )
     sd_pipe.set_progress_bar_config(disable=_a   )

     __lowerCAmelCase  :      Tuple    =						(
         '''the four horsewomen of the apocalypse, painting by tom of finland, gaston bussiere, craig mullins, j. c.'''
         ''' leyendecker'''
     )
     __lowerCAmelCase  :      Optional[Any]    =						10_44_35_52_34
     __lowerCAmelCase  :      Any    =						12

     __lowerCAmelCase  :      int    =						torch.manual_seed(_a   )
     __lowerCAmelCase  :      List[Any]    =						sd_pipe(
         [prompt]	,							generator=_a	,							guidance_scale=_a	,							num_inference_steps=50	,							output_type="""np"""	,							width=5_12	,							height=5_12	,							sld_guidance_scale=0	,							)

     __lowerCAmelCase  :      str    =						output.images
     __lowerCAmelCase  :      str    =						image[0, -3:, -3:, -1]
     __lowerCAmelCase  :      Optional[Any]    =						np.array([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]   )

     assert image.shape == (1, 5_12, 5_12, 3)

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

     __lowerCAmelCase  :      Union[str, Any]    =						torch.manual_seed(_a   )
     __lowerCAmelCase  :      Tuple    =						sd_pipe(
         [prompt]	,							generator=_a	,							guidance_scale=_a	,							num_inference_steps=50	,							output_type="""np"""	,							width=5_12	,							height=5_12	,							sld_guidance_scale=20_00	,							sld_warmup_steps=7	,							sld_threshold=0.025	,							sld_momentum_scale=0.5	,							sld_mom_beta=0.7	,							)

     __lowerCAmelCase  :      Any    =						output.images
     __lowerCAmelCase  :      Dict    =						image[0, -3:, -3:, -1]
     __lowerCAmelCase  :      Any    =						np.array([0.5818, 0.6285, 0.6835, 0.6019, 0.625, 0.6754, 0.6096, 0.6334, 0.6561]   )
     assert image.shape == (1, 5_12, 5_12, 3)

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





from __future__ import annotations

import unittest

from transformers import AutoTokenizer, MBartConfig, 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, TFMBartForConditionalGeneration, TFMBartModel



@require_tf
class SCREAMING_SNAKE_CASE     :
  """simple docstring"""






  lowerCamelCase   :      Union[str, Any]										=MBartConfig
  lowerCamelCase   :      Optional[Any]										={}
  lowerCamelCase   :      Dict										="gelu"







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






     """simple docstring"""







     __lowerCAmelCase  :      str    =						parent
     __lowerCAmelCase  :      int    =						batch_size
     __lowerCAmelCase  :      int    =						seq_length
     __lowerCAmelCase  :      Tuple    =						is_training
     __lowerCAmelCase  :      Optional[int]    =						use_labels
     __lowerCAmelCase  :      str    =						vocab_size
     __lowerCAmelCase  :      List[str]    =						hidden_size
     __lowerCAmelCase  :      Dict    =						num_hidden_layers
     __lowerCAmelCase  :      int    =						num_attention_heads
     __lowerCAmelCase  :      Any    =						intermediate_size
     __lowerCAmelCase  :      Dict    =						hidden_dropout_prob
     __lowerCAmelCase  :      List[Any]    =						attention_probs_dropout_prob
     __lowerCAmelCase  :      Tuple    =						max_position_embeddings
     __lowerCAmelCase  :      Union[str, Any]    =						eos_token_id
     __lowerCAmelCase  :      Optional[Any]    =						pad_token_id
     __lowerCAmelCase  :      int    =						bos_token_id







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






     """simple docstring"""







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

     __lowerCAmelCase  :      Any    =						ids_tensor([self.batch_size, self.seq_length]	,							self.vocab_size   )

     __lowerCAmelCase  :      Dict    =						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  :      Tuple    =						prepare_mbart_inputs_dict(lowerCAmelCase	,							lowerCAmelCase	,							lowerCAmelCase   )
     return config, inputs_dict







  def 	SCREAMING_SNAKE_CASE   (      self			:   List[str]	,							lowerCAmelCase			:   Any	,							lowerCAmelCase			:   str   )							->     Optional[Any]:






     """simple docstring"""







     __lowerCAmelCase  :      List[str]    =						TFMBartModel(config=lowerCAmelCase   ).get_decoder()
     __lowerCAmelCase  :      Tuple    =						inputs_dict["""input_ids"""]

     __lowerCAmelCase  :      Optional[Any]    =						input_ids[:1, :]
     __lowerCAmelCase  :      Union[str, Any]    =						inputs_dict["""attention_mask"""][:1, :]
     __lowerCAmelCase  :      Tuple    =						inputs_dict["""head_mask"""]
     __lowerCAmelCase  :      Any    =						1

     # first forward pass
     __lowerCAmelCase  :      List[Any]    =						model(lowerCAmelCase	,							attention_mask=lowerCAmelCase	,							head_mask=lowerCAmelCase	,							use_cache=lowerCAmelCase   )

     __lowerCAmelCase   ,__lowerCAmelCase  :      List[str]    =						outputs.to_tuple()
     __lowerCAmelCase  :      Union[str, Any]    =						past_key_values[1]






def      snake_case_				(__A					:						str ,       __A					:						Union[str, Any] ,       __A					:						Tuple ,       __A					:						Tuple=None ,       __A					:						Optional[Any]=None ,       __A					:						Optional[Any]=None ,       __A					:						Optional[int]=None ,       __A					:						Optional[Any]=None ,       )      ->     int:
   if attention_mask is None:
      __lowerCAmelCase  :      Dict    =						tf.cast(tf.math.not_equal(__A ,       config.pad_token_id					) ,       tf.inta					)
   if decoder_attention_mask is None:
      __lowerCAmelCase  :      str    =						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  :      Tuple    =						tf.ones((config.encoder_layers, config.encoder_attention_heads)					)
   if decoder_head_mask is None:
      __lowerCAmelCase  :      List[Any]    =						tf.ones((config.decoder_layers, config.decoder_attention_heads)					)
   if cross_attn_head_mask is None:
      __lowerCAmelCase  :      Any    =						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 SCREAMING_SNAKE_CASE     (  a_       ,							a_       ,							unittest.TestCase			):
  """simple docstring"""






  lowerCamelCase   :      Optional[int]										=(TFMBartForConditionalGeneration, TFMBartModel) if is_tf_available() else ()
  lowerCamelCase   :      List[str]										=(TFMBartForConditionalGeneration,) if is_tf_available() else ()
  lowerCamelCase   :      Union[str, Any]										=(
      {
          "conversational": TFMBartForConditionalGeneration,
          "feature-extraction": TFMBartModel,
          "summarization": TFMBartForConditionalGeneration,
          "text2text-generation": TFMBartForConditionalGeneration,
          "translation": TFMBartForConditionalGeneration,
      }
      if is_tf_available()
      else {}
  )
  lowerCamelCase   :      str										=True
  lowerCamelCase   :      Tuple										=False
  lowerCamelCase   :      Dict										=False







  def 	SCREAMING_SNAKE_CASE   (      self			:   str	,							lowerCAmelCase			:   Optional[Any]	,							lowerCAmelCase			:   Union[str, Any]	,							lowerCAmelCase			:   List[str]	,							lowerCAmelCase			:   Any	,							lowerCAmelCase			:   Optional[Any]   )							->     Optional[int]:






     """simple docstring"""







     if pipeline_test_casse_name != "FeatureExtractionPipelineTests":
        # Exception encountered when calling layer '...'
        return True

     return False







  def 	SCREAMING_SNAKE_CASE   (      self			:   Tuple   )							->     Optional[int]:






     """simple docstring"""







     __lowerCAmelCase  :      Union[str, Any]    =						TFMBartModelTester(self   )
     __lowerCAmelCase  :      Union[str, Any]    =						ConfigTester(self	,							config_class=lowerCAmelCase   )







  def 	SCREAMING_SNAKE_CASE   (      self			:   List[str]   )							->     List[Any]:






     """simple docstring"""







     self.config_tester.run_common_tests()







  def 	SCREAMING_SNAKE_CASE   (      self			:   Tuple   )							->     List[str]:






     """simple docstring"""







     __lowerCAmelCase  :      List[Any]    =						self.model_tester.prepare_config_and_inputs_for_common()
     self.model_tester.check_decoder_model_past_large_inputs(*lowerCAmelCase   )






@require_sentencepiece
@require_tokenizers
@require_tf
class SCREAMING_SNAKE_CASE     (  unittest.TestCase			):
  """simple docstring"""






  lowerCamelCase   :      Union[str, Any]										=[
      " UN Chief Says There Is No Military Solution in Syria",
  ]
  lowerCamelCase   :      Tuple										=[
      "Şeful ONU declară că nu există o soluţie militară în Siria",
  ]
  lowerCamelCase   :      List[Any]										="facebook/mbart-large-en-ro"







  @cached_property
  def 	SCREAMING_SNAKE_CASE   (      self			:   List[str]   )							->     Any:






     """simple docstring"""







     return AutoTokenizer.from_pretrained(self.model_name   )







  @cached_property
  def 	SCREAMING_SNAKE_CASE   (      self			:   List[str]   )							->     Union[str, Any]:






     """simple docstring"""







     __lowerCAmelCase  :      int    =						TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name   )
     return model







  def 	SCREAMING_SNAKE_CASE   (      self			:   Optional[Any]	,							**lowerCAmelCase			:   Dict   )							->     Union[str, Any]:






     """simple docstring"""







     __lowerCAmelCase  :      Union[str, Any]    =						self.translate_src_text(**lowerCAmelCase   )
     self.assertListEqual(self.expected_text	,							lowerCAmelCase   )







  def 	SCREAMING_SNAKE_CASE   (      self			:   Union[str, Any]	,							**lowerCAmelCase			:   int   )							->     str:






     """simple docstring"""







     __lowerCAmelCase  :      Dict    =						self.tokenizer(self.src_text	,							**lowerCAmelCase	,							return_tensors="""tf"""   )
     __lowerCAmelCase  :      Union[str, Any]    =						self.model.generate(
         model_inputs.input_ids	,							attention_mask=model_inputs.attention_mask	,							num_beams=2   )
     __lowerCAmelCase  :      List[str]    =						self.tokenizer.batch_decode(lowerCAmelCase	,							skip_special_tokens=lowerCAmelCase   )
     return generated_words







  @slow
  def 	SCREAMING_SNAKE_CASE   (      self			:   Optional[int]   )							->     Any:






     """simple docstring"""







     self._assert_generated_batch_equal_expected()


