




import gc
import random
import unittest

import numpy as np
import torch
from transformers import XLMRobertaTokenizer

from diffusers import (
    AltDiffusionImgaImgPipeline,
    AutoencoderKL,
    PNDMScheduler,
    UNetaDConditionModel,
)
from diffusers.image_processor import VaeImageProcessor
from diffusers.pipelines.alt_diffusion.modeling_roberta_series import (
    RobertaSeriesConfig,
    RobertaSeriesModelWithTransformation,
)
from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu


enable_full_determinism()

class 						__lowerCAmelCase      (      unittest.TestCase					):
							def  lowerCamelCase__				(		self		:List[Any]							):







								'''simple docstring'''







								super().tearDown()
								gc.collect()
								torch.cuda.empty_cache()
							@property
							def  lowerCamelCase__				(		self		:Optional[int]							):







								'''simple docstring'''







								a									=				1
								a									=				3
								a									=				(32, 32)

								a									=				floats_tensor((batch_size, num_channels) + sizes						, rng=random.Random(0							)							).to(__magic_name__							)
								return image
							@property
							def  lowerCamelCase__				(		self		:Union[str, Any]							):







								'''simple docstring'''







								torch.manual_seed(0							)
								a									=				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  lowerCamelCase__				(		self		:Union[str, Any]							):







								'''simple docstring'''







								torch.manual_seed(0							)
								a									=				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  lowerCamelCase__				(		self		:Optional[Any]							):







								'''simple docstring'''







								torch.manual_seed(0							)
								a									=				RobertaSeriesConfig(
								    hidden_size=32						, project_dim=32						, intermediate_size=37						, layer_norm_eps=1E-0_5						, num_attention_heads=4						, num_hidden_layers=5						, pad_token_id=1						, vocab_size=5006						, )
								return RobertaSeriesModelWithTransformation(__magic_name__							)
							@property
							def  lowerCamelCase__				(		self		:Optional[Any]							):







								'''simple docstring'''







								def extract(*__magic_name__		:Dict						, **__magic_name__		:int							):

									class 						__lowerCAmelCase      :
																def __init__(		self		:Any							):







																	'''simple docstring'''







																	a									=				torch.ones([0]							)





																def  lowerCamelCase__				(		self		:Dict						, __magic_name__		:Optional[int]							):







																	'''simple docstring'''







																	self.pixel_values.to(__magic_name__							)
																	return self







									return Out()

								return extract
							def  lowerCamelCase__				(		self		:Dict							):







								'''simple docstring'''







								a									=				"""cpu"""  # ensure determinism for the device-dependent torch.Generator
								a									=				self.dummy_cond_unet
								a									=				PNDMScheduler(skip_prk_steps=__magic_name__							)
								a									=				self.dummy_vae
								a									=				self.dummy_text_encoder
								a									=				XLMRobertaTokenizer.from_pretrained("""hf-internal-testing/tiny-xlm-roberta"""							)
								a									=				77

								a									=				self.dummy_image.to(__magic_name__							)
								a									=				init_image / 2 + 0.5

								# make sure here that pndm scheduler skips prk
								a									=				AltDiffusionImgaImgPipeline(
								    unet=__magic_name__						, scheduler=__magic_name__						, vae=__magic_name__						, text_encoder=__magic_name__						, tokenizer=__magic_name__						, safety_checker=__magic_name__						, feature_extractor=self.dummy_extractor						, )
								a									=				VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor						, do_normalize=__magic_name__							)
								a									=				alt_pipe.to(__magic_name__							)
								alt_pipe.set_progress_bar_config(disable=__magic_name__							)

								a									=				"""A painting of a squirrel eating a burger"""
								a									=				torch.Generator(device=__magic_name__							).manual_seed(0							)
								a									=				alt_pipe(
								    [prompt]						, generator=__magic_name__						, guidance_scale=6.0						, num_inference_steps=2						, output_type="""np"""						, image=__magic_name__						, )

								a									=				output.images

								a									=				torch.Generator(device=__magic_name__							).manual_seed(0							)
								a									=				alt_pipe(
								    [prompt]						, generator=__magic_name__						, guidance_scale=6.0						, num_inference_steps=2						, output_type="""np"""						, image=__magic_name__						, return_dict=__magic_name__						, )[0]

								a									=				image[0, -3:, -3:, -1]
								a									=				image_from_tuple[0, -3:, -3:, -1]

								assert image.shape == (1, 32, 32, 3)
								a									=				np.array([0.4427, 0.3731, 0.4249, 0.4941, 0.4546, 0.4148, 0.4193, 0.4666, 0.4499]							)

								assert np.abs(image_slice.flatten() - expected_slice							).max() < 5E-3
								assert np.abs(image_from_tuple_slice.flatten() - expected_slice							).max() < 5E-3
							@unittest.skipIf(torch_device != """cuda"""						, """This test requires a GPU"""							)
							def  lowerCamelCase__				(		self		:Tuple							):







								'''simple docstring'''







								a									=				self.dummy_cond_unet
								a									=				PNDMScheduler(skip_prk_steps=__magic_name__							)
								a									=				self.dummy_vae
								a									=				self.dummy_text_encoder
								a									=				XLMRobertaTokenizer.from_pretrained("""hf-internal-testing/tiny-xlm-roberta"""							)
								a									=				77

								a									=				self.dummy_image.to(__magic_name__							)

								# put models in fp16
								a									=				unet.half()
								a									=				vae.half()
								a									=				bert.half()

								# make sure here that pndm scheduler skips prk
								a									=				AltDiffusionImgaImgPipeline(
								    unet=__magic_name__						, scheduler=__magic_name__						, vae=__magic_name__						, text_encoder=__magic_name__						, tokenizer=__magic_name__						, safety_checker=__magic_name__						, feature_extractor=self.dummy_extractor						, )
								a									=				VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor						, do_normalize=__magic_name__							)
								a									=				alt_pipe.to(__magic_name__							)
								alt_pipe.set_progress_bar_config(disable=__magic_name__							)

								a									=				"""A painting of a squirrel eating a burger"""
								a									=				torch.manual_seed(0							)
								a									=				alt_pipe(
								    [prompt]						, generator=__magic_name__						, num_inference_steps=2						, output_type="""np"""						, image=__magic_name__						, ).images

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





							@unittest.skipIf(torch_device != """cuda"""						, """This test requires a GPU"""							)
							def  lowerCamelCase__				(		self		:Any							):







								'''simple docstring'''







								a									=				load_image(
								    """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
								    """/img2img/sketch-mountains-input.jpg"""							)
								# resize to resolution that is divisible by 8 but not 16 or 32
								a									=				init_image.resize((760, 504)							)

								a									=				"""BAAI/AltDiffusion"""
								a									=				AltDiffusionImgaImgPipeline.from_pretrained(
								    __magic_name__						, safety_checker=__magic_name__						, )
								pipe.to(__magic_name__							)
								pipe.set_progress_bar_config(disable=__magic_name__							)
								pipe.enable_attention_slicing()

								a									=				"""A fantasy landscape, trending on artstation"""

								a									=				torch.manual_seed(0							)
								a									=				pipe(
								    prompt=__magic_name__						, image=__magic_name__						, strength=0.75						, guidance_scale=7.5						, generator=__magic_name__						, output_type="""np"""						, )
								a									=				output.images[0]

								a									=				image[255:258, 383:386, -1]

								assert image.shape == (504, 760, 3)
								a									=				np.array([0.9358, 0.9397, 0.9599, 0.9901, 1.0000, 1.0000, 0.9882, 1.0000, 1.0000]							)

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







@slow
@require_torch_gpu
class 						__lowerCAmelCase      (      unittest.TestCase					):
							def  lowerCamelCase__				(		self		:Union[str, Any]							):







								'''simple docstring'''







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





							def  lowerCamelCase__				(		self		:List[str]							):







								'''simple docstring'''







								a									=				load_image(
								    """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
								    """/img2img/sketch-mountains-input.jpg"""							)
								a									=				init_image.resize((768, 512)							)
								a									=				load_numpy(
								    """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/img2img/fantasy_landscape_alt.npy"""							)

								a									=				"""BAAI/AltDiffusion"""
								a									=				AltDiffusionImgaImgPipeline.from_pretrained(
								    __magic_name__						, safety_checker=__magic_name__						, )
								pipe.to(__magic_name__							)
								pipe.set_progress_bar_config(disable=__magic_name__							)
								pipe.enable_attention_slicing()

								a									=				"""A fantasy landscape, trending on artstation"""

								a									=				torch.manual_seed(0							)
								a									=				pipe(
								    prompt=__magic_name__						, image=__magic_name__						, strength=0.75						, guidance_scale=7.5						, generator=__magic_name__						, output_type="""np"""						, )
								a									=				output.images[0]

								assert image.shape == (512, 768, 3)
								# img2img is flaky across GPUs even in fp32, so using MAE here
								assert np.abs(expected_image - image							).max() < 1E-2







from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available


__UpperCamelCase   :			Optional[int]          = {
    "configuration_jukebox": [
        "JUKEBOX_PRETRAINED_CONFIG_ARCHIVE_MAP",
        "JukeboxConfig",
        "JukeboxPriorConfig",
        "JukeboxVQVAEConfig",
    ],
    "tokenization_jukebox": ["JukeboxTokenizer"],
}

try:
		if not is_torch_available():
				raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
		pass
else:
		__UpperCamelCase   :			int          = [
		    "JUKEBOX_PRETRAINED_MODEL_ARCHIVE_LIST",
		    "JukeboxModel",
		    "JukeboxPreTrainedModel",
		    "JukeboxVQVAE",
		    "JukeboxPrior",
		]

if TYPE_CHECKING:
		from .configuration_jukebox import (
		    JUKEBOX_PRETRAINED_CONFIG_ARCHIVE_MAP,
		    JukeboxConfig,
		    JukeboxPriorConfig,
		    JukeboxVQVAEConfig,
		)
		from .tokenization_jukebox import JukeboxTokenizer

		try:
				if not is_torch_available():
						raise OptionalDependencyNotAvailable()
		except OptionalDependencyNotAvailable:
				pass
		else:
				from .modeling_jukebox import (
				    JUKEBOX_PRETRAINED_MODEL_ARCHIVE_LIST,
				    JukeboxModel,
				    JukeboxPreTrainedModel,
				    JukeboxPrior,
				    JukeboxVQVAE,
				)

else:
		import sys

		__UpperCamelCase   :			List[str]          = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)

