



"""simple docstring"""






import gc
import random
import unittest

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

from diffusers import (
    AutoencoderKL,
    DiffusionPipeline,
    EulerDiscreteScheduler,
    StableDiffusionXLImgaImgPipeline,
    UNetaDConditionModel,
)
from diffusers.utils import floats_tensor, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..pipeline_params import (
    IMAGE_TO_IMAGE_IMAGE_PARAMS,
    TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS,
    TEXT_GUIDED_IMAGE_VARIATION_PARAMS,
)
from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()






class 			__snake_case			(      _lowercase    ,	_lowercase    ,	unittest.TestCase):
  snake_case__							:  Optional[Any]         =		StableDiffusionXLImgaImgPipeline
  snake_case__							:  Union[str, Any]         =		TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"height", "width"}
  snake_case__							:  int         =		PipelineTesterMixin.required_optional_params - {"latents"}
  snake_case__							:  Union[str, Any]         =		TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS
  snake_case__							:  Dict         =		IMAGE_TO_IMAGE_IMAGE_PARAMS
  snake_case__							:  Any         =		IMAGE_TO_IMAGE_IMAGE_PARAMS




  def 		SCREAMING_SNAKE_CASE							(					self	:		Optional[Any]						):






         """simple docstring"""






         torch.manual_seed(0						)
         _lowerCamelCase		:							Union[str, Any]            =					UNetaDConditionModel(
             block_out_channels=(3_2, 6_4)		,   layers_per_block=2		,   sample_size=3_2		,   in_channels=4		,   out_channels=4		,   down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''')		,   up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D''')		,   attention_head_dim=(2, 4)		,   use_linear_projection=__lowerCAmelCase		,   addition_embed_type='''text_time'''		,   addition_time_embed_dim=8		,   transformer_layers_per_block=(1, 2)		,   projection_class_embeddings_input_dim=8_0		,   cross_attention_dim=6_4		,   )
         _lowerCamelCase		:							Dict            =					EulerDiscreteScheduler(
             beta_start=0.0_00_85		,   beta_end=0.0_12		,   steps_offset=1		,   beta_schedule='''scaled_linear'''		,   timestep_spacing='''leading'''		,   )
         torch.manual_seed(0						)
         _lowerCamelCase		:							str            =					AutoencoderKL(
             block_out_channels=[3_2, 6_4]		,   in_channels=3		,   out_channels=3		,   down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D''']		,   up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D''']		,   latent_channels=4		,   sample_size=1_2_8		,   )
         torch.manual_seed(0						)
         _lowerCamelCase		:							Any            =					CLIPTextConfig(
             bos_token_id=0		,   eos_token_id=2		,   hidden_size=3_2		,   intermediate_size=3_7		,   layer_norm_eps=1E-05		,   num_attention_heads=4		,   num_hidden_layers=5		,   pad_token_id=1		,   vocab_size=1_0_0_0		,   hidden_act='''gelu'''		,   projection_dim=3_2		,   )
         _lowerCamelCase		:							Dict            =					CLIPTextModel(__lowerCAmelCase						)
         _lowerCamelCase		:							Dict            =					CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''		,   local_files_only=__lowerCAmelCase						)

         _lowerCamelCase		:							List[str]            =					CLIPTextModelWithProjection(__lowerCAmelCase						)
         _lowerCamelCase		:							str            =					CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''		,   local_files_only=__lowerCAmelCase						)

         _lowerCamelCase		:							List[Any]            =					{
             '''unet''': unet,
             '''scheduler''': scheduler,
             '''vae''': vae,
             '''text_encoder''': text_encoder,
             '''tokenizer''': tokenizer,
             '''text_encoder_2''': text_encoder_a,
             '''tokenizer_2''': tokenizer_a,
             # "safety_checker": None,
             # "feature_extractor": None,
         }
         return components




  def 		SCREAMING_SNAKE_CASE							(					self	:		int		,   __lowerCAmelCase	:		Tuple		,   __lowerCAmelCase	:		Any=0						):






         """simple docstring"""






         _lowerCamelCase		:							Dict            =					floats_tensor((1, 3, 3_2, 3_2)		,   rng=random.Random(__lowerCAmelCase						)						).to(__lowerCAmelCase						)
         _lowerCamelCase		:							str            =					image / 2 + 0.5
         if str(__lowerCAmelCase						).startswith('''mps'''						):
                _lowerCamelCase		:							Any            =					torch.manual_seed(__lowerCAmelCase						)
         else:
                _lowerCamelCase		:							str            =					torch.Generator(device=__lowerCAmelCase						).manual_seed(__lowerCAmelCase						)
         _lowerCamelCase		:							Union[str, Any]            =					{
             '''prompt''': '''A painting of a squirrel eating a burger''',
             '''image''': image,
             '''generator''': generator,
             '''num_inference_steps''': 2,
             '''guidance_scale''': 5.0,
             '''output_type''': '''numpy''',
             '''strength''': 0.75,
         }
         return inputs




  def 		SCREAMING_SNAKE_CASE							(					self	:		Dict						):






         """simple docstring"""






         _lowerCamelCase		:							Dict            =					'''cpu'''  # ensure determinism for the device-dependent torch.Generator
         _lowerCamelCase		:							int            =					self.get_dummy_components()
         _lowerCamelCase		:							Any            =					StableDiffusionXLImgaImgPipeline(**__lowerCAmelCase						)
         _lowerCamelCase		:							List[Any]            =					sd_pipe.to(__lowerCAmelCase						)
         sd_pipe.set_progress_bar_config(disable=__lowerCAmelCase						)

         _lowerCamelCase		:							Optional[Any]            =					self.get_dummy_inputs(__lowerCAmelCase						)
         _lowerCamelCase		:							List[Any]            =					sd_pipe(**__lowerCAmelCase						).images
         _lowerCamelCase		:							Tuple            =					image[0, -3:, -3:, -1]

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

         _lowerCamelCase		:							Any            =					np.array([0.46_56, 0.48_40, 0.44_39, 0.66_98, 0.55_74, 0.45_24, 0.57_99, 0.59_43, 0.51_65]						)

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




  def 		SCREAMING_SNAKE_CASE							(					self	:		str						):






         """simple docstring"""






         super().test_attention_slicing_forward_pass(expected_max_diff=3E-3						)




  def 		SCREAMING_SNAKE_CASE							(					self	:		List[str]						):






         """simple docstring"""






         super().test_inference_batch_single_identical(expected_max_diff=3E-3						)




  def 		SCREAMING_SNAKE_CASE							(					self	:		Any						):






         """simple docstring"""






         pass




  def 		SCREAMING_SNAKE_CASE							(					self	:		int						):






         """simple docstring"""






         _lowerCamelCase		:							Dict            =					self.get_dummy_components()
         _lowerCamelCase		:							Dict            =					StableDiffusionXLImgaImgPipeline(**__lowerCAmelCase						)
         _lowerCamelCase		:							Optional[Any]            =					sd_pipe.to(__lowerCAmelCase						)
         _lowerCamelCase		:							Optional[int]            =					sd_pipe.to(__lowerCAmelCase						)
         sd_pipe.set_progress_bar_config(disable=__lowerCAmelCase						)

         # forward without prompt embeds
         _lowerCamelCase		:							List[Any]            =					self.get_dummy_inputs(__lowerCAmelCase						)
         _lowerCamelCase		:							str            =					3 * ['''this is a negative prompt''']
         _lowerCamelCase		:							Dict            =					negative_prompt
         _lowerCamelCase		:							int            =					3 * [inputs['''prompt''']]

         _lowerCamelCase		:							Dict            =					sd_pipe(**__lowerCAmelCase						)
         _lowerCamelCase		:							Tuple            =					output.images[0, -3:, -3:, -1]

         # forward with prompt embeds
         _lowerCamelCase		:							List[str]            =					self.get_dummy_inputs(__lowerCAmelCase						)
         _lowerCamelCase		:							str            =					3 * ['''this is a negative prompt''']
         _lowerCamelCase		:							int            =					3 * [inputs.pop('''prompt'''						)]

         (
             (
             _lowerCamelCase
         )     ,       (
             _lowerCamelCase
         )     ,       (
             _lowerCamelCase
         )     ,       (
             _lowerCamelCase
         )     ,       
         )		:							Any            =					sd_pipe.encode_prompt(__lowerCAmelCase		,   negative_prompt=__lowerCAmelCase						)

         _lowerCamelCase		:							Optional[Any]            =					sd_pipe(
             **__lowerCAmelCase		,   prompt_embeds=__lowerCAmelCase		,   negative_prompt_embeds=__lowerCAmelCase		,   pooled_prompt_embeds=__lowerCAmelCase		,   negative_pooled_prompt_embeds=__lowerCAmelCase		,   )
         _lowerCamelCase		:							str            =					output.images[0, -3:, -3:, -1]

         # make sure that it's equal
         assert np.abs(image_slice_a.flatten() - image_slice_a.flatten()						).max() < 1E-4






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




  def 		SCREAMING_SNAKE_CASE							(					self	:		List[str]						):






         """simple docstring"""






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




  def 		SCREAMING_SNAKE_CASE							(					self	:		str		,   __lowerCAmelCase	:		Any		,   __lowerCAmelCase	:		Tuple="cpu"		,   __lowerCAmelCase	:		Tuple=torch.floataa		,   __lowerCAmelCase	:		Dict=0						):






         """simple docstring"""






         _lowerCamelCase		:							Tuple            =					torch.Generator(device=__lowerCAmelCase						).manual_seed(__lowerCAmelCase						)
         _lowerCamelCase		:							Optional[Any]            =					np.random.RandomState(__lowerCAmelCase						).standard_normal((1, 4, 6_4, 6_4)						)
         _lowerCamelCase		:							List[Any]            =					torch.from_numpy(__lowerCAmelCase						).to(device=__lowerCAmelCase		,   dtype=__lowerCAmelCase						)
         _lowerCamelCase		:							Optional[Any]            =					{
             '''prompt''': '''a photograph of an astronaut riding a horse''',
             '''latents''': latents,
             '''generator''': generator,
             '''num_inference_steps''': 3,
             '''guidance_scale''': 7.5,
             '''output_type''': '''numpy''',
         }
         return inputs




  def 		SCREAMING_SNAKE_CASE							(					self	:		Optional[int]						):






         """simple docstring"""






         _lowerCamelCase		:							List[str]            =					DiffusionPipeline.from_pretrained('''stabilityai/stable-diffusion-2-base'''						)
         pipe.to(__lowerCAmelCase						)
         pipe.set_progress_bar_config(disable=__lowerCAmelCase						)

         _lowerCamelCase		:							List[Any]            =					self.get_inputs(__lowerCAmelCase						)
         _lowerCamelCase		:							int            =					pipe(**__lowerCAmelCase						).images
         _lowerCamelCase		:							Tuple            =					image[0, -3:, -3:, -1].flatten()

         assert image.shape == (1, 5_1_2, 5_1_2, 3)
         _lowerCamelCase		:							Optional[int]            =					np.array([0.4_94_93, 0.4_78_96, 0.4_07_98, 0.5_42_14, 0.5_32_12, 0.4_82_02, 0.4_76_56, 0.4_63_29, 0.4_85_06]						)
         assert np.abs(image_slice - expected_slice						).max() < 7E-3



'''simple docstring'''


import argparse
import collections
import os
import re

from transformers.utils import direct_transformers_import


# All paths are set with the intent you should run this script from the root of the repo with the command
# python utils/check_table.py
__snake_case						  =		"""src/transformers"""
__snake_case						  =		"""docs/source/en"""
__snake_case						  =		"""."""

def   A_      (       SCREAMING_SNAKE_CASE_ ,	SCREAMING_SNAKE_CASE_ ,	SCREAMING_SNAKE_CASE_						)			->Tuple:
  with open(SCREAMING_SNAKE_CASE_ ,	"""r""" ,	encoding="""utf-8""" ,	newline="""\n"""						) as f:
    lowercase_     =       f.readlines()
  # Find the start prompt.
  lowercase_     =       0
  while not lines[start_index].startswith(SCREAMING_SNAKE_CASE_						):
    start_index += 1
  start_index += 1

  lowercase_     =       start_index
  while not lines[end_index].startswith(SCREAMING_SNAKE_CASE_						):
    end_index += 1
  end_index -= 1

  while len(lines[start_index]						) <= 1:
    start_index += 1
  while len(lines[end_index]						) <= 1:
    end_index -= 1
  end_index += 1
  return "".join(lines[start_index:end_index]						), start_index, end_index, lines


# Add here suffixes that are used to identify models, separated by |
__snake_case						  =		"""Model|Encoder|Decoder|ForConditionalGeneration"""
# Regexes that match TF/Flax/PT model names.
__snake_case						  =		re.compile(r"""TF(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)""")
__snake_case						  =		re.compile(r"""Flax(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)""")
# Will match any TF or Flax model too so need to be in an else branch afterthe two previous regexes.
__snake_case						  =		re.compile(r"""(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)""")


# This is to make sure the transformers module imported is the one in the repo.
__snake_case						  =		direct_transformers_import(TRANSFORMERS_PATH)

def   A_      (       SCREAMING_SNAKE_CASE_						)			->Dict:
  lowercase_     =       re.finditer(""".+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)""" ,	SCREAMING_SNAKE_CASE_						)
  return [m.group(0						) for m in matches]

def   A_      (       SCREAMING_SNAKE_CASE_ ,	SCREAMING_SNAKE_CASE_						)			->Optional[Any]:
  lowercase_     =       2 if text == """✅""" or text == """❌""" else len(SCREAMING_SNAKE_CASE_						)
  lowercase_     =       (width - text_length) // 2
  lowercase_     =       width - text_length - left_indent
  return " " * left_indent + text + " " * right_indent

def   A_      (       )			->Tuple:
  lowercase_     =       transformers_module.models.auto.configuration_auto.CONFIG_MAPPING_NAMES
  lowercase_     =       {
      name: config_maping_names[code]
      for code, name in transformers_module.MODEL_NAMES_MAPPING.items()
      if code in config_maping_names
  }
  lowercase_     =       {name: config.replace("""Config""" ,	""""""						) for name, config in model_name_to_config.items()}

  # Dictionaries flagging if each model prefix has a slow/fast tokenizer, backend in PT/TF/Flax.
  lowercase_     =       collections.defaultdict(SCREAMING_SNAKE_CASE_						)
  lowercase_     =       collections.defaultdict(SCREAMING_SNAKE_CASE_						)
  lowercase_     =       collections.defaultdict(SCREAMING_SNAKE_CASE_						)
  lowercase_     =       collections.defaultdict(SCREAMING_SNAKE_CASE_						)
  lowercase_     =       collections.defaultdict(SCREAMING_SNAKE_CASE_						)

  # Let's lookup through all transformers object (once).
  for attr_name in dir(SCREAMING_SNAKE_CASE_						):
    lowercase_     =       None
    if attr_name.endswith("""Tokenizer"""						):
      lowercase_     =       slow_tokenizers
      lowercase_     =       attr_name[:-9]
    elif attr_name.endswith("""TokenizerFast"""						):
      lowercase_     =       fast_tokenizers
      lowercase_     =       attr_name[:-13]
    elif _re_tf_models.match(SCREAMING_SNAKE_CASE_						) is not None:
      lowercase_     =       tf_models
      lowercase_     =       _re_tf_models.match(SCREAMING_SNAKE_CASE_						).groups()[0]
    elif _re_flax_models.match(SCREAMING_SNAKE_CASE_						) is not None:
      lowercase_     =       flax_models
      lowercase_     =       _re_flax_models.match(SCREAMING_SNAKE_CASE_						).groups()[0]
    elif _re_pt_models.match(SCREAMING_SNAKE_CASE_						) is not None:
      lowercase_     =       pt_models
      lowercase_     =       _re_pt_models.match(SCREAMING_SNAKE_CASE_						).groups()[0]

    if lookup_dict is not None:
      while len(SCREAMING_SNAKE_CASE_						) > 0:
        if attr_name in model_name_to_prefix.values():
          lowercase_     =       True
          break
        # Try again after removing the last word in the name
        lowercase_     =       """""".join(camel_case_split(SCREAMING_SNAKE_CASE_						)[:-1]						)

    # Let's build that table!
  lowercase_     =       list(model_name_to_config.keys()						)
  model_names.sort(key=str.lower						)
  lowercase_     =       ["""Model""", """Tokenizer slow""", """Tokenizer fast""", """PyTorch support""", """TensorFlow support""", """Flax Support"""]
  # We'll need widths to properly display everything in the center (+2 is to leave one extra space on each side).
  lowercase_     =       [len(SCREAMING_SNAKE_CASE_						) + 2 for c in columns]
  lowercase_     =       max([len(SCREAMING_SNAKE_CASE_						) for name in model_names]						) + 2

  # Build the table per se
  lowercase_     =       """|""" + """|""".join([_center_text(SCREAMING_SNAKE_CASE_ ,	SCREAMING_SNAKE_CASE_						) for c, w in zip(SCREAMING_SNAKE_CASE_ ,	SCREAMING_SNAKE_CASE_						)]						) + """|\n"""
  # Use ":-----:" format to center-aligned table cell texts
  table += "|" + "|".join([""":""" + """-""" * (w - 2) + """:""" for w in widths]						) + "|\n"

  lowercase_     =       {True: """✅""", False: """❌"""}
  for name in model_names:
    lowercase_     =       model_name_to_prefix[name]
    lowercase_     =       [
        name,
        check[slow_tokenizers[prefix]],
        check[fast_tokenizers[prefix]],
        check[pt_models[prefix]],
        check[tf_models[prefix]],
        check[flax_models[prefix]],
    ]
    table += "|" + "|".join([_center_text(SCREAMING_SNAKE_CASE_ ,	SCREAMING_SNAKE_CASE_						) for l, w in zip(SCREAMING_SNAKE_CASE_ ,	SCREAMING_SNAKE_CASE_						)]						) + "|\n"
  return table

def   A_      (       SCREAMING_SNAKE_CASE_=False						)			->Dict:
  lowercase_     ,	lowercase_     ,	lowercase_     ,	lowercase_     =       _find_text_in_file(
      filename=os.path.join(SCREAMING_SNAKE_CASE_ ,	"""index.md"""						) ,	start_prompt="""<!--This table is updated automatically from the auto modules""" ,	end_prompt="""<!-- End table-->""" ,	)
  lowercase_     =       get_model_table_from_auto_modules()

  if current_table != new_table:
    if overwrite:
      with open(os.path.join(SCREAMING_SNAKE_CASE_ ,	"""index.md"""						) ,	"""w""" ,	encoding="""utf-8""" ,	newline="""\n"""						) as f:
        f.writelines(lines[:start_index] + [new_table] + lines[end_index:]						)
    else:
      raise ValueError(
          """The model table in the `index.md` has not been updated. Run `make fix-copies` to fix this."""						)


if __name__ == "__main__":
       __snake_case						  =		argparse.ArgumentParser()
       parser.add_argument("""--fix_and_overwrite""", action="""store_true""", help="""Whether to fix inconsistencies.""")
       __snake_case						  =		parser.parse_args()

       check_model_table(args.fix_and_overwrite)

