




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 				__UpperCamelCase      (			__UpperCAmelCase	):





				'''simple docstring'''



				__a				:			torch.FloatTensor




class 				__UpperCamelCase      (			__UpperCAmelCase  ,       __UpperCAmelCase	):





				'''simple docstring'''



				@register_to_config
				def __init__(			self							,			UpperCAmelCase_ = None							,			UpperCAmelCase_ = 3							,			UpperCAmelCase_ = 3							,			UpperCAmelCase_ = False							,			UpperCAmelCase_ = "positional"							,			UpperCAmelCase_ = 0							,			UpperCAmelCase_ = True							,			UpperCAmelCase_ = ("DownBlock2D", "AttnDownBlock2D", "AttnDownBlock2D", "AttnDownBlock2D")							,			UpperCAmelCase_ = ("AttnUpBlock2D", "AttnUpBlock2D", "AttnUpBlock2D", "UpBlock2D")							,			UpperCAmelCase_ = (2_24, 4_48, 6_72, 8_96)							,			UpperCAmelCase_ = 2							,			UpperCAmelCase_ = 1							,			UpperCAmelCase_ = 1							,			UpperCAmelCase_ = "conv"							,			UpperCAmelCase_ = "conv"							,			UpperCAmelCase_ = "silu"							,			UpperCAmelCase_ = 8							,			UpperCAmelCase_ = 32							,			UpperCAmelCase_ = 1E-5							,			UpperCAmelCase_ = "default"							,			UpperCAmelCase_ = True							,			UpperCAmelCase_ = None							,			UpperCAmelCase_ = None							,			):
											super().__init__()

											lowerCAmelCase =		sample_size
											lowerCAmelCase =		block_out_channels[0] * 4

											# Check inputs
											if len(UpperCAmelCase_    ) != len(UpperCAmelCase_    ):
																		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(UpperCAmelCase_    ) != len(UpperCAmelCase_    ):
																		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
											lowerCAmelCase =		nn.Convad(UpperCAmelCase_							,			block_out_channels[0]							,			kernel_size=3							,			padding=(1, 1)    )

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

											lowerCAmelCase =		TimestepEmbedding(UpperCAmelCase_							,			UpperCAmelCase_    )

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

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

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

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

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

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

																		lowerCAmelCase =		i == len(UpperCAmelCase_    ) - 1

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

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






				def    __snake_case		(			self							,			UpperCAmelCase_							,			UpperCAmelCase_							,			UpperCAmelCase_ = None							,			UpperCAmelCase_ = True							,			):
											# 0. center input if necessary
											if self.config.center_input_sample:
																		lowerCAmelCase =		2 * sample - 1.0

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

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

											lowerCAmelCase =		self.time_proj(UpperCAmelCase_    )

											# 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.
											lowerCAmelCase =		t_emb.to(dtype=self.dtype    )
											lowerCAmelCase =		self.time_embedding(UpperCAmelCase_    )

											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":
																									lowerCAmelCase =		self.time_proj(UpperCAmelCase_    )

																		lowerCAmelCase =		self.class_embedding(UpperCAmelCase_    ).to(dtype=self.dtype    )
																		lowerCAmelCase =		emb + class_emb

											# 2. pre-process
											lowerCAmelCase =		sample
											lowerCAmelCase =		self.conv_in(UpperCAmelCase_    )

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

																		down_block_res_samples += res_samples

											# 4. mid
											lowerCAmelCase =		self.mid_block(UpperCAmelCase_							,			UpperCAmelCase_    )

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

																		if hasattr(UpperCAmelCase_							,			'''skip_conv'''    ):
																									lowerCAmelCase ,  lowerCAmelCase =		upsample_block(UpperCAmelCase_							,			UpperCAmelCase_							,			UpperCAmelCase_							,			UpperCAmelCase_    )
																		else:
																									lowerCAmelCase =		upsample_block(UpperCAmelCase_							,			UpperCAmelCase_							,			UpperCAmelCase_    )

        # 6. post-process
											lowerCAmelCase =		self.conv_norm_out(UpperCAmelCase_    )
											lowerCAmelCase =		self.conv_act(UpperCAmelCase_    )
											lowerCAmelCase =		self.conv_out(UpperCAmelCase_    )

											if skip_sample is not None:
																		sample += skip_sample

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

											if not return_dict:
																		return (sample,)

											return UNetaDOutput(sample=UpperCAmelCase_    )









from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available


UpperCAmelCase_    ={
    """configuration_splinter""": ["""SPLINTER_PRETRAINED_CONFIG_ARCHIVE_MAP""", """SplinterConfig"""],
    """tokenization_splinter""": ["""SplinterTokenizer"""],
}

try:
		if not is_tokenizers_available():
				raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
		pass
else:
		UpperCAmelCase_    =["""SplinterTokenizerFast"""]

try:
		if not is_torch_available():
				raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
		pass
else:
		UpperCAmelCase_    =[
		    """SPLINTER_PRETRAINED_MODEL_ARCHIVE_LIST""",
		    """SplinterForQuestionAnswering""",
		    """SplinterForPreTraining""",
		    """SplinterLayer""",
		    """SplinterModel""",
		    """SplinterPreTrainedModel""",
		]


if TYPE_CHECKING:
		from .configuration_splinter import SPLINTER_PRETRAINED_CONFIG_ARCHIVE_MAP, SplinterConfig
		from .tokenization_splinter import SplinterTokenizer

		try:
				if not is_tokenizers_available():
						raise OptionalDependencyNotAvailable()
		except OptionalDependencyNotAvailable:
				pass
		else:
				from .tokenization_splinter_fast import SplinterTokenizerFast

		try:
				if not is_torch_available():
						raise OptionalDependencyNotAvailable()
		except OptionalDependencyNotAvailable:
				pass
		else:
				from .modeling_splinter import (
				    SPLINTER_PRETRAINED_MODEL_ARCHIVE_LIST,
				    SplinterForPreTraining,
				    SplinterForQuestionAnswering,
				    SplinterLayer,
				    SplinterModel,
				    SplinterPreTrainedModel,
				)


else:
		import sys

		UpperCAmelCase_    =_LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)



