


'''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			(	a_    , unittest.TestCase	):
    """simple docstring"""
    a													=   LDMTextToImagePipeline
    a													=   TEXT_TO_IMAGE_PARAMS - {
        "negative_prompt",
        "negative_prompt_embeds",
        "cross_attention_kwargs",
        "prompt_embeds",
    }
    a													=   PipelineTesterMixin.required_optional_params - {
        "num_images_per_prompt",
        "callback",
        "callback_steps",
    }
    a													=   TEXT_TO_IMAGE_BATCH_PARAMS
    a													=   False


    def        A   (  self      :							Optional[Any]):
           torch.manual_seed(0)
           _A					:     Optional[int]     = 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				,							)
           _A					:     Optional[Any]     = DDIMScheduler(
               beta_start=0.0_0085				,							beta_end=0.012				,							beta_schedule='scaled_linear'				,							clip_sample=SCREAMING_SNAKE_CASE				,							set_alpha_to_one=SCREAMING_SNAKE_CASE				,							)
           torch.manual_seed(0)
           _A					:     int     = 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)
           _A					:     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=1000				,							)
           _A					:     Tuple     = CLIPTextModel(SCREAMING_SNAKE_CASE)
           _A					:     Tuple     = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip')

           _A					:     Optional[int]     = {
               'unet': unet,
               'scheduler': scheduler,
               'vqvae': vae,
               'bert': text_encoder,
               'tokenizer': tokenizer,
           }
           return components


    def        A   (  self      :							Optional[Any]				,							SCREAMING_SNAKE_CASE      :							Optional[Any]				,							SCREAMING_SNAKE_CASE      :							Tuple=0):
           if str(SCREAMING_SNAKE_CASE).startswith('mps'):
                  _A					:     int     = torch.manual_seed(SCREAMING_SNAKE_CASE)
           else:
                  _A					:     Optional[Any]     = torch.Generator(device=SCREAMING_SNAKE_CASE).manual_seed(SCREAMING_SNAKE_CASE)
           _A					:     Union[str, Any]     = {
               '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        A   (  self      :							int):
           _A					:     Optional[Any]     = 'cpu'  # ensure determinism for the device-dependent torch.Generator

           _A					:     str     = self.get_dummy_components()
           _A					:     Dict     = LDMTextToImagePipeline(**SCREAMING_SNAKE_CASE)
           pipe.to(SCREAMING_SNAKE_CASE)
           pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE)

           _A					:     List[str]     = self.get_dummy_inputs(SCREAMING_SNAKE_CASE)
           _A					:     Dict     = pipe(**SCREAMING_SNAKE_CASE).images
           _A					:     Any     = image[0, -3:, -3:, -1]

           assert image.shape == (1, 16, 16, 3)
           _A					:     str     = 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        A   (  self      :							List[str]):
           super().tearDown()
           gc.collect()
           torch.cuda.empty_cache()


    def        A   (  self      :							int				,							SCREAMING_SNAKE_CASE      :							Any				,							SCREAMING_SNAKE_CASE      :							Union[str, Any]=torch.floataa				,							SCREAMING_SNAKE_CASE      :							List[str]=0):
           _A					:     List[str]     = torch.manual_seed(SCREAMING_SNAKE_CASE)
           _A					:     Optional[Any]     = np.random.RandomState(SCREAMING_SNAKE_CASE).standard_normal((1, 4, 32, 32))
           _A					:     str     = torch.from_numpy(SCREAMING_SNAKE_CASE).to(device=SCREAMING_SNAKE_CASE				,							dtype=SCREAMING_SNAKE_CASE)
           _A					:     Union[str, Any]     = {
               '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        A   (  self      :							Union[str, Any]):
           _A					:     Tuple     = LDMTextToImagePipeline.from_pretrained('CompVis/ldm-text2im-large-256').to(SCREAMING_SNAKE_CASE)
           pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE)

           _A					:     str     = self.get_inputs(SCREAMING_SNAKE_CASE)
           _A					:     Any     = pipe(**SCREAMING_SNAKE_CASE).images
           _A					:     Tuple     = image[0, -3:, -3:, -1].flatten()

           assert image.shape == (1, 256, 256, 3)
           _A					:     Union[str, Any]     = np.array([0.5_1825, 0.5_2850, 0.5_2543, 0.5_4258, 0.5_2304, 0.5_2569, 0.5_4363, 0.5_5276, 0.5_6878])
           _A					:     int     = np.abs(expected_slice - image_slice).max()
           assert max_diff < 1e-3




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


    def        A   (  self      :							Dict):
           super().tearDown()
           gc.collect()
           torch.cuda.empty_cache()


    def        A   (  self      :							Optional[Any]				,							SCREAMING_SNAKE_CASE      :							Any				,							SCREAMING_SNAKE_CASE      :							Any=torch.floataa				,							SCREAMING_SNAKE_CASE      :							Optional[Any]=0):
           _A					:     Tuple     = torch.manual_seed(SCREAMING_SNAKE_CASE)
           _A					:     Optional[Any]     = np.random.RandomState(SCREAMING_SNAKE_CASE).standard_normal((1, 4, 32, 32))
           _A					:     List[Any]     = torch.from_numpy(SCREAMING_SNAKE_CASE).to(device=SCREAMING_SNAKE_CASE				,							dtype=SCREAMING_SNAKE_CASE)
           _A					:     List[Any]     = {
               '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        A   (  self      :							Any):
           _A					:     int     = LDMTextToImagePipeline.from_pretrained('CompVis/ldm-text2im-large-256').to(SCREAMING_SNAKE_CASE)
           pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE)

           _A					:     Any     = self.get_inputs(SCREAMING_SNAKE_CASE)
           _A					:     Dict     = pipe(**SCREAMING_SNAKE_CASE).images[0]

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










'''simple docstring'''







from dataclasses import dataclass, field
from typing import Optional


@dataclass
class 			__lowerCamelCase			:
    """simple docstring"""
    a													=   field(
        default="codeparrot/codeparrot"    , metadata={"help": "Model name or path of model to be trained."}	)
    a													=   field(
        default="./"    , metadata={"help": "Save dir where model repo is cloned and models updates are saved to."}	)
    a													=   field(
        default="codeparrot/codeparrot-clean-train"    , metadata={"help": "Name or path of training dataset."}	)
    a													=   field(
        default="codeparrot/codeparrot-clean-valid"    , metadata={"help": "Name or path of validation dataset."}	)
    a													=   field(default=2    , metadata={"help": "Batch size for training."}	)
    a													=   field(default=2    , metadata={"help": "Batch size for evaluation."}	)
    a													=   field(default=0.1    , metadata={"help": "Value of weight decay."}	)
    a													=   field(
        default=1_0000    , metadata={"help": "Size of buffer used to shuffle streaming dataset."}	)
    a													=   field(default=2E-4    , metadata={"help": "Learning rate fo training."}	)
    a													=   field(default="cosine"    , metadata={"help": "Learning rate."}	)
    a													=   field(
        default=750    , metadata={"help": "Number of warmup steps in the learning rate schedule."}	)
    a													=   field(
        default=16    , metadata={"help": "Number of gradient accumulation steps."}	)
    a													=   field(
        default=a_    , metadata={"help": "Use gradient checkpointing to reduce memory footprint."}	)
    a													=   field(default=5_0000    , metadata={"help": "Maximum number of training steps."}	)
    a													=   field(
        default=-1    , metadata={"help": "Maximum number of evaluation steps. If -1 the full dataset is evaluated."}	)
    a													=   field(default=1024    , metadata={"help": "Sequence lengths used for training."}	)
    a													=   field(default=1    , metadata={"help": "Training seed."}	)
    a													=   field(
        default=1024    , metadata={"help": "Interval to save checkpoints. Measured as number of forward passes not training steps."}    , )
    a													=   field(
        default=a_    , metadata={"help": "States path if the training should continue from a checkpoint folder."}	)
    a													=   field(default=a_    , metadata={"help": "If True the data is pretokenized."}	)




@dataclass
class 			__lowerCamelCase			:
    """simple docstring"""
    a													=   field(
        default="codeparrot/codeparrot"    , metadata={"help": "Model name or path of model to be evaluated."}	)
    a													=   field(
        default="codeparrot/codeparrot-clean-valid"    , metadata={"help": "Name or path of validation dataset."}	)
    a													=   field(default=2    , metadata={"help": "Batch size used for evaluation."}	)
    a													=   field(
        default=-1    , metadata={"help": "Maximum number of evaluation steps. If -1 the full dataset is evaluated."}	)
    a													=   field(default=1024    , metadata={"help": "Length of sequences to be evaluated."}	)
    a													=   field(default=1    , metadata={"help": "Random seed used for evaluation."}	)




@dataclass
class 			__lowerCamelCase			:
    """simple docstring"""
    a													=   field(
        default="codeparrot/codeparrot"    , metadata={"help": "Model name or path of model to be evaluated."}	)
    a													=   field(default=a_    , metadata={"help": "Number of workers used for code evaluation."}	)
    a													=   field(
        default=a_    , metadata={"help": "The number of human-eval tasks to run. If not included all tasks are evaluated."}    , )
    a													=   field(
        default=a_    , metadata={"help": "Sample from the language model's output distribution."}	)
    a													=   field(default=0.2    , metadata={"help": "Sampling temperature used for generation."}	)
    a													=   field(default=256    , metadata={"help": "Maximum number of newly generated tokens."}	)
    a													=   field(default=0    , metadata={"help": "Top-k parameter used for generation."}	)
    a													=   field(default=0.95    , metadata={"help": "Top-p parameter used for nucleus sampling."}	)
    a													=   field(default=10    , metadata={"help": "Number of generations to run in parallel."}	)
    a													=   field(
        default=200    , metadata={"help": "Number of completions to generate for each sample."}	)
    a													=   field(default=1    , metadata={"help": "Random seed used for evaluation."}	)
    a													=   field(
        default="eval_results.json"    , metadata={"help": "Random seed used for evaluation."}	)
    a													=   field(
        default="0"    , metadata={"help": "Allow `code_eval` to execute Python code on machine"}	)
    a													=   field(
        default=-1    , metadata={
            "help": (
                "Determine which device to run the `text-generation` Pipeline on. -1 is CPU and any zero or positive"
                " number corresponds to which GPU device id to run on."
            )
        }    , )




@dataclass
class 			__lowerCamelCase			:
    """simple docstring"""
    a													=   field(
        default=a_    , metadata={
            "help": "The number of CPU cores to use for parallel preprocessing. Default uses the maximum available."
        }    , )
    a													=   field(
        default="transformersbook/codeparrot"    , metadata={"help": "Folder or name of dataset to process."}	)
    a													=   field(
        default="codeparrot-clean"    , metadata={"help": "Folder to save processed processed dataset."}	)
    a													=   field(
        default=10_0000    , metadata={"help": "Number of files to save per JSON output file."}	)
    a													=   field(default="content"    , metadata={"help": "Column containing text data to process."}	)
    a													=   field(
        default=1000    , metadata={"help": "Maximum line length in file, otherwise file is filtered."}	)
    a													=   field(
        default=100    , metadata={"help": "Maximum mean line length in file, otherwise file is filtered."}	)
    a													=   field(
        default=0.25    , metadata={"help": "Maximum fraction of non-alphanumeric characters, otherwise file is filtered."}	)
    a													=   field(
        default=1.5    , metadata={"help": "Minimum character token ratio for the file, otherwise file is filtered."}	)
    a													=   field(
        default=0.7    , metadata={"help": "Probability for filtering config, test and uncommon files."}	)
    a													=   field(
        default="codeparrot/codeparrot"    , metadata={"help": "Name or path to the tokenizer."}    , )
    a													=   field(
        default=a_    , metadata={"help": "If True, near-duplicate samples are removed."}	)
    a													=   field(
        default=0.85    , metadata={"help": "Jaccard threshold for near-duplicate samples."}	)




@dataclass
class 			__lowerCamelCase			:
    """simple docstring"""
    a													=   field(
        default="gpt2"    , metadata={"help": "Base tokenizer to build new tokenizer from."}	)
    a													=   field(
        default="transformersbook/codeparrot-train"    , metadata={"help": "Dataset to train tokenizer on."}	)
    a													=   field(default="content"    , metadata={"help": "Column containing text data to process."}	)
    a													=   field(default=20_0000    , metadata={"help": "Number of examples to train tokenizer on."}	)
    a													=   field(
        default=3_2768    , metadata={"help": "Number of examples to train the tokenizer on."}	)
    a													=   field(default="codeparrot"    , metadata={"help": "Name of new tokenizer."}	)
    a													=   field(default=a_    , metadata={"help": "Push saved tokenizer to the hub."}	)




@dataclass
class 			__lowerCamelCase			:
    """simple docstring"""
    a													=   field(
        default="codeparrot/codeparrot"    , metadata={"help": "Name or path to the tokenizer."}	)
    a													=   field(
        default="codeparrot/codeparrot-clean-train"    , metadata={"help": "Name or path to the dataset to pretokenize."}	)
    a													=   field(
        default="tokenized-codeparrot-train"    , metadata={"help": "Repo name of the pretokenized data."}	)
    a													=   field(default=a_    , metadata={"help": "Number of workers used for code evaluation."}	)




@dataclass
class 			__lowerCamelCase			:
    """simple docstring"""
    a													=   field(
        default="gpt2-large"    , metadata={"help": "Configuration to use for model initialization."}	)
    a													=   field(
        default="codeparrot/codeparrot"    , metadata={"help": "Tokenizer attached to model."}	)
    a													=   field(default="codeparrot"    , metadata={"help": "Name of the created model."}	)
    a													=   field(default=a_    , metadata={"help": "Push saved tokenizer to the hub."}	)






