

'''simple docstring'''


from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available


lowerCAmelCase__										= {"tokenization_herbert": ["HerbertTokenizer"]}

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


if TYPE_CHECKING:
						from .tokenization_herbert import HerbertTokenizer

						try:
												if not is_tokenizers_available():
																		raise OptionalDependencyNotAvailable()
						except OptionalDependencyNotAvailable:
												pass
						else:
												from .tokenization_herbert_fast import HerbertTokenizerFast

else:
						import sys

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









'''simple docstring'''


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 get_down_block, get_mid_block, get_out_block, get_up_block



@dataclass
class 					lowercase						(  a_ ):
							_lowerCamelCase		:      torch.FloatTensor



class 					lowercase						(  a_,					a_ ):


							@register_to_config
							def __init__(			self    ,			_snake_case = 6_5536    ,			_snake_case = None    ,			_snake_case = 2    ,			_snake_case = 2    ,			_snake_case = 0    ,			_snake_case = "fourier"    ,			_snake_case = True    ,			_snake_case = False    ,			_snake_case = 0.0    ,			_snake_case = ("DownBlock1DNoSkip", "DownBlock1D", "AttnDownBlock1D")    ,			_snake_case = ("AttnUpBlock1D", "UpBlock1D", "UpBlock1DNoSkip")    ,			_snake_case = "UNetMidBlock1D"    ,			_snake_case = None    ,			_snake_case = (32, 32, 64)    ,			_snake_case = None    ,			_snake_case = 8    ,			_snake_case = 1    ,			_snake_case = False    ,			)							->				List[str]:
								super().__init__()
								UpperCAmelCase_		:      Optional[Any]       	=					sample_size

								# time
								if time_embedding_type == "fourier":
									UpperCAmelCase_		:      Tuple       	=					GaussianFourierProjection(
									    embedding_size=8    ,			set_W_to_weight=_snake_case    ,			log=_snake_case    ,			flip_sin_to_cos=_snake_case)
									UpperCAmelCase_		:      int       	=					2 * block_out_channels[0]
								elif time_embedding_type == "positional":
									UpperCAmelCase_		:      Optional[Any]       	=					Timesteps(
									    block_out_channels[0]    ,			flip_sin_to_cos=_snake_case    ,			downscale_freq_shift=_snake_case)
									UpperCAmelCase_		:      List[Any]       	=					block_out_channels[0]

								if use_timestep_embedding:
									UpperCAmelCase_		:      Dict       	=					block_out_channels[0] * 4
									UpperCAmelCase_		:      List[Any]       	=					TimestepEmbedding(
									    in_channels=_snake_case    ,			time_embed_dim=_snake_case    ,			act_fn=_snake_case    ,			out_dim=block_out_channels[0]    ,			)

								UpperCAmelCase_		:      int       	=					nn.ModuleList([])
								UpperCAmelCase_		:      Optional[int]       	=					None
								UpperCAmelCase_		:      Optional[int]       	=					nn.ModuleList([])
								UpperCAmelCase_		:      Any       	=					None

								# down
								UpperCAmelCase_		:      Dict       	=					in_channels
								for i, down_block_type in enumerate(_snake_case):
									UpperCAmelCase_		:      int       	=					output_channel
									UpperCAmelCase_		:      Optional[int]       	=					block_out_channels[i]

									if i == 0:
										input_channel += extra_in_channels

									UpperCAmelCase_		:      int       	=					i == len(_snake_case) - 1

									UpperCAmelCase_		:      Any       	=					get_down_block(
									    _snake_case    ,			num_layers=_snake_case    ,			in_channels=_snake_case    ,			out_channels=_snake_case    ,			temb_channels=block_out_channels[0]    ,			add_downsample=not is_final_block or downsample_each_block    ,			)
									self.down_blocks.append(_snake_case)

								# mid
								UpperCAmelCase_		:      Optional[int]       	=					get_mid_block(
								    _snake_case    ,			in_channels=block_out_channels[-1]    ,			mid_channels=block_out_channels[-1]    ,			out_channels=block_out_channels[-1]    ,			embed_dim=block_out_channels[0]    ,			num_layers=_snake_case    ,			add_downsample=_snake_case    ,			)

								# up
								UpperCAmelCase_		:      Union[str, Any]       	=					list(reversed(_snake_case))
								UpperCAmelCase_		:      Optional[int]       	=					reversed_block_out_channels[0]
								if out_block_type is None:
									UpperCAmelCase_		:      Tuple       	=					out_channels
								else:
									UpperCAmelCase_		:      int       	=					block_out_channels[0]

								for i, up_block_type in enumerate(_snake_case):
									UpperCAmelCase_		:      Dict       	=					output_channel
									UpperCAmelCase_		:      Optional[Any]       	=					(
									    reversed_block_out_channels[i + 1] if i < len(_snake_case) - 1 else final_upsample_channels
									)

									UpperCAmelCase_		:      str       	=					i == len(_snake_case) - 1

									UpperCAmelCase_		:      Union[str, Any]       	=					get_up_block(
									    _snake_case    ,			num_layers=_snake_case    ,			in_channels=_snake_case    ,			out_channels=_snake_case    ,			temb_channels=block_out_channels[0]    ,			add_upsample=not is_final_block    ,			)
									self.up_blocks.append(_snake_case)
									UpperCAmelCase_		:      Dict       	=					output_channel

								# out
								UpperCAmelCase_		:      Union[str, Any]       	=					norm_num_groups if norm_num_groups is not None else min(block_out_channels[0] // 4    ,			32)
								UpperCAmelCase_		:      Any       	=					get_out_block(
								    out_block_type=_snake_case    ,			num_groups_out=_snake_case    ,			embed_dim=block_out_channels[0]    ,			out_channels=_snake_case    ,			act_fn=_snake_case    ,			fc_dim=block_out_channels[-1] // 4    ,			)





							def 						_snake_case							(			self    ,			_snake_case    ,			_snake_case    ,			_snake_case = True    ,			)							->				Union[UNetaDOutput, Tuple]:
								UpperCAmelCase_		:      Union[str, Any]       	=					timestep
								if not torch.is_tensor(_snake_case):
									UpperCAmelCase_		:      Union[str, Any]       	=					torch.tensor([timesteps]    ,			dtype=torch.long    ,			device=sample.device)
								elif torch.is_tensor(_snake_case) and len(timesteps.shape) == 0:
									UpperCAmelCase_		:      Tuple       	=					timesteps[None].to(sample.device)

								UpperCAmelCase_		:      Any       	=					self.time_proj(_snake_case)
								if self.config.use_timestep_embedding:
									UpperCAmelCase_		:      int       	=					self.time_mlp(_snake_case)
								else:
									UpperCAmelCase_		:      int       	=					timestep_embed[..., None]
									UpperCAmelCase_		:      List[Any]       	=					timestep_embed.repeat([1, 1, sample.shape[2]]).to(sample.dtype)
									UpperCAmelCase_		:      int       	=					timestep_embed.broadcast_to((sample.shape[:1] + timestep_embed.shape[1:]))

								# 2. down
								UpperCAmelCase_		:      Optional[Any]       	=					()
								for downsample_block in self.down_blocks:
									UpperCAmelCase_	,    UpperCAmelCase_		:      Optional[int]       	=					downsample_block(hidden_states=_snake_case    ,			temb=_snake_case)
									down_block_res_samples += res_samples

								# 3. mid
								if self.mid_block:
									UpperCAmelCase_		:      List[Any]       	=					self.mid_block(_snake_case    ,			_snake_case)

								# 4. up
								for i, upsample_block in enumerate(self.up_blocks):
									UpperCAmelCase_		:      int       	=					down_block_res_samples[-1:]
									UpperCAmelCase_		:      Tuple       	=					down_block_res_samples[:-1]
									UpperCAmelCase_		:      List[Any]       	=					upsample_block(_snake_case    ,			res_hidden_states_tuple=_snake_case    ,			temb=_snake_case)

								# 5. post-process
								if self.out_block:
									UpperCAmelCase_		:      Optional[Any]       	=					self.out_block(_snake_case    ,			_snake_case)

								if not return_dict:
									return (sample,)

								return UNetaDOutput(sample=_snake_case)






