





'''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 UNetMidBlockaD, get_down_block, get_up_block
@dataclass
class    a_     (       snake_case_							):
     __A  				=    42







class    a_     (       snake_case_			,		snake_case_							):





     @register_to_config
     def __init__(				self	:      Dict			,   lowercase	:      int = None			,   lowercase	:      int = 3			,   lowercase	:      Optional[int] = 3			,   lowercase	:      Dict = False			,   lowercase	:      Any = "positional"			,   lowercase	:      str = 0			,   lowercase	:      Tuple = True			,   lowercase	:      Any = ("DownBlock2D", "AttnDownBlock2D", "AttnDownBlock2D", "AttnDownBlock2D")			,   lowercase	:      Optional[int] = ("AttnUpBlock2D", "AttnUpBlock2D", "AttnUpBlock2D", "UpBlock2D")			,   lowercase	:      Any = (224, 448, 672, 896)			,   lowercase	:      List[Any] = 2			,   lowercase	:      str = 1			,   lowercase	:      Any = 1			,   lowercase	:      List[str] = "conv"			,   lowercase	:      Dict = "conv"			,   lowercase	:      Dict = "silu"			,   lowercase	:      str = 8			,   lowercase	:      Optional[Any] = 32			,   lowercase	:      int = 1e-5			,   lowercase	:      List[str] = "default"			,   lowercase	:      Dict = True			,   lowercase	:      int = None			,   lowercase	:      List[Any] = None			,   ):





        """simple docstring"""




        super().__init__()

        lowercase_    :Union[str, Any]           =				sample_size
        lowercase_    :List[Any]           =				block_out_channels[0] * 4

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

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

        lowercase_    :Dict           =				TimestepEmbedding(lowercase			,   lowercase		)

        # class embedding
        if class_embed_type is None and num_class_embeds is not None:
           lowercase_    :str           =				nn.Embedding(lowercase			,   lowercase		)
        elif class_embed_type == "timestep":
           lowercase_    :Any           =				TimestepEmbedding(lowercase			,   lowercase		)
        elif class_embed_type == "identity":
           lowercase_    :Tuple           =				nn.Identity(lowercase			,   lowercase		)
        else:
           lowercase_    :Any           =				None

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

        # down
        lowercase_    :Dict           =				block_out_channels[0]
        for i, down_block_type in enumerate(lowercase		):
           lowercase_    :str           =				output_channel
           lowercase_    :Optional[Any]           =				block_out_channels[i]
           lowercase_    :Union[str, Any]           =				i == len(lowercase		) - 1

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

        # mid
        lowercase_    :Optional[Any]           =				UNetMidBlockaD(
            in_channels=block_out_channels[-1]			,   temb_channels=lowercase			,   resnet_eps=lowercase			,   resnet_act_fn=lowercase			,   output_scale_factor=lowercase			,   resnet_time_scale_shift=lowercase			,   attention_head_dim=attention_head_dim if attention_head_dim is not None else block_out_channels[-1]			,   resnet_groups=lowercase			,   add_attention=lowercase			,   )

        # up
        lowercase_    :int           =				list(reversed(lowercase		)		)
        lowercase_    :Any           =				reversed_block_out_channels[0]
        for i, up_block_type in enumerate(lowercase		):
           lowercase_    :Optional[Any]           =				output_channel
           lowercase_    :Any           =				reversed_block_out_channels[i]
           lowercase_    :Tuple           =				reversed_block_out_channels[min(i + 1			,   len(lowercase		) - 1		)]

           lowercase_    :Optional[Any]           =				i == len(lowercase		) - 1

           lowercase_    :List[str]           =				get_up_block(
               lowercase			,   num_layers=layers_per_block + 1			,   in_channels=lowercase			,   out_channels=lowercase			,   prev_output_channel=lowercase			,   temb_channels=lowercase			,   add_upsample=not is_final_block			,   resnet_eps=lowercase			,   resnet_act_fn=lowercase			,   resnet_groups=lowercase			,   attention_head_dim=attention_head_dim if attention_head_dim is not None else output_channel			,   resnet_time_scale_shift=lowercase			,   upsample_type=lowercase			,   )
           self.up_blocks.append(lowercase		)
           lowercase_    :int           =				output_channel

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







     def 							lowercase__   (				self	:      int			,   lowercase	:      Tuple			,   lowercase	:      Union[str, Any]			,   lowercase	:      Dict = None			,   lowercase	:      Optional[int] = True			,   ):





        """simple docstring"""




        if self.config.center_input_sample:
           lowercase_    :Optional[Any]           =				2 * sample - 1.0

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

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

        lowercase_    :Union[str, Any]           =				self.time_proj(lowercase		)

        # 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.
        lowercase_    :Any           =				t_emb.to(dtype=self.dtype		)
        lowercase_    :Any           =				self.time_embedding(lowercase		)

        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":
              lowercase_    :Any           =				self.time_proj(lowercase		)

           lowercase_    :Optional[int]           =				self.class_embedding(lowercase		).to(dtype=self.dtype		)
           lowercase_    :List[Any]           =				emb + class_emb

        # 2. pre-process
        lowercase_    :Dict           =				sample
        lowercase_    :Optional[Any]           =				self.conv_in(lowercase		)

        # 3. down
        lowercase_    :List[str]           =				(sample,)
        for downsample_block in self.down_blocks:
           if hasattr(lowercase			,   "skip_conv"		):
              lowercase_    ,							lowercase_    ,							lowercase_    :Optional[int]           =				downsample_block(
                  hidden_states=lowercase			,   temb=lowercase			,   skip_sample=lowercase		)
           else:
              lowercase_    ,							lowercase_    :Any           =				downsample_block(hidden_states=lowercase			,   temb=lowercase		)

           down_block_res_samples += res_samples

        # 4. mid
        lowercase_    :List[str]           =				self.mid_block(lowercase			,   lowercase		)

        # 5. up
        lowercase_    :Dict           =				None
        for upsample_block in self.up_blocks:
           lowercase_    :Union[str, Any]           =				down_block_res_samples[-len(upsample_block.resnets		) :]
           lowercase_    :Optional[Any]           =				down_block_res_samples[: -len(upsample_block.resnets		)]

           if hasattr(lowercase			,   "skip_conv"		):
              lowercase_    ,							lowercase_    :List[Any]           =				upsample_block(lowercase			,   lowercase			,   lowercase			,   lowercase		)
           else:
              lowercase_    :Optional[int]           =				upsample_block(lowercase			,   lowercase			,   lowercase		)

        # 6. post-process
        lowercase_    :Tuple           =				self.conv_norm_out(lowercase		)
        lowercase_    :Union[str, Any]           =				self.conv_act(lowercase		)
        lowercase_    :Union[str, Any]           =				self.conv_out(lowercase		)

        if skip_sample is not None:
           sample += skip_sample

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

        if not return_dict:
           return (sample,)

        return UNetaDOutput(sample=lowercase		)









'''simple docstring'''


import json
import os
from collections.abc import Mapping
from typing import Dict, List, Optional, Union

import numpy as np
import torch

from .imports import is_safetensors_available
def 							UpperCAmelCase_						(		__lowerCamelCase      :      Optional[int]			,__lowerCamelCase      :      Union[str, Any]			,__lowerCamelCase      :      List[Any]			,__lowerCamelCase      :      str=None				):
   lowercase_    :List[Any]					    =				None
   # Check the string instead of the dtype to be compatible with versions of PyTorch that don't have bfloat16.
   if str(weight.dtype				) == "torch.bfloat16":
      # Need to reinterpret the underlined data as int16 since NumPy does not handle bfloat16s.
      lowercase_    :int					    =				weight.view(torch.intaa				)
      lowercase_    :List[Any]					    =				"bfloat16"
   lowercase_    :Optional[Any]					    =				weight.cpu().numpy()
   lowercase_    :Optional[int]					    =				os.path.join(__lowerCamelCase			,F'{weight_name}.dat'				)
   if index is not None:
      if dtype is None:
         lowercase_    :str					    =				str(array.dtype				)
      lowercase_    :int					    =				{"dtype": dtype, "shape": list(array.shape				)}
   if array.ndim == 0:
      lowercase_    :int					    =				array[None]
   lowercase_    :List[Any]					    =				np.memmap(__lowerCamelCase			,dtype=array.dtype			,mode="w+"			,shape=array.shape				)
   lowercase_    :List[Any]					    =				array[:]
   file_array.flush()
   return index
def 							UpperCAmelCase_						(		__lowerCamelCase      :      int			,__lowerCamelCase      :      Dict				):
   lowercase_    :int					    =				tuple(weight_info["shape"]				)
   if shape == ():
      # NumPy memory-mapped arrays can't have 0 dims so it was saved as 1d tensor
      lowercase_    :List[str]					    =				(1,)

   lowercase_    :List[str]					    =				weight_info["dtype"]
   if dtype == "bfloat16":
      # NumPy does not support bfloat16 so this was saved as a int16
      lowercase_    :Optional[Any]					    =				"int16"

   lowercase_    :str					    =				np.memmap(__lowerCamelCase			,dtype=__lowerCamelCase			,shape=__lowerCamelCase			,mode="r"				)

   if len(weight_info["shape"]				) == 0:
      lowercase_    :Union[str, Any]					    =				weight[0]
   lowercase_    :str					    =				torch.tensor(__lowerCamelCase				)
   if weight_info["dtype"] == "bfloat16":
      lowercase_    :Any					    =				weight.view(torch.bfloataa				)

   return weight
def 							UpperCAmelCase_						(		__lowerCamelCase      :      Dict			,__lowerCamelCase      :      List[str]				):
   if index is None or len(__lowerCamelCase				) == 0:
      # Nothing to save
      return

   lowercase_    :List[Any]					    =				os.path.join(__lowerCamelCase			,"index.json"				)
   if os.path.isfile(__lowerCamelCase				):
      with open(__lowerCamelCase			,"r"			,encoding="utf-8"				) as f:
         lowercase_    :Any					    =				json.load(__lowerCamelCase				)
   else:
      lowercase_    :Union[str, Any]					    =				{}
   current_index.update(__lowerCamelCase				)

   with open(__lowerCamelCase			,"w"			,encoding="utf-8"				) as f:
      json.dump(__lowerCamelCase			,__lowerCamelCase			,indent=2				)
def 							UpperCAmelCase_						(		__lowerCamelCase      :      Union[str, os.PathLike]			,__lowerCamelCase      :      Dict[str, torch.Tensor]				):
   os.makedirs(__lowerCamelCase			,exist_ok=__lowerCamelCase				)
   lowercase_    :List[Any]					    =				{}
   for name, parameter in state_dict.items():
      lowercase_    :Tuple					    =				offload_weight(__lowerCamelCase			,__lowerCamelCase			,__lowerCamelCase			,index=__lowerCamelCase				)

   # Update index
   save_offload_index(__lowerCamelCase			,__lowerCamelCase				)
class    a_     (       _lowerCAmelCase							):





     def __init__(				self	:      int			,   lowercase	:      Mapping			,   lowercase	:      str		):





        """simple docstring"""




        lowercase_    :Union[str, Any]					    =				dataset
        lowercase_    :List[str]					    =				prefix





     def __getitem__(				self	:      Any			,   lowercase	:      List[str]		):





        """simple docstring"""




        return self.dataset[F'{self.prefix}{key}']





     def __iter__(				self	:      Optional[int]		):





        """simple docstring"""




        return iter([key for key in self.dataset if key.startswith(self.prefix		)]		)







     def __len__(				self	:      Any		):





        """simple docstring"""




        return len(self.dataset		)







class    a_     (       _lowerCAmelCase							):





     def __init__(				self	:      Tuple			,   lowercase	:      Dict[str, torch.Tensor] = None			,   lowercase	:      Optional[Union[str, os.PathLike]] = None			,   lowercase	:      Mapping = None			,   lowercase	:      Optional[Any]=None			,   ):





        """simple docstring"""




        if state_dict is None and save_folder is None:
           raise ValueError("Need either a `state_dict` or a `save_folder` containing offloaded weights."		)

        lowercase_    :Optional[int]					    =				{} if state_dict is None else state_dict
        lowercase_    :str					    =				save_folder
        if index is None and save_folder is not None:
           with open(os.path.join(lowercase			,   "index.json"		)		) as f:
              lowercase_    :Any					    =				json.load(lowercase		)
        lowercase_    :str					    =				{} if index is None else index
        lowercase_    :List[str]					    =				list(self.state_dict.keys()		)
        self.all_keys.extend([key for key in self.index if key not in self.all_keys]		)
        lowercase_    :List[Any]					    =				device





     def __getitem__(				self	:      Any			,   lowercase	:      str		):





        """simple docstring"""




        if key in self.state_dict:
           return self.state_dict[key]
        lowercase_    :int					    =				self.index[key]
        if weight_info.get("safetensors_file"		) is not None:
           if not is_safetensors_available():
              raise ImportError("These offloaded weights require the use of safetensors: `pip install safetensors`."		)

           from safetensors import safe_open

           lowercase_    :Dict					    =				"cpu" if self.device is None else self.device
           with safe_open(weight_info["safetensors_file"]			,   framework="pt"			,   device=lowercase		) as f:
              lowercase_    :Tuple					    =				f.get_tensor(weight_info.get("weight_name"			,   lowercase		)		)

           if "dtype" in weight_info:
              return tensor.to(getattr(lowercase			,   weight_info["dtype"]		)		)
           else:
              return tensor

        lowercase_    :str					    =				os.path.join(self.save_folder			,   F'{key}.dat'		)
        return load_offloaded_weight(lowercase			,   lowercase		)





     def __iter__(				self	:      Optional[int]		):





        """simple docstring"""




        return iter(self.all_keys		)







     def __len__(				self	:      Tuple		):





        """simple docstring"""




        return len(self.all_keys		)







def 							UpperCAmelCase_						(		__lowerCamelCase      :      Dict[str, torch.Tensor]			,__lowerCamelCase      :      List[str]				):
   lowercase_    :List[str]					    =				{}
   for module_name in submodule_names:
      # We want to catch module_name parameter (module_name.xxx) or potentially module_name, but not any of the
      # submodules that could being like module_name (transformers.h.1 and transformers.h.10 for instance)
      result.update(
          {
              key: param
              for key, param in state_dict.items()
              if key == module_name or key.startswith(module_name + "."				)
          }				)
   return result


