


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    _a				(							_lowercase):
	_a    :    torch.FloatTensor





class    _a				(							_lowercase	,		_lowercase):




	@register_to_config
	def __init__(   self		:						Optional[int]						,   _SCREAMING_SNAKE_CASE		:						Optional[Union[int, Tuple[int, int]]] = None						,   _SCREAMING_SNAKE_CASE		:						int = 3						,   _SCREAMING_SNAKE_CASE		:						int = 3						,   _SCREAMING_SNAKE_CASE		:						bool = False						,   _SCREAMING_SNAKE_CASE		:						str = "positional"						,   _SCREAMING_SNAKE_CASE		:						int = 0						,   _SCREAMING_SNAKE_CASE		:						bool = True						,   _SCREAMING_SNAKE_CASE		:						Tuple[str] = ("DownBlock2D", "AttnDownBlock2D", "AttnDownBlock2D", "AttnDownBlock2D")						,   _SCREAMING_SNAKE_CASE		:						Tuple[str] = ("AttnUpBlock2D", "AttnUpBlock2D", "AttnUpBlock2D", "UpBlock2D")						,   _SCREAMING_SNAKE_CASE		:						Tuple[int] = (224, 448, 672, 896)						,   _SCREAMING_SNAKE_CASE		:						int = 2						,   _SCREAMING_SNAKE_CASE		:						float = 1						,   _SCREAMING_SNAKE_CASE		:						int = 1						,   _SCREAMING_SNAKE_CASE		:						str = "conv"						,   _SCREAMING_SNAKE_CASE		:						str = "conv"						,   _SCREAMING_SNAKE_CASE		:						str = "silu"						,   _SCREAMING_SNAKE_CASE		:						Optional[int] = 8						,   _SCREAMING_SNAKE_CASE		:						int = 32						,   _SCREAMING_SNAKE_CASE		:						float = 1E-5						,   _SCREAMING_SNAKE_CASE		:						str = "default"						,   _SCREAMING_SNAKE_CASE		:						bool = True						,   _SCREAMING_SNAKE_CASE		:						Optional[str] = None						,   _SCREAMING_SNAKE_CASE		:						Optional[int] = None						,   )->			List[Any]:
			super().__init__()

			lowerCAmelCase__  :     List[Any]       	=   sample_size
			lowerCAmelCase__  :     List[str]       	=   block_out_channels[0] * 4

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

			# time
			if time_embedding_type == "fourier":
					lowerCAmelCase__  :     Optional[int]       	=   GaussianFourierProjection(embedding_size=block_out_channels[0]						,   scale=16						)
					lowerCAmelCase__  :     List[str]       	=   2 * block_out_channels[0]
			elif time_embedding_type == "positional":
					lowerCAmelCase__  :     Optional[int]       	=   Timesteps(block_out_channels[0]						,   _SCREAMING_SNAKE_CASE						,   _SCREAMING_SNAKE_CASE						)
					lowerCAmelCase__  :     Tuple       	=   block_out_channels[0]

			lowerCAmelCase__  :     int       	=   TimestepEmbedding(_SCREAMING_SNAKE_CASE						,   _SCREAMING_SNAKE_CASE						)

			# class embedding
			if class_embed_type is None and num_class_embeds is not None:
					lowerCAmelCase__  :     Any       	=   nn.Embedding(_SCREAMING_SNAKE_CASE						,   _SCREAMING_SNAKE_CASE						)
			elif class_embed_type == "timestep":
					lowerCAmelCase__  :     str       	=   TimestepEmbedding(_SCREAMING_SNAKE_CASE						,   _SCREAMING_SNAKE_CASE						)
			elif class_embed_type == "identity":
					lowerCAmelCase__  :     List[Any]       	=   nn.Identity(_SCREAMING_SNAKE_CASE						,   _SCREAMING_SNAKE_CASE						)
			else:
					lowerCAmelCase__  :     Dict       	=   None

			lowerCAmelCase__  :     List[Any]       	=   nn.ModuleList([]						)
			lowerCAmelCase__  :     List[Any]       	=   None
			lowerCAmelCase__  :     Optional[Any]       	=   nn.ModuleList([]						)

			# down
			lowerCAmelCase__  :     Tuple       	=   block_out_channels[0]
			for i, down_block_type in enumerate(_SCREAMING_SNAKE_CASE						):
					lowerCAmelCase__  :     Optional[int]       	=   output_channel
					lowerCAmelCase__  :     Optional[Any]       	=   block_out_channels[i]
					lowerCAmelCase__  :     Optional[Any]       	=   i == len(_SCREAMING_SNAKE_CASE						) - 1

					lowerCAmelCase__  :     Optional[Any]       	=   get_down_block(
					    _SCREAMING_SNAKE_CASE						,   num_layers=_SCREAMING_SNAKE_CASE						,   in_channels=_SCREAMING_SNAKE_CASE						,   out_channels=_SCREAMING_SNAKE_CASE						,   temb_channels=_SCREAMING_SNAKE_CASE						,   add_downsample=not is_final_block						,   resnet_eps=_SCREAMING_SNAKE_CASE						,   resnet_act_fn=_SCREAMING_SNAKE_CASE						,   resnet_groups=_SCREAMING_SNAKE_CASE						,   attention_head_dim=attention_head_dim if attention_head_dim is not None else output_channel						,   downsample_padding=_SCREAMING_SNAKE_CASE						,   resnet_time_scale_shift=_SCREAMING_SNAKE_CASE						,   downsample_type=_SCREAMING_SNAKE_CASE						,   )
					self.down_blocks.append(_SCREAMING_SNAKE_CASE						)

			# mid
			lowerCAmelCase__  :     List[str]       	=   UNetMidBlockaD(
			    in_channels=block_out_channels[-1]						,   temb_channels=_SCREAMING_SNAKE_CASE						,   resnet_eps=_SCREAMING_SNAKE_CASE						,   resnet_act_fn=_SCREAMING_SNAKE_CASE						,   output_scale_factor=_SCREAMING_SNAKE_CASE						,   resnet_time_scale_shift=_SCREAMING_SNAKE_CASE						,   attention_head_dim=attention_head_dim if attention_head_dim is not None else block_out_channels[-1]						,   resnet_groups=_SCREAMING_SNAKE_CASE						,   add_attention=_SCREAMING_SNAKE_CASE						,   )

			# up
			lowerCAmelCase__  :     Tuple       	=   list(reversed(_SCREAMING_SNAKE_CASE						)						)
			lowerCAmelCase__  :     Any       	=   reversed_block_out_channels[0]
			for i, up_block_type in enumerate(_SCREAMING_SNAKE_CASE						):
					lowerCAmelCase__  :     Tuple       	=   output_channel
					lowerCAmelCase__  :     Union[str, Any]       	=   reversed_block_out_channels[i]
					lowerCAmelCase__  :     Union[str, Any]       	=   reversed_block_out_channels[min(i + 1						,   len(_SCREAMING_SNAKE_CASE						) - 1						)]

					lowerCAmelCase__  :     Any       	=   i == len(_SCREAMING_SNAKE_CASE						) - 1

					lowerCAmelCase__  :     Dict       	=   get_up_block(
					    _SCREAMING_SNAKE_CASE						,   num_layers=layers_per_block + 1						,   in_channels=_SCREAMING_SNAKE_CASE						,   out_channels=_SCREAMING_SNAKE_CASE						,   prev_output_channel=_SCREAMING_SNAKE_CASE						,   temb_channels=_SCREAMING_SNAKE_CASE						,   add_upsample=not is_final_block						,   resnet_eps=_SCREAMING_SNAKE_CASE						,   resnet_act_fn=_SCREAMING_SNAKE_CASE						,   resnet_groups=_SCREAMING_SNAKE_CASE						,   attention_head_dim=attention_head_dim if attention_head_dim is not None else output_channel						,   resnet_time_scale_shift=_SCREAMING_SNAKE_CASE						,   upsample_type=_SCREAMING_SNAKE_CASE						,   )
					self.up_blocks.append(_SCREAMING_SNAKE_CASE						)
					lowerCAmelCase__  :     Union[str, Any]       	=   output_channel

			# out
			lowerCAmelCase__  :     Any       	=   norm_num_groups if norm_num_groups is not None else min(block_out_channels[0] // 4						,   32						)
			lowerCAmelCase__  :     Any       	=   nn.GroupNorm(num_channels=block_out_channels[0]						,   num_groups=_SCREAMING_SNAKE_CASE						,   eps=_SCREAMING_SNAKE_CASE						)
			lowerCAmelCase__  :     List[str]       	=   nn.SiLU()
			lowerCAmelCase__  :     Dict       	=   nn.Convad(block_out_channels[0]						,   _SCREAMING_SNAKE_CASE						,   kernel_size=3						,   padding=1						)




	def 				UpperCAmelCase__(   self		:						Tuple						,   _SCREAMING_SNAKE_CASE		:						torch.FloatTensor						,   _SCREAMING_SNAKE_CASE		:						Union[torch.Tensor, float, int]						,   _SCREAMING_SNAKE_CASE		:						Optional[torch.Tensor] = None						,   _SCREAMING_SNAKE_CASE		:						bool = True						,   )->			Union[UNetaDOutput, Tuple]:
			# 0. center input if necessary
			if self.config.center_input_sample:
					lowerCAmelCase__  :     Tuple       	=   2 * sample - 1.0

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

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

			lowerCAmelCase__  :     str       	=   self.time_proj(_SCREAMING_SNAKE_CASE						)

			# 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__  :     List[str]       	=   t_emb.to(dtype=self.dtype						)
			lowerCAmelCase__  :     Union[str, Any]       	=   self.time_embedding(_SCREAMING_SNAKE_CASE						)

			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__  :     Dict       	=   self.time_proj(_SCREAMING_SNAKE_CASE						)

					lowerCAmelCase__  :     int       	=   self.class_embedding(_SCREAMING_SNAKE_CASE						).to(dtype=self.dtype						)
					lowerCAmelCase__  :     Optional[Any]       	=   emb + class_emb

			# 2. pre-process
			lowerCAmelCase__  :     List[str]       	=   sample
			lowerCAmelCase__  :     List[str]       	=   self.conv_in(_SCREAMING_SNAKE_CASE						)

			# 3. down
			lowerCAmelCase__  :     Any       	=   (sample,)
			for downsample_block in self.down_blocks:
					if hasattr(_SCREAMING_SNAKE_CASE						,   '''skip_conv'''						):
							lowerCAmelCase__	,      lowerCAmelCase__	,      lowerCAmelCase__  :     List[str]       	=   downsample_block(
							    hidden_states=_SCREAMING_SNAKE_CASE						,   temb=_SCREAMING_SNAKE_CASE						,   skip_sample=_SCREAMING_SNAKE_CASE						)
					else:
							lowerCAmelCase__	,      lowerCAmelCase__  :     List[Any]       	=   downsample_block(hidden_states=_SCREAMING_SNAKE_CASE						,   temb=_SCREAMING_SNAKE_CASE						)

					down_block_res_samples += res_samples

			# 4. mid
			lowerCAmelCase__  :     Union[str, Any]       	=   self.mid_block(_SCREAMING_SNAKE_CASE						,   _SCREAMING_SNAKE_CASE						)

			# 5. up
			lowerCAmelCase__  :     Optional[int]       	=   None
			for upsample_block in self.up_blocks:
					lowerCAmelCase__  :     Dict       	=   down_block_res_samples[-len(upsample_block.resnets						) :]
					lowerCAmelCase__  :     List[Any]       	=   down_block_res_samples[: -len(upsample_block.resnets						)]

					if hasattr(_SCREAMING_SNAKE_CASE						,   '''skip_conv'''						):
							lowerCAmelCase__	,      lowerCAmelCase__  :     str       	=   upsample_block(_SCREAMING_SNAKE_CASE						,   _SCREAMING_SNAKE_CASE						,   _SCREAMING_SNAKE_CASE						,   _SCREAMING_SNAKE_CASE						)
					else:
							lowerCAmelCase__  :     Dict       	=   upsample_block(_SCREAMING_SNAKE_CASE						,   _SCREAMING_SNAKE_CASE						,   _SCREAMING_SNAKE_CASE						)

        # 6. post-process
			lowerCAmelCase__  :     List[str]       	=   self.conv_norm_out(_SCREAMING_SNAKE_CASE						)
			lowerCAmelCase__  :     str       	=   self.conv_act(_SCREAMING_SNAKE_CASE						)
			lowerCAmelCase__  :     Optional[Any]       	=   self.conv_out(_SCREAMING_SNAKE_CASE						)

			if skip_sample is not None:
					sample += skip_sample

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

			if not return_dict:
					return (sample,)

			return UNetaDOutput(sample=_SCREAMING_SNAKE_CASE						)








from .chunk_utils import chunk_layer
from .data_transforms import make_atomaa_masks
from .feats import atomaa_to_atomaa, frames_and_literature_positions_to_atomaa_pos, torsion_angles_to_frames
from .loss import compute_predicted_aligned_error, compute_tm
from .protein import Protein as OFProtein
from .protein import to_pdb
from .rigid_utils import Rigid, Rotation
from .tensor_utils import dict_multimap, flatten_final_dims, permute_final_dims




