




'''simple docstring'''





import logging
from pathlib import Path

import numpy as np
import pytorch_lightning as pl
import torch
from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint
from pytorch_lightning.utilities import rank_zero_only
from utils_rag import save_json


def 					UpperCamelCase_(     snake_case							:	List[Any]					):

							'''simple docstring'''






							snake_case_      =				filter(lambda snake_case					: p.requires_grad							,    model.parameters()					)
							snake_case_      =				sum([np.prod(p.size()					) for p in model_parameters]					)
							return params


_SCREAMING_SNAKE_CASE							:       Union[str, Any]						=			logging.getLogger(__name__)


def 					UpperCamelCase_(     snake_case							:	List[str]							,    snake_case							:	Tuple					):

							'''simple docstring'''






							if metric == "rouge2":
														snake_case_      =				"{val_avg_rouge2:.4f}-{step_count}"
							elif metric == "bleu":
														snake_case_      =				"{val_avg_bleu:.4f}-{step_count}"
							elif metric == "em":
														snake_case_      =				"{val_avg_em:.4f}-{step_count}"
							elif metric == "loss":
														snake_case_      =				"{val_avg_loss:.4f}-{step_count}"
							else:
														raise NotImplementedError(
														    f'seq2seq callbacks only support rouge2 and bleu, got {metric}, You can make your own by adding to this'
														    " function."					)

							snake_case_      =				ModelCheckpoint(
							    dirpath=snake_case							,    filename=snake_case							,    monitor=f'val_{metric}'							,    mode="max"							,    save_top_k=1							,    every_n_epochs=1							,    )

							return checkpoint_callback


def 					UpperCamelCase_(     snake_case							:	Dict							,    snake_case							:	List[Any]					):

							'''simple docstring'''






							return EarlyStopping(
							    monitor=f'val_{metric}'							,    mode="min" if "loss" in metric else "max"							,    patience=snake_case							,    verbose=snake_case							,    )




class 			_snake_case		(     pl.Callback							):




			def        lowerCAmelCase__    ( self    ,							a__    ,							a__							)    ->    List[str]:

										'''simple docstring'''




										snake_case_      =				{F'lr_group_{i}': param["lr"] for i, param in enumerate(pl_module.trainer.optimizers[0].param_groups							)}
										pl_module.logger.log_metrics(a__							)




			@rank_zero_only
			def        lowerCAmelCase__    ( self    ,							a__    ,							a__    ,							a__    ,							a__=True							)    ->    None:

										'''simple docstring'''




										logger.info(F'***** {type_path} results at step {trainer.global_step:05d} *****'							)
										snake_case_      =				trainer.callback_metrics
										trainer.logger.log_metrics({k: v for k, v in metrics.items() if k not in ["log", "progress_bar", "preds"]}							)
										# Log results
										snake_case_      =				Path(pl_module.hparams.output_dir							)
										if type_path == "test":
																	snake_case_      =				od / "test_results.txt"
																	snake_case_      =				od / "test_generations.txt"
										else:
																	# this never gets hit. I prefer not to save intermediate generations, and results are in metrics.json
																	# If people want this it will be easy enough to add back.
																	snake_case_      =				od / F'{type_path}_results/{trainer.global_step:05d}.txt'
																	snake_case_      =				od / F'{type_path}_generations/{trainer.global_step:05d}.txt'
																	results_file.parent.mkdir(exist_ok=a__							)
																	generations_file.parent.mkdir(exist_ok=a__							)
										with open(a__    ,							"a+"							) as writer:
																	for key in sorted(a__							):
																								if key in ["log", "progress_bar", "preds"]:
																															continue
																								snake_case_      =				metrics[key]
																								if isinstance(a__    ,							torch.Tensor							):
																															snake_case_      =				val.item()
																								snake_case_      =				F'{key}: {val:.6f}\n'
																								writer.write(a__							)

										if not save_generations:
																	return

										if "preds" in metrics:
																	snake_case_      =				"\n".join(metrics["preds"]							)
																	generations_file.open("w+"							).write(a__							)




			@rank_zero_only
			def        lowerCAmelCase__    ( self    ,							a__    ,							a__							)    ->    Optional[Any]:

										'''simple docstring'''




										try:
																	snake_case_      =				pl_module.model.model.num_parameters()
										except AttributeError:
																	snake_case_      =				pl_module.model.num_parameters()

										snake_case_      =				count_trainable_parameters(a__							)
										# mp stands for million parameters
										trainer.logger.log_metrics({"n_params": npars, "mp": npars / 1e6, "grad_mp": n_trainable_pars / 1e6}							)




			@rank_zero_only
			def        lowerCAmelCase__    ( self    ,							a__    ,							a__							)    ->    int:

										'''simple docstring'''




										save_json(pl_module.metrics    ,							pl_module.metrics_save_path							)
										return self._write_logs(a__    ,							a__    ,							"test"							)




			@rank_zero_only
			def        lowerCAmelCase__    ( self    ,							a__    ,							a__							)    ->    List[Any]:

										'''simple docstring'''




										save_json(pl_module.metrics    ,							pl_module.metrics_save_path							)
										# Uncommenting this will save val generations
										# return self._write_logs(trainer, pl_module, "valid")










'''simple docstring'''





import gc
import random
import unittest

import torch

from diffusers import (
    IFImgaImgPipeline,
    IFImgaImgSuperResolutionPipeline,
    IFInpaintingPipeline,
    IFInpaintingSuperResolutionPipeline,
    IFPipeline,
    IFSuperResolutionPipeline,
)
from diffusers.models.attention_processor import AttnAddedKVProcessor
from diffusers.utils.import_utils import is_xformers_available
from diffusers.utils.testing_utils import floats_tensor, load_numpy, require_torch_gpu, skip_mps, slow, torch_device

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




@skip_mps
class 			_snake_case		(     lowercase_						,						lowercase_						,						unittest.TestCase							):
			lowerCAmelCase_					:				List[str]							=   IFPipeline
			lowerCAmelCase_					:				int							=   TEXT_TO_IMAGE_PARAMS - {"width", "height", "latents"}
			lowerCAmelCase_					:				Optional[int]							=   TEXT_TO_IMAGE_BATCH_PARAMS
			lowerCAmelCase_					:				List[Any]							=   PipelineTesterMixin.required_optional_params - {"latents"}




			def        lowerCAmelCase__    ( self							)    ->    Optional[Any]:

										'''simple docstring'''




										return self._get_dummy_components()




			def        lowerCAmelCase__    ( self    ,							a__    ,							a__=0							)    ->    str:

										'''simple docstring'''




										if str(a__							).startswith("mps"							):
																	snake_case_      =				torch.manual_seed(a__							)
										else:
																	snake_case_      =				torch.Generator(device=a__							).manual_seed(a__							)

										snake_case_      =				{
										    "prompt": "A painting of a squirrel eating a burger",
										    "generator": generator,
										    "num_inference_steps": 2,
										    "output_type": "numpy",
										}

										return inputs




			def        lowerCAmelCase__    ( self							)    ->    List[str]:

										'''simple docstring'''




										self._test_save_load_optional_components()




			@unittest.skipIf(torch_device != "cuda"    ,							reason="float16 requires CUDA"							)
			def        lowerCAmelCase__    ( self							)    ->    str:

										'''simple docstring'''




										super().test_save_load_floataa(expected_max_diff=1e-1							)




			def        lowerCAmelCase__    ( self							)    ->    List[Any]:

										'''simple docstring'''




										self._test_attention_slicing_forward_pass(expected_max_diff=1e-2							)




			def        lowerCAmelCase__    ( self							)    ->    int:

										'''simple docstring'''




										self._test_save_load_local()




			def        lowerCAmelCase__    ( self							)    ->    int:

										'''simple docstring'''




										self._test_inference_batch_single_identical(
										    expected_max_diff=1e-2    ,							)




			@unittest.skipIf(
			    torch_device != "cuda" or not is_xformers_available()    ,							reason="XFormers attention is only available with CUDA and `xformers` installed"    ,							)
			def        lowerCAmelCase__    ( self							)    ->    List[str]:

										'''simple docstring'''




										self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3							)




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




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

										'''simple docstring'''




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




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

										'''simple docstring'''




										snake_case_      =				IFPipeline.from_pretrained("DeepFloyd/IF-I-XL-v1.0"    ,							variant="fp16"    ,							torch_dtype=torch.floataa							)

										snake_case_      =				IFSuperResolutionPipeline.from_pretrained(
										    "DeepFloyd/IF-II-L-v1.0"    ,							variant="fp16"    ,							torch_dtype=torch.floataa    ,							text_encoder=a__    ,							tokenizer=a__							)

										# pre compute text embeddings and remove T5 to save memory

										pipe_a.text_encoder.to("cuda"							)

										snake_case_ ,				snake_case_      =				pipe_a.encode_prompt("anime turtle"    ,							device="cuda"							)

										del pipe_a.tokenizer
										del pipe_a.text_encoder
										gc.collect()

										snake_case_      =				None
										snake_case_      =				None

										pipe_a.enable_model_cpu_offload()
										pipe_a.enable_model_cpu_offload()

										pipe_a.unet.set_attn_processor(AttnAddedKVProcessor()							)
										pipe_a.unet.set_attn_processor(AttnAddedKVProcessor()							)

										self._test_if(a__    ,							a__    ,							a__    ,							a__							)

										pipe_a.remove_all_hooks()
										pipe_a.remove_all_hooks()

										# img2img

										snake_case_      =				IFImgaImgPipeline(**pipe_a.components							)
										snake_case_      =				IFImgaImgSuperResolutionPipeline(**pipe_a.components							)

										pipe_a.enable_model_cpu_offload()
										pipe_a.enable_model_cpu_offload()

										pipe_a.unet.set_attn_processor(AttnAddedKVProcessor()							)
										pipe_a.unet.set_attn_processor(AttnAddedKVProcessor()							)

										self._test_if_imgaimg(a__    ,							a__    ,							a__    ,							a__							)

										pipe_a.remove_all_hooks()
										pipe_a.remove_all_hooks()

										# inpainting

										snake_case_      =				IFInpaintingPipeline(**pipe_a.components							)
										snake_case_      =				IFInpaintingSuperResolutionPipeline(**pipe_a.components							)

										pipe_a.enable_model_cpu_offload()
										pipe_a.enable_model_cpu_offload()

										pipe_a.unet.set_attn_processor(AttnAddedKVProcessor()							)
										pipe_a.unet.set_attn_processor(AttnAddedKVProcessor()							)

										self._test_if_inpainting(a__    ,							a__    ,							a__    ,							a__							)




			def        lowerCAmelCase__    ( self    ,							a__    ,							a__    ,							a__    ,							a__							)    ->    Dict:

										'''simple docstring'''




										_start_torch_memory_measurement()

										snake_case_      =				torch.Generator(device="cpu"							).manual_seed(0							)
										snake_case_      =				pipe_a(
										    prompt_embeds=a__    ,							negative_prompt_embeds=a__    ,							num_inference_steps=2    ,							generator=a__    ,							output_type="np"    ,							)

										snake_case_      =				output.images[0]

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

										snake_case_      =				torch.cuda.max_memory_allocated()
										assert mem_bytes < 13 * 10**9

										snake_case_      =				load_numpy(
										    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if.npy"							)
										assert_mean_pixel_difference(a__    ,							a__							)

										# pipeline 2

										_start_torch_memory_measurement()

										snake_case_      =				torch.Generator(device="cpu"							).manual_seed(0							)

										snake_case_      =				floats_tensor((1, 3, 64, 64)    ,							rng=random.Random(0							)							).to(a__							)

										snake_case_      =				pipe_a(
										    prompt_embeds=a__    ,							negative_prompt_embeds=a__    ,							image=a__    ,							generator=a__    ,							num_inference_steps=2    ,							output_type="np"    ,							)

										snake_case_      =				output.images[0]

										assert image.shape == (256, 256, 3)

										snake_case_      =				torch.cuda.max_memory_allocated()
										assert mem_bytes < 4 * 10**9

										snake_case_      =				load_numpy(
										    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_superresolution_stage_II.npy"							)
										assert_mean_pixel_difference(a__    ,							a__							)




			def        lowerCAmelCase__    ( self    ,							a__    ,							a__    ,							a__    ,							a__							)    ->    Dict:

										'''simple docstring'''




										_start_torch_memory_measurement()

										snake_case_      =				floats_tensor((1, 3, 64, 64)    ,							rng=random.Random(0							)							).to(a__							)

										snake_case_      =				torch.Generator(device="cpu"							).manual_seed(0							)

										snake_case_      =				pipe_a(
										    prompt_embeds=a__    ,							negative_prompt_embeds=a__    ,							image=a__    ,							num_inference_steps=2    ,							generator=a__    ,							output_type="np"    ,							)

										snake_case_      =				output.images[0]

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

										snake_case_      =				torch.cuda.max_memory_allocated()
										assert mem_bytes < 10 * 10**9

										snake_case_      =				load_numpy(
										    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_img2img.npy"							)
										assert_mean_pixel_difference(a__    ,							a__							)

										# pipeline 2

										_start_torch_memory_measurement()

										snake_case_      =				torch.Generator(device="cpu"							).manual_seed(0							)

										snake_case_      =				floats_tensor((1, 3, 256, 256)    ,							rng=random.Random(0							)							).to(a__							)
										snake_case_      =				floats_tensor((1, 3, 64, 64)    ,							rng=random.Random(0							)							).to(a__							)

										snake_case_      =				pipe_a(
										    prompt_embeds=a__    ,							negative_prompt_embeds=a__    ,							image=a__    ,							original_image=a__    ,							generator=a__    ,							num_inference_steps=2    ,							output_type="np"    ,							)

										snake_case_      =				output.images[0]

										assert image.shape == (256, 256, 3)

										snake_case_      =				torch.cuda.max_memory_allocated()
										assert mem_bytes < 4 * 10**9

										snake_case_      =				load_numpy(
										    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_img2img_superresolution_stage_II.npy"							)
										assert_mean_pixel_difference(a__    ,							a__							)




			def        lowerCAmelCase__    ( self    ,							a__    ,							a__    ,							a__    ,							a__							)    ->    str:

										'''simple docstring'''




										_start_torch_memory_measurement()

										snake_case_      =				floats_tensor((1, 3, 64, 64)    ,							rng=random.Random(0							)							).to(a__							)
										snake_case_      =				floats_tensor((1, 3, 64, 64)    ,							rng=random.Random(1							)							).to(a__							)

										snake_case_      =				torch.Generator(device="cpu"							).manual_seed(0							)
										snake_case_      =				pipe_a(
										    prompt_embeds=a__    ,							negative_prompt_embeds=a__    ,							image=a__    ,							mask_image=a__    ,							num_inference_steps=2    ,							generator=a__    ,							output_type="np"    ,							)

										snake_case_      =				output.images[0]

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

										snake_case_      =				torch.cuda.max_memory_allocated()
										assert mem_bytes < 10 * 10**9

										snake_case_      =				load_numpy(
										    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_inpainting.npy"							)
										assert_mean_pixel_difference(a__    ,							a__							)

										# pipeline 2

										_start_torch_memory_measurement()

										snake_case_      =				torch.Generator(device="cpu"							).manual_seed(0							)

										snake_case_      =				floats_tensor((1, 3, 64, 64)    ,							rng=random.Random(0							)							).to(a__							)
										snake_case_      =				floats_tensor((1, 3, 256, 256)    ,							rng=random.Random(0							)							).to(a__							)
										snake_case_      =				floats_tensor((1, 3, 256, 256)    ,							rng=random.Random(1							)							).to(a__							)

										snake_case_      =				pipe_a(
										    prompt_embeds=a__    ,							negative_prompt_embeds=a__    ,							image=a__    ,							mask_image=a__    ,							original_image=a__    ,							generator=a__    ,							num_inference_steps=2    ,							output_type="np"    ,							)

										snake_case_      =				output.images[0]

										assert image.shape == (256, 256, 3)

										snake_case_      =				torch.cuda.max_memory_allocated()
										assert mem_bytes < 4 * 10**9

										snake_case_      =				load_numpy(
										    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_inpainting_superresolution_stage_II.npy"							)
										assert_mean_pixel_difference(a__    ,							a__							)


def 					UpperCamelCase_(     ):

							'''simple docstring'''






							torch.cuda.empty_cache()
							torch.cuda.reset_max_memory_allocated()
							torch.cuda.reset_peak_memory_stats()




