




from dataclasses import dataclass
from typing import Optional, Tuple, Union

import torch
import torch.nn as nn

from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import BaseOutput
from .embeddings import GaussianFourierProjection, TimestepEmbedding, Timesteps
from .modeling_utils import ModelMixin
from .unet_ad_blocks import UNetMidBlockaD, get_down_block, get_up_block



@dataclass
class       lowercase_		(a__   ):
						lowerCAmelCase__ 			=42



class       lowercase_		(a__       ,  a__   ):



						@register_to_config
						def __init__( self  :      str				,       snake_case__  :      Tuple = None				,       snake_case__  :      Optional[Any] = 3				,       snake_case__  :      Any = 3				,       snake_case__  :      Optional[int] = False				,       snake_case__  :      List[str] = "positional"				,       snake_case__  :      Any = 0				,       snake_case__  :      List[Any] = True				,       snake_case__  :      Union[str, Any] = ("DownBlock2D", "AttnDownBlock2D", "AttnDownBlock2D", "AttnDownBlock2D")				,       snake_case__  :      str = ("AttnUpBlock2D", "AttnUpBlock2D", "AttnUpBlock2D", "UpBlock2D")				,       snake_case__  :      Dict = (2_24, 4_48, 6_72, 8_96)				,       snake_case__  :      Any = 2				,       snake_case__  :      str = 1				,       snake_case__  :      Optional[int] = 1				,       snake_case__  :      Optional[Any] = "conv"				,       snake_case__  :      int = "conv"				,       snake_case__  :      int = "silu"				,       snake_case__  :      int = 8				,       snake_case__  :      Optional[Any] = 32				,       snake_case__  :      int = 1e-5				,       snake_case__  :      Union[str, Any] = "default"				,       snake_case__  :      List[Any] = True				,       snake_case__  :      int = None				,       snake_case__  :      Tuple = None				,       ):

								"""simple docstring"""

								super().__init__()

								SCREAMING_SNAKE_CASE_							=       sample_size
								SCREAMING_SNAKE_CASE_							=       block_out_channels[0] * 4

								# Check inputs
								if len(__A     ) != len(__A     ):
										raise ValueError(
										    f'''Must provide the same number of `down_block_types` as `up_block_types`. `down_block_types`: {down_block_types}. `up_block_types`: {up_block_types}.'''     )

								if len(__A     ) != len(__A     ):
										raise ValueError(
										    f'''Must provide the same number of `block_out_channels` as `down_block_types`. `block_out_channels`: {block_out_channels}. `down_block_types`: {down_block_types}.'''     )

								# input
								SCREAMING_SNAKE_CASE_							=       nn.Convad(__A				,       block_out_channels[0]				,       kernel_size=3				,       padding=(1, 1)     )

								# time
								if time_embedding_type == "fourier":
										SCREAMING_SNAKE_CASE_							=       GaussianFourierProjection(embedding_size=block_out_channels[0]				,       scale=16     )
										SCREAMING_SNAKE_CASE_							=       2 * block_out_channels[0]
								elif time_embedding_type == "positional":
										SCREAMING_SNAKE_CASE_							=       Timesteps(block_out_channels[0]				,       __A				,       __A     )
										SCREAMING_SNAKE_CASE_							=       block_out_channels[0]

								SCREAMING_SNAKE_CASE_							=       TimestepEmbedding(__A				,       __A     )

								# class embedding
								if class_embed_type is None and num_class_embeds is not None:
										SCREAMING_SNAKE_CASE_							=       nn.Embedding(__A				,       __A     )
								elif class_embed_type == "timestep":
										SCREAMING_SNAKE_CASE_							=       TimestepEmbedding(__A				,       __A     )
								elif class_embed_type == "identity":
										SCREAMING_SNAKE_CASE_							=       nn.Identity(__A				,       __A     )
								else:
										SCREAMING_SNAKE_CASE_							=       None

								SCREAMING_SNAKE_CASE_							=       nn.ModuleList([]     )
								SCREAMING_SNAKE_CASE_							=       None
								SCREAMING_SNAKE_CASE_							=       nn.ModuleList([]     )

								# down
								SCREAMING_SNAKE_CASE_							=       block_out_channels[0]
								for i, down_block_type in enumerate(__A     ):
										SCREAMING_SNAKE_CASE_							=       output_channel
										SCREAMING_SNAKE_CASE_							=       block_out_channels[i]
										SCREAMING_SNAKE_CASE_							=       i == len(__A     ) - 1

										SCREAMING_SNAKE_CASE_							=       get_down_block(
										    __A				,       num_layers=__A				,       in_channels=__A				,       out_channels=__A				,       temb_channels=__A				,       add_downsample=not is_final_block				,       resnet_eps=__A				,       resnet_act_fn=__A				,       resnet_groups=__A				,       attention_head_dim=attention_head_dim if attention_head_dim is not None else output_channel				,       downsample_padding=__A				,       resnet_time_scale_shift=__A				,       downsample_type=__A				,       )
										self.down_blocks.append(__A     )

								# mid
								SCREAMING_SNAKE_CASE_							=       UNetMidBlockaD(
								    in_channels=block_out_channels[-1]				,       temb_channels=__A				,       resnet_eps=__A				,       resnet_act_fn=__A				,       output_scale_factor=__A				,       resnet_time_scale_shift=__A				,       attention_head_dim=attention_head_dim if attention_head_dim is not None else block_out_channels[-1]				,       resnet_groups=__A				,       add_attention=__A				,       )

								# up
								SCREAMING_SNAKE_CASE_							=       list(reversed(__A     )     )
								SCREAMING_SNAKE_CASE_							=       reversed_block_out_channels[0]
								for i, up_block_type in enumerate(__A     ):
										SCREAMING_SNAKE_CASE_							=       output_channel
										SCREAMING_SNAKE_CASE_							=       reversed_block_out_channels[i]
										SCREAMING_SNAKE_CASE_							=       reversed_block_out_channels[min(i + 1				,       len(__A     ) - 1     )]

										SCREAMING_SNAKE_CASE_							=       i == len(__A     ) - 1

										SCREAMING_SNAKE_CASE_							=       get_up_block(
										    __A				,       num_layers=layers_per_block + 1				,       in_channels=__A				,       out_channels=__A				,       prev_output_channel=__A				,       temb_channels=__A				,       add_upsample=not is_final_block				,       resnet_eps=__A				,       resnet_act_fn=__A				,       resnet_groups=__A				,       attention_head_dim=attention_head_dim if attention_head_dim is not None else output_channel				,       resnet_time_scale_shift=__A				,       upsample_type=__A				,       )
										self.up_blocks.append(__A     )
										SCREAMING_SNAKE_CASE_							=       output_channel

								# out
								SCREAMING_SNAKE_CASE_							=       norm_num_groups if norm_num_groups is not None else min(block_out_channels[0] // 4				,       32     )
								SCREAMING_SNAKE_CASE_							=       nn.GroupNorm(num_channels=block_out_channels[0]				,       num_groups=__A				,       eps=__A     )
								SCREAMING_SNAKE_CASE_							=       nn.SiLU()
								SCREAMING_SNAKE_CASE_							=       nn.Convad(block_out_channels[0]				,       __A				,       kernel_size=3				,       padding=1     )






						def   __a				( self  :      Tuple				,       snake_case__  :      List[Any]				,       snake_case__  :      Optional[Any]				,       snake_case__  :      Dict = None				,       snake_case__  :      List[Any] = True				,       ):

								"""simple docstring"""

								if self.config.center_input_sample:
										SCREAMING_SNAKE_CASE_							=       2 * sample - 1.0

								# 1. time
								SCREAMING_SNAKE_CASE_							=       timestep
								if not torch.is_tensor(__A     ):
										SCREAMING_SNAKE_CASE_							=       torch.tensor([timesteps]				,       dtype=torch.long				,       device=sample.device     )
								elif torch.is_tensor(__A     ) and len(timesteps.shape     ) == 0:
										SCREAMING_SNAKE_CASE_							=       timesteps[None].to(sample.device     )

								# broadcast to batch dimension in a way that's compatible with ONNX/Core ML
								SCREAMING_SNAKE_CASE_							=       timesteps * torch.ones(sample.shape[0]				,       dtype=timesteps.dtype				,       device=timesteps.device     )

								SCREAMING_SNAKE_CASE_							=       self.time_proj(__A     )

								# timesteps does not contain any weights and will always return f32 tensors
								# but time_embedding might actually be running in fp16. so we need to cast here.
								# there might be better ways to encapsulate this.
								SCREAMING_SNAKE_CASE_							=       t_emb.to(dtype=self.dtype     )
								SCREAMING_SNAKE_CASE_							=       self.time_embedding(__A     )

								if self.class_embedding is not None:
										if class_labels is None:
												raise ValueError('class_labels should be provided when doing class conditioning'     )

										if self.config.class_embed_type == "timestep":
												SCREAMING_SNAKE_CASE_							=       self.time_proj(__A     )

										SCREAMING_SNAKE_CASE_							=       self.class_embedding(__A     ).to(dtype=self.dtype     )
										SCREAMING_SNAKE_CASE_							=       emb + class_emb

								# 2. pre-process
								SCREAMING_SNAKE_CASE_							=       sample
								SCREAMING_SNAKE_CASE_							=       self.conv_in(__A     )

								# 3. down
								SCREAMING_SNAKE_CASE_							=       (sample,)
								for downsample_block in self.down_blocks:
										if hasattr(__A				,       'skip_conv'     ):
												SCREAMING_SNAKE_CASE_							=       downsample_block(
												    hidden_states=__A				,       temb=__A				,       skip_sample=__A     )
										else:
												SCREAMING_SNAKE_CASE_							=       downsample_block(hidden_states=__A				,       temb=__A     )

										down_block_res_samples += res_samples

								# 4. mid
								SCREAMING_SNAKE_CASE_							=       self.mid_block(__A				,       __A     )

								# 5. up
								SCREAMING_SNAKE_CASE_							=       None
								for upsample_block in self.up_blocks:
										SCREAMING_SNAKE_CASE_							=       down_block_res_samples[-len(upsample_block.resnets     ) :]
										SCREAMING_SNAKE_CASE_							=       down_block_res_samples[: -len(upsample_block.resnets     )]

										if hasattr(__A				,       'skip_conv'     ):
												SCREAMING_SNAKE_CASE_							=       upsample_block(__A				,       __A				,       __A				,       __A     )
										else:
												SCREAMING_SNAKE_CASE_							=       upsample_block(__A				,       __A				,       __A     )

        # 6. post-process
								SCREAMING_SNAKE_CASE_							=       self.conv_norm_out(__A     )
								SCREAMING_SNAKE_CASE_							=       self.conv_act(__A     )
								SCREAMING_SNAKE_CASE_							=       self.conv_out(__A     )

								if skip_sample is not None:
										sample += skip_sample

								if self.config.time_embedding_type == "fourier":
										SCREAMING_SNAKE_CASE_							=       timesteps.reshape((sample.shape[0], *([1] * len(sample.shape[1:]     )))     )
										SCREAMING_SNAKE_CASE_							=       sample / timesteps

								if not return_dict:
										return (sample,)

								return UNetaDOutput(sample=__A     )





import collections

from .utils import ExplicitEnum, is_torch_available, logging


if is_torch_available():
						import torch


SCREAMING_SNAKE_CASE:    Any											=   logging.get_logger(__name__)



class       lowercase_		:



						def __init__( self  :      Union[str, Any]				,       snake_case__  :      List[str]				,       snake_case__  :      Dict=21				,       snake_case__  :      List[str]=[]				,       snake_case__  :      List[str]=None     ):

								"""simple docstring"""

								SCREAMING_SNAKE_CASE_							=       model
								SCREAMING_SNAKE_CASE_							=       trace_batch_nums
								SCREAMING_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
								SCREAMING_SNAKE_CASE_							=       collections.deque([]				,       snake_case__     )
								SCREAMING_SNAKE_CASE_							=       []
								SCREAMING_SNAKE_CASE_							=       0
								SCREAMING_SNAKE_CASE_							=       0
								SCREAMING_SNAKE_CASE_							=       False
								SCREAMING_SNAKE_CASE_							=       '                 '

								self.analyse_model()

								self.register_forward_hook()



						def   __a				( self  :      Union[str, Any]				,       snake_case__  :      Optional[int]=None     ):

								"""simple docstring"""

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



						def   __a				( self  :      Union[str, Any]				,       snake_case__  :      Any     ):

								"""simple docstring"""

								self.frame.append(snake_case__     )



						def   __a				( self  :      Optional[int]     ):

								"""simple docstring"""

								print('\n'.join(self.frames     )     )
								SCREAMING_SNAKE_CASE_							=       []



						def   __a				( self  :      Dict     ):

								"""simple docstring"""

								SCREAMING_SNAKE_CASE_							=       []



						def   __a				( self  :      int     ):

								"""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'     )
								SCREAMING_SNAKE_CASE_							=       []



						def   __a				( self  :      str     ):

								"""simple docstring"""

								SCREAMING_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   __a				( self  :      List[str]				,       snake_case__  :      List[str]				,       snake_case__  :      Union[str, Any]     ):

								"""simple docstring"""

								if torch.is_tensor(snake_case__     ):
										self.expand_frame(get_abs_min_max(snake_case__				,       snake_case__     )     )
										if detect_overflow(snake_case__				,       snake_case__     ):
												SCREAMING_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   __a				( self  :      str     ):

								"""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   __a				( self  :      List[str]     ):

								"""simple docstring"""

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



						def   __a				( self  :      Optional[int]				,       snake_case__  :      int				,       snake_case__  :      List[Any]				,       snake_case__  :      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=snake_case__     ):
										self.analyse_variable(snake_case__				,       snake_case__     )

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

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

								self.save_frame()



						def   __a				( self  :      Tuple     ):

								"""simple docstring"""

								self.model.apply(self._register_forward_hook     )



						def   __a				( self  :      int				,       snake_case__  :      Optional[int]     ):

								"""simple docstring"""

								module.register_forward_hook(self.forward_hook     )






						def   __a				( self  :      Optional[Any]				,       snake_case__  :      str				,       snake_case__  :      Optional[Any]				,       snake_case__  :      Dict     ):

								"""simple docstring"""

								SCREAMING_SNAKE_CASE_							=       False

								SCREAMING_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
										SCREAMING_SNAKE_CASE_							=       True

								self.create_frame(snake_case__				,       snake_case__				,       snake_case__     )

								# 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 				_a       (				lowerCAmelCase						,	lowerCAmelCase   )->  Union[str, Any]:
		SCREAMING_SNAKE_CASE_							=       var.abs()
		return F'''{abs_var.min():8.2e} {abs_var.max():8.2e} {ctx}'''


def 				_a       (				lowerCAmelCase						,	lowerCAmelCase   )->  int:
		SCREAMING_SNAKE_CASE_							=       False
		if torch.isnan(lowerCAmelCase   ).any().item():
				SCREAMING_SNAKE_CASE_							=       True
				print(F'''{ctx} has nans'''   )
		if torch.isinf(lowerCAmelCase   ).any().item():
				SCREAMING_SNAKE_CASE_							=       True
				print(F'''{ctx} has infs'''   )

		# if needed to monitor large elements can enable the following
		if 0:  # and detected:
				SCREAMING_SNAKE_CASE_							=       var[torch.ge(var.abs()						,	100   )]
				if naaa.numel() > 0:
						print(F'''{ctx}:  n100={naaa.numel()}'''   )
				SCREAMING_SNAKE_CASE_							=       var[torch.ge(var.abs()						,	1000   )]
				if naaaa.numel() > 0:
						print(F'''{ctx}: n1000={naaaa.numel()}'''   )
				SCREAMING_SNAKE_CASE_							=       var[torch.ge(var.abs()						,	10000   )]
				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       lowercase_		(SCREAMING_SNAKE_CASE__   ):
						lowerCAmelCase__ 			="underflow_overflow"
						lowerCAmelCase__ 			="tpu_metrics_debug"