




'''simple docstring'''

import collections

from .utils import ExplicitEnum, is_torch_available, logging


if is_torch_available():
		import torch


a__         =     logging.get_logger(__name__)





class __magic_name__:






						def __init__(   self						:						str					,   __UpperCamelCase						:						str					,   __UpperCamelCase						:						Optional[Any]=2_1					,   __UpperCamelCase						:						Optional[Any]=[]					,   __UpperCamelCase						:						List[str]=None       ):



									'''simple docstring'''






									snake_case__          =						model
									snake_case__          =						trace_batch_nums
									snake_case__          =						abort_after_batch_num

									# keep a LIFO buffer of frames to dump as soon as inf/nan is encountered to give context to the problem emergence
									snake_case__          =						collections.deque([]					,   a_       )
									snake_case__          =						[]
									snake_case__          =						0
									snake_case__          =						0
									snake_case__          =						False
									snake_case__          =						"""                 """

									self.analyse_model()

									self.register_forward_hook()






						def       __lowerCAmelCase(   self						:						Tuple					,   __UpperCamelCase						:						int=None       ):



									'''simple docstring'''






									if frame is not None:
												self.expand_frame(a_       )
									self.frames.append("""\n""".join(self.frame       )       )
									snake_case__          =						[]  # start a new frame






						def       __lowerCAmelCase(   self						:						Any					,   __UpperCamelCase						:						Optional[int]       ):



									'''simple docstring'''






									self.frame.append(a_       )






						def       __lowerCAmelCase(   self						:						Union[str, Any]       ):



									'''simple docstring'''






									print("""\n""".join(self.frames       )       )
									snake_case__          =						[]






						def       __lowerCAmelCase(   self						:						Optional[Any]       ):



									'''simple docstring'''






									snake_case__          =						[]






						def       __lowerCAmelCase(   self						:						Union[str, Any]       ):



									'''simple docstring'''






									print(f"""\nDetected inf/nan during batch_number={self.batch_number}"""       )
									print(f"""Last {len(self.frames       )} forward frames:"""       )
									print(f"""{"abs min":8} {"abs max":8} metadata"""       )
									print("""\n""".join(self.frames       )       )
									print("""\n\n"""       )
									snake_case__          =						[]






						def       __lowerCAmelCase(   self						:						Optional[int]       ):



									'''simple docstring'''






									snake_case__          =						{m: name for name, m in self.model.named_modules()}
									# self.longest_module_name = max(len(v) for v in self.module_names.values())






						def       __lowerCAmelCase(   self						:						Optional[int]					,   __UpperCamelCase						:						Union[str, Any]					,   __UpperCamelCase						:						List[str]       ):



									'''simple docstring'''






									if torch.is_tensor(a_       ):
												self.expand_frame(get_abs_min_max(a_					,   a_       )       )
												if detect_overflow(a_					,   a_       ):
															snake_case__          =						True
									elif var is None:
												self.expand_frame(f"""{"None":>17} {ctx}"""       )
									else:
												self.expand_frame(f"""{"not a tensor":>17} {ctx}"""       )






						def       __lowerCAmelCase(   self						:						Optional[int]       ):



									'''simple docstring'''






									self.expand_frame(f"""\n\n{self.prefix} *** Starting batch number={self.batch_number} ***"""       )
									self.expand_frame(f"""{"abs min":8} {"abs max":8} metadata"""       )






						def       __lowerCAmelCase(   self						:						Optional[Any]       ):



									'''simple docstring'''






									self.expand_frame(f"""{self.prefix} *** Finished batch number={self.batch_number-1} ***\n\n"""       )






						def       __lowerCAmelCase(   self						:						Dict					,   __UpperCamelCase						:						str					,   __UpperCamelCase						:						Optional[int]					,   __UpperCamelCase						:						List[str]       ):



									'''simple docstring'''






									self.expand_frame(f"""{self.prefix} {self.module_names[module]} {module.__class__.__name__}"""       )

									# params
									for name, p in module.named_parameters(recurse=a_       ):
												self.analyse_variable(a_					,   a_       )

									# inputs
									if isinstance(a_					,   a_       ):
												for i, x in enumerate(a_       ):
															self.analyse_variable(a_					,   f"""input[{i}]"""       )
									else:
												self.analyse_variable(a_					,   """input"""       )

									# outputs
									if isinstance(a_					,   a_       ):
												for i, x in enumerate(a_       ):
															# possibly a tuple of tuples
															if isinstance(a_					,   a_       ):
																		for j, y in enumerate(a_       ):
																					self.analyse_variable(a_					,   f"""output[{i}][{j}]"""       )
															else:
																		self.analyse_variable(a_					,   f"""output[{i}]"""       )
									else:
												self.analyse_variable(a_					,   """output"""       )

									self.save_frame()






						def       __lowerCAmelCase(   self						:						str       ):



									'''simple docstring'''






									self.model.apply(self._register_forward_hook       )






						def       __lowerCAmelCase(   self						:						List[Any]					,   __UpperCamelCase						:						Tuple       ):



									'''simple docstring'''






									module.register_forward_hook(self.forward_hook       )







						def       __lowerCAmelCase(   self						:						str					,   __UpperCamelCase						:						List[Any]					,   __UpperCamelCase						:						Tuple					,   __UpperCamelCase						:						Any       ):



									'''simple docstring'''






									snake_case__          =						False

									snake_case__          =						True if self.batch_number in self.trace_batch_nums else False
									if trace_mode:
												self.reset_saved_frames()

									if self.total_calls == 0:
												self.batch_start_frame()
									self.total_calls += 1

									# count batch numbers - the very first forward hook of the batch will be called when the
									# batch completes - i.e. it gets called very last - we know this batch has finished
									if module == self.model:
												self.batch_number += 1
												snake_case__          =						True

									self.create_frame(a_					,   a_					,   a_       )

									# if last_frame_of_batch:
									#     self.batch_end_frame()

									if trace_mode:
												self.trace_frames()

									if last_frame_of_batch:
												self.batch_start_frame()

									if self.detected_overflow and not trace_mode:
												self.dump_saved_frames()

												# now we can abort, as it's pointless to continue running
												raise ValueError(
												    """DebugUnderflowOverflow: inf/nan detected, aborting as there is no point running further. """
												    """Please scroll up above this traceback to see the activation values prior to this event."""       )

									# abort after certain batch if requested to do so
									if self.abort_after_batch_num is not None and self.batch_number > self.abort_after_batch_num:
												raise ValueError(
												    f"""DebugUnderflowOverflow: aborting after {self.batch_number} batches due to"""
												    f""" `abort_after_batch_num={self.abort_after_batch_num}` arg"""       )







def    snake_case__     (  a       ,      a	)			->       Optional[Any]:





			'''simple docstring'''






			snake_case__          =						var.abs()
			return F"""{abs_var.min():8.2e} {abs_var.max():8.2e} {ctx}"""




def    snake_case__     (  a       ,      a	)			->       List[str]:





			'''simple docstring'''






			snake_case__          =						False
			if torch.isnan(_UpperCamelCase	).any().item():
						snake_case__          =						True
						print(F"""{ctx} has nans"""	)
			if torch.isinf(_UpperCamelCase	).any().item():
						snake_case__          =						True
						print(F"""{ctx} has infs"""	)

			# if needed to monitor large elements can enable the following
			if 0:  # and detected:
						snake_case__          =						var[torch.ge(var.abs()       ,      100	)]
						if naaa.numel() > 0:
									print(F"""{ctx}:  n100={naaa.numel()}"""	)
						snake_case__          =						var[torch.ge(var.abs()       ,      1000	)]
						if naaaa.numel() > 0:
									print(F"""{ctx}: n1000={naaaa.numel()}"""	)
						snake_case__          =						var[torch.ge(var.abs()       ,      1_0000	)]
						if naaaaa.numel() > 0:
									print(F"""{ctx}: n10000={naaaaa.numel()}"""	)

			if 0:
						print(F"""min={var.min():9.2e} max={var.max():9.2e}"""	)

			if 0:
						print(F"""min={var.min():9.2e} max={var.max():9.2e} var={var.var():9.2e} mean={var.mean():9.2e} ({ctx})"""	)

			return detected





class __magic_name__(						SCREAMING_SNAKE_CASE__      ):
						UpperCAmelCase_		:					str    =  'underflow_overflow'
						UpperCAmelCase_		:					Any    =  'tpu_metrics_debug'



'''simple docstring'''

import random
import unittest

import numpy as np
import torch
from PIL import Image
from torch import nn
from transformers import (
    CLIPImageProcessor,
    CLIPTextConfig,
    CLIPTextModelWithProjection,
    CLIPTokenizer,
    CLIPVisionConfig,
    CLIPVisionModelWithProjection,
)

from diffusers import KandinskyVaaPriorEmbaEmbPipeline, PriorTransformer, UnCLIPScheduler
from diffusers.utils import floats_tensor, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, skip_mps

from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()







class 			UpperCAmelCase			(							SCREAMING_SNAKE_CASE__		,      unittest.TestCase):
 _lowerCamelCase			:       List[Any]            =       KandinskyVaaPriorEmbaEmbPipeline
 _lowerCamelCase			:       Tuple            =       ['prompt', 'image']
 _lowerCamelCase			:       List[str]            =       ['prompt', 'image']
 _lowerCamelCase			:       List[str]            =       [
     'num_images_per_prompt',
     'strength',
     'generator',
     'num_inference_steps',
     'latents',
     'negative_prompt',
     'guidance_scale',
     'output_type',
     'return_dict',
 ]
 _lowerCamelCase			:       List[str]            =       False

 @property
 def 		lowercase_    (			self			:						int       ):





    """simple docstring"""



    return 32

 @property
 def 		lowercase_    (			self			:						Union[str, Any]       ):





    """simple docstring"""



    return 32

 @property
 def 		lowercase_    (			self			:						Any       ):





    """simple docstring"""



    return self.time_input_dim

 @property
 def 		lowercase_    (			self			:						Dict       ):





    """simple docstring"""



    return self.time_input_dim * 4

 @property
 def 		lowercase_    (			self			:						str       ):





    """simple docstring"""



    return 100

 @property
 def 		lowercase_    (			self			:						Any       ):





    """simple docstring"""



    UpperCamelCase__			    =    CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"       )
    return tokenizer

 @property
 def 		lowercase_    (			self			:						Optional[int]       ):





    """simple docstring"""



    torch.manual_seed(0       )
    UpperCamelCase__			    =    CLIPTextConfig(
        bos_token_id=0,       eos_token_id=2,       hidden_size=self.text_embedder_hidden_size,       projection_dim=self.text_embedder_hidden_size,       intermediate_size=37,       layer_norm_eps=1e-0_5,       num_attention_heads=4,       num_hidden_layers=5,       pad_token_id=1,       vocab_size=1000,       )
    return CLIPTextModelWithProjection(a_       )

 @property
 def 		lowercase_    (			self			:						str       ):





    """simple docstring"""



    torch.manual_seed(0       )

    UpperCamelCase__			    =    {
        "num_attention_heads": 2,
        "attention_head_dim": 12,
        "embedding_dim": self.text_embedder_hidden_size,
        "num_layers": 1,
    }

    UpperCamelCase__			    =    PriorTransformer(**a_       )
    # clip_std and clip_mean is initialized to be 0 so PriorTransformer.post_process_latents will always return 0 - set clip_std to be 1 so it won't return 0
    UpperCamelCase__			    =    nn.Parameter(torch.ones(model.clip_std.shape       )       )
    return model

 @property
 def 		lowercase_    (			self			:						Any       ):





    """simple docstring"""



    torch.manual_seed(0       )
    UpperCamelCase__			    =    CLIPVisionConfig(
        hidden_size=self.text_embedder_hidden_size,       image_size=224,       projection_dim=self.text_embedder_hidden_size,       intermediate_size=37,       num_attention_heads=4,       num_channels=3,       num_hidden_layers=5,       patch_size=14,       )

    UpperCamelCase__			    =    CLIPVisionModelWithProjection(a_       )
    return model

 @property
 def 		lowercase_    (			self			:						Dict       ):





    """simple docstring"""



    UpperCamelCase__			    =    CLIPImageProcessor(
        crop_size=224,       do_center_crop=a_,       do_normalize=a_,       do_resize=a_,       image_mean=[0.48_145_466, 0.4_578_275, 0.40_821_073],       image_std=[0.26_862_954, 0.26_130_258, 0.27_577_711],       resample=3,       size=224,       )

    return image_processor

 def 		lowercase_    (			self			:						Optional[int]       ):





    """simple docstring"""



    UpperCamelCase__			    =    self.dummy_prior
    UpperCamelCase__			    =    self.dummy_image_encoder
    UpperCamelCase__			    =    self.dummy_text_encoder
    UpperCamelCase__			    =    self.dummy_tokenizer
    UpperCamelCase__			    =    self.dummy_image_processor

    UpperCamelCase__			    =    UnCLIPScheduler(
        variance_type="fixed_small_log",       prediction_type="sample",       num_train_timesteps=1000,       clip_sample=a_,       clip_sample_range=10.0,       )

    UpperCamelCase__			    =    {
        "prior": prior,
        "image_encoder": image_encoder,
        "text_encoder": text_encoder,
        "tokenizer": tokenizer,
        "scheduler": scheduler,
        "image_processor": image_processor,
    }

    return components

 def 		lowercase_    (			self			:						Union[str, Any],       a_			:						List[str],       a_			:						Union[str, Any]=0       ):





    """simple docstring"""



    if str(a_       ).startswith("mps"       ):
       UpperCamelCase__			    =    torch.manual_seed(a_       )
    else:
       UpperCamelCase__			    =    torch.Generator(device=a_       ).manual_seed(a_       )

    UpperCamelCase__			    =    floats_tensor((1, 3, 64, 64),       rng=random.Random(a_       )       ).to(a_       )
    UpperCamelCase__			    =    image.cpu().permute(0,       2,       3,       1       )[0]
    UpperCamelCase__			    =    Image.fromarray(np.uinta(a_       )       ).convert("RGB"       ).resize((256, 256)       )

    UpperCamelCase__			    =    {
        "prompt": "horse",
        "image": init_image,
        "strength": 0.5,
        "generator": generator,
        "guidance_scale": 4.0,
        "num_inference_steps": 2,
        "output_type": "np",
    }
    return inputs

 def 		lowercase_    (			self			:						Union[str, Any]       ):





    """simple docstring"""



    UpperCamelCase__			    =    "cpu"

    UpperCamelCase__			    =    self.get_dummy_components()

    UpperCamelCase__			    =    self.pipeline_class(**a_       )
    UpperCamelCase__			    =    pipe.to(a_       )

    pipe.set_progress_bar_config(disable=a_       )

    UpperCamelCase__			    =    pipe(**self.get_dummy_inputs(a_       )       )
    UpperCamelCase__			    =    output.image_embeds

    UpperCamelCase__			    =    pipe(
        **self.get_dummy_inputs(a_       ),       return_dict=a_,       )[0]

    UpperCamelCase__			    =    image[0, -10:]
    UpperCamelCase__			    =    image_from_tuple[0, -10:]

    assert image.shape == (1, 32)

    UpperCamelCase__			    =    np.array(
        [
            0.1_071_284,
            1.3_330_271,
            0.61_260_223,
            -0.6_691_065,
            -0.3_846_852,
            -1.0_303_661,
            0.22_716_111,
            0.03_348_901,
            0.30_040_675,
            -0.24_805_029,
        ]       )

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

 @skip_mps
 def 		lowercase_    (			self			:						Optional[int]       ):





    """simple docstring"""



    UpperCamelCase__			    =    torch_device == "cpu"
    UpperCamelCase__			    =    True
    UpperCamelCase__			    =    False

    self._test_inference_batch_single_identical(
        test_max_difference=a_,       relax_max_difference=a_,       test_mean_pixel_difference=a_,       )

 @skip_mps
 def 		lowercase_    (			self			:						Optional[int]       ):





    """simple docstring"""



    UpperCamelCase__			    =    torch_device == "cpu"
    UpperCamelCase__			    =    False

    self._test_attention_slicing_forward_pass(
        test_max_difference=a_,       test_mean_pixel_difference=a_,       )