import gc
import unittest

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

from diffusers import (
    AutoencoderKL,
    DDIMParallelScheduler,
    DDPMParallelScheduler,
    StableDiffusionParadigmsPipeline,
    UNetaDConditionModel,
)
from diffusers.utils import slow, torch_device
from diffusers.utils.testing_utils import (
    enable_full_determinism,
    require_torch_gpu,
)

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


enable_full_determinism()
class 	_a  (							lowerCamelCase_							,		lowerCamelCase_							,		unittest.TestCase					):



	"""simple docstring"""



	__SCREAMING_SNAKE_CASE              =					StableDiffusionParadigmsPipeline
	__SCREAMING_SNAKE_CASE              =					TEXT_TO_IMAGE_PARAMS
	__SCREAMING_SNAKE_CASE              =					TEXT_TO_IMAGE_BATCH_PARAMS
	__SCREAMING_SNAKE_CASE              =					TEXT_TO_IMAGE_IMAGE_PARAMS
	__SCREAMING_SNAKE_CASE              =					TEXT_TO_IMAGE_IMAGE_PARAMS


	def __lowerCAmelCase      (   self       ):
		torch.manual_seed(0       )
		_lowercase   =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       ,  attention_head_dim=(2, 4)       ,  use_linear_projection=lowerCAmelCase_       ,  )
		_lowercase   =DDIMParallelScheduler(
		    beta_start=0.0_0_0_8_5       ,  beta_end=0.0_1_2       ,  beta_schedule="scaled_linear"       ,  clip_sample=lowerCAmelCase_       ,  set_alpha_to_one=lowerCAmelCase_       ,  )
		torch.manual_seed(0       )
		_lowercase   =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       ,  sample_size=128       ,  )
		torch.manual_seed(0       )
		_lowercase   =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       ,  hidden_act="gelu"       ,  projection_dim=512       ,  )
		_lowercase   =CLIPTextModel(lowerCAmelCase_       )
		_lowercase   =CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"       )

		_lowercase   ={
		    "unet": unet,
		    "scheduler": scheduler,
		    "vae": vae,
		    "text_encoder": text_encoder,
		    "tokenizer": tokenizer,
		    "safety_checker": None,
		    "feature_extractor": None,
		}
		return components


	def __lowerCAmelCase      (   self       ,  lowerCAmelCase_       ,  lowerCAmelCase_=0       ):
		if str(lowerCAmelCase_       ).startswith("mps"       ):
			_lowercase   =torch.manual_seed(lowerCAmelCase_       )
		else:
			_lowercase   =torch.Generator(device=lowerCAmelCase_       ).manual_seed(lowerCAmelCase_       )
		_lowercase   ={
		    "prompt": "a photograph of an astronaut riding a horse",
		    "generator": generator,
		    "num_inference_steps": 10,
		    "guidance_scale": 6.0,
		    "output_type": "numpy",
		    "parallel": 3,
		    "debug": True,
		}
		return inputs


	def __lowerCAmelCase      (   self       ):
		_lowercase   ="cpu"  # ensure determinism for the device-dependent torch.Generator
		_lowercase   =self.get_dummy_components()
		_lowercase   =StableDiffusionParadigmsPipeline(**lowerCAmelCase_       )
		_lowercase   =sd_pipe.to(lowerCAmelCase_       )
		sd_pipe.set_progress_bar_config(disable=lowerCAmelCase_       )

		_lowercase   =self.get_dummy_inputs(lowerCAmelCase_       )
		_lowercase   =sd_pipe(**lowerCAmelCase_       ).images
		_lowercase   =image[0, -3:, -3:, -1]
		assert image.shape == (1, 64, 64, 3)

		_lowercase   =np.array([0.4_7_7_3, 0.5_4_1_7, 0.4_7_2_3, 0.4_9_2_5, 0.5_6_3_1, 0.4_7_5_2, 0.5_2_4_0, 0.4_9_3_5, 0.5_0_2_3]       )

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


	def __lowerCAmelCase      (   self       ):
		_lowercase   ="cpu"  # ensure determinism for the device-dependent torch.Generator
		_lowercase   =self.get_dummy_components()
		torch.manual_seed(0       )
		_lowercase   =DDPMParallelScheduler()
		torch.manual_seed(0       )
		_lowercase   =StableDiffusionParadigmsPipeline(**lowerCAmelCase_       )
		_lowercase   =sd_pipe.to(lowerCAmelCase_       )
		sd_pipe.set_progress_bar_config(disable=lowerCAmelCase_       )

		_lowercase   =self.get_dummy_inputs(lowerCAmelCase_       )
		_lowercase   =sd_pipe(**lowerCAmelCase_       ).images
		_lowercase   =image[0, -3:, -3:, -1]
		assert image.shape == (1, 64, 64, 3)

		_lowercase   =np.array([0.3_5_7_3, 0.4_4_2_0, 0.4_9_6_0, 0.4_7_9_9, 0.3_7_9_6, 0.3_8_7_9, 0.4_8_1_9, 0.4_3_6_5, 0.4_4_6_8]       )

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


	def __lowerCAmelCase      (   self       ):
		super().test_inference_batch_consistent(batch_sizes=[1, 2]       )


	def __lowerCAmelCase      (   self       ):
		super().test_inference_batch_single_identical(batch_size=2       ,  expected_max_diff=3e-3       )


	def __lowerCAmelCase      (   self       ):
		_lowercase   ="cpu"  # ensure determinism for the device-dependent torch.Generator
		_lowercase   =self.get_dummy_components()
		_lowercase   =StableDiffusionParadigmsPipeline(**lowerCAmelCase_       )
		_lowercase   =sd_pipe.to(lowerCAmelCase_       )
		sd_pipe.set_progress_bar_config(disable=lowerCAmelCase_       )

		_lowercase   =self.get_dummy_inputs(lowerCAmelCase_       )
		_lowercase   ="french fries"
		_lowercase   =sd_pipe(**lowerCAmelCase_       ,  negative_prompt=lowerCAmelCase_       )
		_lowercase   =output.images
		_lowercase   =image[0, -3:, -3:, -1]

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

		_lowercase   =np.array([0.4_7_7_1, 0.5_4_2_0, 0.4_6_8_3, 0.4_9_1_8, 0.5_6_3_6, 0.4_7_2_5, 0.5_2_3_0, 0.4_9_2_3, 0.5_0_1_5]       )

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

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



	"""simple docstring"""



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


	def __lowerCAmelCase      (   self       ,  lowerCAmelCase_=0       ):
		_lowercase   =torch.Generator(device=lowerCAmelCase_       ).manual_seed(lowerCAmelCase_       )
		_lowercase   ={
		    "prompt": "a photograph of an astronaut riding a horse",
		    "generator": generator,
		    "num_inference_steps": 10,
		    "guidance_scale": 7.5,
		    "output_type": "numpy",
		    "parallel": 3,
		    "debug": True,
		}
		return inputs


	def __lowerCAmelCase      (   self       ):
		_lowercase   ="stabilityai/stable-diffusion-2-base"
		_lowercase   =DDIMParallelScheduler.from_pretrained(lowerCAmelCase_       ,  subfolder="scheduler"       )
		_lowercase   =StableDiffusionParadigmsPipeline.from_pretrained(lowerCAmelCase_       ,  scheduler=lowerCAmelCase_       ,  safety_checker=lowerCAmelCase_       )
		pipe.to(lowerCAmelCase_       )
		pipe.set_progress_bar_config(disable=lowerCAmelCase_       )
		pipe.enable_attention_slicing()

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

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

		_lowercase   =np.array([0.9_6_2_2, 0.9_6_0_2, 0.9_7_4_8, 0.9_5_9_1, 0.9_6_3_0, 0.9_6_9_1, 0.9_6_6_1, 0.9_6_3_1, 0.9_7_4_1]       )

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












'''simple docstring'''







import unittest

from transformers import is_torch_available
from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device


if is_torch_available():
  import torch

  from transformers import CamembertModel




@require_torch
@require_sentencepiece
@require_tokenizers
class 					__UpperCAmelCase (		unittest.TestCase	):

      '''simple docstring'''





      @slow
      def 							lowerCamelCase     (					self						):
             UpperCAmelCase__	:   Optional[int]												=	CamembertModel.from_pretrained('''camembert-base'''						)
             model.to(_UpperCAmelCase						)

             UpperCAmelCase__	:   Optional[int]												=	torch.tensor(
                 [[5, 121, 11, 660, 16, 730, 2_5543, 110, 83, 6]]  ,		device=_UpperCAmelCase  ,		dtype=torch.long  ,		)  # J'aime le camembert !
             with torch.no_grad():
                    UpperCAmelCase__	:   Tuple												=	model(_UpperCAmelCase						)['''last_hidden_state''']
             UpperCAmelCase__	:   List[str]												=	torch.Size((1, 10, 768)						)
             self.assertEqual(output.shape  ,		_UpperCAmelCase						)
             # compare the actual values for a slice.
             UpperCAmelCase__	:   List[Any]												=	torch.tensor(
                 [[[-0.02_54, 0.02_35, 0.10_27], [0.06_06, -0.18_11, -0.04_18], [-0.15_61, -0.11_27, 0.26_87]]]  ,		device=_UpperCAmelCase  ,		dtype=torch.float  ,		)
             # camembert = torch.hub.load('pytorch/fairseq', 'camembert.v0')
             # camembert.eval()
             # expected_slice = roberta.model.forward(input_ids)[0][:, :3, :3].detach()

             self.assertTrue(torch.allclose(output[:, :3, :3]  ,		_UpperCAmelCase  ,		atol=1E-4						)						)