





'''simple docstring'''

import gc
import unittest

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

from diffusers import AutoencoderKL, DDIMScheduler, LDMTextToImagePipeline, UNetaDConditionModel
from diffusers.utils.testing_utils import (
    enable_full_determinism,
    load_numpy,
    nightly,
    require_torch_gpu,
    slow,
    torch_device,
)

from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()
class 				__lowerCAmelCase     (    __snake_case						,						unittest.TestCase ):






       """simple docstring"""
       _snake_case	:     Dict										=    LDMTextToImagePipeline
       _snake_case	:     int										=    TEXT_TO_IMAGE_PARAMS - {
           'negative_prompt',
           'negative_prompt_embeds',
           'cross_attention_kwargs',
           'prompt_embeds',
       }
       _snake_case	:     Tuple										=    PipelineTesterMixin.required_optional_params - {
           'num_images_per_prompt',
           'callback',
           'callback_steps',
       }
       _snake_case	:     Union[str, Any]										=    TEXT_TO_IMAGE_BATCH_PARAMS
       _snake_case	:     Optional[Any]										=    False





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

            '''simple docstring'''




            torch.manual_seed(0     )
            _UpperCamelCase				    =       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       , )
            _UpperCamelCase				    =       DDIMScheduler(
                beta_start=0.00085       , beta_end=0.012       , beta_schedule='''scaled_linear'''       , clip_sample=A_       , set_alpha_to_one=A_       , )
            torch.manual_seed(0     )
            _UpperCamelCase				    =       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       , )
            torch.manual_seed(0     )
            _UpperCamelCase				    =       CLIPTextConfig(
                bos_token_id=0       , eos_token_id=2       , hidden_size=32       , intermediate_size=37       , layer_norm_eps=1e-0_5       , num_attention_heads=4       , num_hidden_layers=5       , pad_token_id=1       , vocab_size=1000       , )
            _UpperCamelCase				    =       CLIPTextModel(A_     )
            _UpperCamelCase				    =       CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''     )

            _UpperCamelCase				    =       {
                "unet": unet,
                "scheduler": scheduler,
                "vqvae": vae,
                "bert": text_encoder,
                "tokenizer": tokenizer,
            }
            return components





       def snake_case__						(							self   :		Tuple       , lowerCAmelCase__   :		Union[str, Any]       , lowerCAmelCase__   :		int=0     )    ->     Dict:

            '''simple docstring'''




            if str(A_     ).startswith('''mps'''     ):
                 _UpperCamelCase				    =       torch.manual_seed(A_     )
            else:
                 _UpperCamelCase				    =       torch.Generator(device=A_     ).manual_seed(A_     )
            _UpperCamelCase				    =       {
                "prompt": "A painting of a squirrel eating a burger",
                "generator": generator,
                "num_inference_steps": 2,
                "guidance_scale": 6.0,
                "output_type": "numpy",
            }
            return inputs







       def snake_case__						(							self   :		int     )    ->     List[str]:

            '''simple docstring'''




            _UpperCamelCase				    =       "cpu"  # ensure determinism for the device-dependent torch.Generator

            _UpperCamelCase				    =       self.get_dummy_components()
            _UpperCamelCase				    =       LDMTextToImagePipeline(**A_     )
            pipe.to(A_     )
            pipe.set_progress_bar_config(disable=A_     )

            _UpperCamelCase				    =       self.get_dummy_inputs(A_     )
            _UpperCamelCase				    =       pipe(**A_     ).images
            _UpperCamelCase				    =       image[0, -3:, -3:, -1]

            assert image.shape == (1, 16, 16, 3)
            _UpperCamelCase				    =       np.array([0.6101, 0.6156, 0.5622, 0.4895, 0.6661, 0.3804, 0.5748, 0.6136, 0.5014]     )

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

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






       """simple docstring"""





       def snake_case__						(							self   :		Union[str, Any]     )    ->     Tuple:

            '''simple docstring'''




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





       def snake_case__						(							self   :		List[str]       , lowerCAmelCase__   :		Tuple       , lowerCAmelCase__   :		Any=torch.floataa       , lowerCAmelCase__   :		int=0     )    ->     Any:

            '''simple docstring'''




            _UpperCamelCase				    =       torch.manual_seed(A_     )
            _UpperCamelCase				    =       np.random.RandomState(A_     ).standard_normal((1, 4, 32, 32)     )
            _UpperCamelCase				    =       torch.from_numpy(A_     ).to(device=A_       , dtype=A_     )
            _UpperCamelCase				    =       {
                "prompt": "A painting of a squirrel eating a burger",
                "latents": latents,
                "generator": generator,
                "num_inference_steps": 3,
                "guidance_scale": 6.0,
                "output_type": "numpy",
            }
            return inputs







       def snake_case__						(							self   :		Any     )    ->     int:

            '''simple docstring'''




            _UpperCamelCase				    =       LDMTextToImagePipeline.from_pretrained('''CompVis/ldm-text2im-large-256'''     ).to(A_     )
            pipe.set_progress_bar_config(disable=A_     )

            _UpperCamelCase				    =       self.get_inputs(A_     )
            _UpperCamelCase				    =       pipe(**A_     ).images
            _UpperCamelCase				    =       image[0, -3:, -3:, -1].flatten()

            assert image.shape == (1, 256, 256, 3)
            _UpperCamelCase				    =       np.array([0.51825, 0.52850, 0.52543, 0.54258, 0.52304, 0.52569, 0.54363, 0.55276, 0.56878]     )
            _UpperCamelCase				    =       np.abs(expected_slice - image_slice     ).max()
            assert max_diff < 1e-3

@nightly
@require_torch_gpu
class 				__lowerCAmelCase     (    unittest.TestCase ):






       """simple docstring"""





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

            '''simple docstring'''




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





       def snake_case__						(							self   :		List[Any]       , lowerCAmelCase__   :		Dict       , lowerCAmelCase__   :		Optional[int]=torch.floataa       , lowerCAmelCase__   :		Optional[int]=0     )    ->     List[str]:

            '''simple docstring'''




            _UpperCamelCase				    =       torch.manual_seed(A_     )
            _UpperCamelCase				    =       np.random.RandomState(A_     ).standard_normal((1, 4, 32, 32)     )
            _UpperCamelCase				    =       torch.from_numpy(A_     ).to(device=A_       , dtype=A_     )
            _UpperCamelCase				    =       {
                "prompt": "A painting of a squirrel eating a burger",
                "latents": latents,
                "generator": generator,
                "num_inference_steps": 50,
                "guidance_scale": 6.0,
                "output_type": "numpy",
            }
            return inputs







       def snake_case__						(							self   :		Dict     )    ->     List[str]:

            '''simple docstring'''




            _UpperCamelCase				    =       LDMTextToImagePipeline.from_pretrained('''CompVis/ldm-text2im-large-256'''     ).to(A_     )
            pipe.set_progress_bar_config(disable=A_     )

            _UpperCamelCase				    =       self.get_inputs(A_     )
            _UpperCamelCase				    =       pipe(**A_     ).images[0]

            _UpperCamelCase				    =       load_numpy(
                '''https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/ldm_text2img/ldm_large_256_ddim.npy'''     )
            _UpperCamelCase				    =       np.abs(expected_image - image     ).max()
            assert max_diff < 1e-3










import inspect
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_config_docstrings.py
__lowerCamelCase       :     str   =     """src/transformers"""


# This is to make sure the transformers module imported is the one in the repo.
__lowerCamelCase       :     Tuple   =     direct_transformers_import(PATH_TO_TRANSFORMERS)

__lowerCamelCase       :     List[str]   =     transformers.models.auto.configuration_auto.CONFIG_MAPPING

# Regex pattern used to find the checkpoint mentioned in the docstring of `config_class`.
# For example, `[bert-base-uncased](https://huggingface.co/bert-base-uncased)`
__lowerCamelCase       :     Optional[Any]   =     re.compile(r"""\[(.+?)\]\((https://huggingface\.co/.+?)\)""")


__lowerCamelCase       :     List[str]   =     {
    """DecisionTransformerConfig""",
    """EncoderDecoderConfig""",
    """MusicgenConfig""",
    """RagConfig""",
    """SpeechEncoderDecoderConfig""",
    """TimmBackboneConfig""",
    """VisionEncoderDecoderConfig""",
    """VisionTextDualEncoderConfig""",
    """LlamaConfig""",
}



def 		A_				(     _lowerCAmelCase     )						-> List[str]:
 UpperCamelCase	:					Optional[Any]       	=   None

 # source code of `config_class`
 UpperCamelCase	:					Tuple       	=   inspect.getsource(_lowerCAmelCase     )
 UpperCamelCase	:					Optional[Any]       	=   _re_checkpoint.findall(_lowerCAmelCase     )

 # Each `checkpoint` is a tuple of a checkpoint name and a checkpoint link.
 # For example, `('bert-base-uncased', 'https://huggingface.co/bert-base-uncased')`
 for ckpt_name, ckpt_link in checkpoints:
  # allow the link to end with `/`
  if ckpt_link.endswith("/"     ):
   UpperCamelCase	:					Dict       	=   ckpt_link[:-1]

  # verify the checkpoint name corresponds to the checkpoint link
  UpperCamelCase	:					Any       	=   F"""https://huggingface.co/{ckpt_name}"""
  if ckpt_link == ckpt_link_from_name:
   UpperCamelCase	:					List[Any]       	=   ckpt_name
   break

 return checkpoint



def 		A_				(     )						-> List[str]:
 UpperCamelCase	:					Optional[int]       	=   []

 for config_class in list(CONFIG_MAPPING.values()     ):
  # Skip deprecated models
  if "models.deprecated" in config_class.__module__:
   continue
  UpperCamelCase	:					Union[str, Any]       	=   get_checkpoint_from_config_class(_lowerCAmelCase     )

  UpperCamelCase	:					Optional[int]       	=   config_class.__name__
  if checkpoint is None and name not in CONFIG_CLASSES_TO_IGNORE_FOR_DOCSTRING_CHECKPOINT_CHECK:
   configs_without_checkpoint.append(_lowerCAmelCase     )

 if len(_lowerCAmelCase     ) > 0:
  UpperCamelCase	:					Any       	=   "\n".join(sorted(_lowerCAmelCase     )     )
  raise ValueError(F"""The following configurations don't contain any valid checkpoint:\n{message}"""     )


if __name__ == "__main__":
    check_config_docstrings_have_checkpoints()
