

from typing import Any, Dict, Optional

import torch
import torch.nn.functional as F
from torch import nn

from ..utils import maybe_allow_in_graph
from .activations import get_activation
from .attention_processor import Attention
from .embeddings import CombinedTimestepLabelEmbeddings

@maybe_allow_in_graph
class     __snake_case    (				nn.Module  ):
       """simple docstring"""







       def __init__(		self      , _UpperCamelCase      , _UpperCamelCase      , _UpperCamelCase      , _UpperCamelCase=0.0      , _UpperCamelCase = None      , _UpperCamelCase = "geglu"      , _UpperCamelCase = None      , _UpperCamelCase = False      , _UpperCamelCase = False      , _UpperCamelCase = False      , _UpperCamelCase = False      , _UpperCamelCase = True      , _UpperCamelCase = "layer_norm"      , _UpperCamelCase = False      , )      ->							str:






              """simple docstring"""


              super().__init__()
              __snake_case       	=							only_cross_attention

              __snake_case       	=							(num_embeds_ada_norm is not None) and norm_type == """ada_norm_zero"""
              __snake_case       	=							(num_embeds_ada_norm is not None) and norm_type == """ada_norm"""

              if norm_type in ("ada_norm", "ada_norm_zero") and num_embeds_ada_norm is None:
                     raise ValueError(
                         F'`norm_type` is set to {norm_type}, but `num_embeds_ada_norm` is not defined. Please make sure to'
                         F' define `num_embeds_ada_norm` if setting `norm_type` to {norm_type}.'   )

              # Define 3 blocks. Each block has its own normalization layer.
              # 1. Self-Attn
              if self.use_ada_layer_norm:
                     __snake_case       	=							AdaLayerNorm(_UpperCamelCase      , _UpperCamelCase   )
              elif self.use_ada_layer_norm_zero:
                     __snake_case       	=							AdaLayerNormZero(_UpperCamelCase      , _UpperCamelCase   )
              else:
                     __snake_case       	=							nn.LayerNorm(_UpperCamelCase      , elementwise_affine=_UpperCamelCase   )
              __snake_case       	=							Attention(
                  query_dim=_UpperCamelCase      , heads=_UpperCamelCase      , dim_head=_UpperCamelCase      , dropout=_UpperCamelCase      , bias=_UpperCamelCase      , cross_attention_dim=cross_attention_dim if only_cross_attention else None      , upcast_attention=_UpperCamelCase      , )

              # 2. Cross-Attn
              if cross_attention_dim is not None or double_self_attention:
                     # We currently only use AdaLayerNormZero for self attention where there will only be one attention block.
                     # I.e. the number of returned modulation chunks from AdaLayerZero would not make sense if returned during
                     # the second cross attention block.
                     __snake_case       	=							(
                         AdaLayerNorm(_UpperCamelCase      , _UpperCamelCase   )
                         if self.use_ada_layer_norm
                         else nn.LayerNorm(_UpperCamelCase      , elementwise_affine=_UpperCamelCase   )
                     )
                     __snake_case       	=							Attention(
                         query_dim=_UpperCamelCase      , cross_attention_dim=cross_attention_dim if not double_self_attention else None      , heads=_UpperCamelCase      , dim_head=_UpperCamelCase      , dropout=_UpperCamelCase      , bias=_UpperCamelCase      , upcast_attention=_UpperCamelCase      , )  # is self-attn if encoder_hidden_states is none
              else:
                     __snake_case       	=							None
                     __snake_case       	=							None

              # 3. Feed-forward
              __snake_case       	=							nn.LayerNorm(_UpperCamelCase      , elementwise_affine=_UpperCamelCase   )
              __snake_case       	=							FeedForward(_UpperCamelCase      , dropout=_UpperCamelCase      , activation_fn=_UpperCamelCase      , final_dropout=_UpperCamelCase   )

              # let chunk size default to None
              __snake_case       	=							None
              __snake_case       	=							0


       def 			a		(		self      , _UpperCamelCase      , _UpperCamelCase   )      ->							Tuple:






              """simple docstring"""


              __snake_case       	=							chunk_size
              __snake_case       	=							dim






       def 			a		(		self      , _UpperCamelCase      , _UpperCamelCase = None      , _UpperCamelCase = None      , _UpperCamelCase = None      , _UpperCamelCase = None      , _UpperCamelCase = None      , _UpperCamelCase = None      , )      ->							str:






              """simple docstring"""


              if self.use_ada_layer_norm:
                     __snake_case       	=							self.norma(_UpperCamelCase      , _UpperCamelCase   )
              elif self.use_ada_layer_norm_zero:
                     __snake_case	,    __snake_case	,    __snake_case	,    __snake_case	,    __snake_case       	=							self.norma(
                         _UpperCamelCase      , _UpperCamelCase      , _UpperCamelCase      , hidden_dtype=hidden_states.dtype   )
              else:
                     __snake_case       	=							self.norma(_UpperCamelCase   )

              __snake_case       	=							cross_attention_kwargs if cross_attention_kwargs is not None else {}

              __snake_case       	=							self.attna(
                  _UpperCamelCase      , encoder_hidden_states=encoder_hidden_states if self.only_cross_attention else None      , attention_mask=_UpperCamelCase      , **_UpperCamelCase      , )
              if self.use_ada_layer_norm_zero:
                     __snake_case       	=							gate_msa.unsqueeze(1   ) * attn_output
              __snake_case       	=							attn_output + hidden_states

              # 2. Cross-Attention
              if self.attna is not None:
                     __snake_case       	=							(
                         self.norma(_UpperCamelCase      , _UpperCamelCase   ) if self.use_ada_layer_norm else self.norma(_UpperCamelCase   )
                     )

                     __snake_case       	=							self.attna(
                         _UpperCamelCase      , encoder_hidden_states=_UpperCamelCase      , attention_mask=_UpperCamelCase      , **_UpperCamelCase      , )
                     __snake_case       	=							attn_output + hidden_states

              # 3. Feed-forward
              __snake_case       	=							self.norma(_UpperCamelCase   )

              if self.use_ada_layer_norm_zero:
                     __snake_case       	=							norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None]

              if self._chunk_size is not None:
                     # "feed_forward_chunk_size" can be used to save memory
                     if norm_hidden_states.shape[self._chunk_dim] % self._chunk_size != 0:
                            raise ValueError(
                                F'`hidden_states` dimension to be chunked: {norm_hidden_states.shape[self._chunk_dim]} has to be divisible by chunk size: {self._chunk_size}. Make sure to set an appropriate `chunk_size` when calling `unet.enable_forward_chunking`.'   )

                     __snake_case       	=							norm_hidden_states.shape[self._chunk_dim] // self._chunk_size
                     __snake_case       	=							torch.cat(
                         [self.ff(_UpperCamelCase   ) for hid_slice in norm_hidden_states.chunk(_UpperCamelCase      , dim=self._chunk_dim   )]      , dim=self._chunk_dim      , )
              else:
                     __snake_case       	=							self.ff(_UpperCamelCase   )

              if self.use_ada_layer_norm_zero:
                     __snake_case       	=							gate_mlp.unsqueeze(1   ) * ff_output

              __snake_case       	=							ff_output + hidden_states

              return hidden_states






class     __snake_case    (				nn.Module  ):
       """simple docstring"""







       def __init__(		self      , _UpperCamelCase      , _UpperCamelCase = None      , _UpperCamelCase = 4      , _UpperCamelCase = 0.0      , _UpperCamelCase = "geglu"      , _UpperCamelCase = False      , )      ->							int:






              """simple docstring"""


              super().__init__()
              __snake_case       	=							int(dim * mult   )
              __snake_case       	=							dim_out if dim_out is not None else dim

              if activation_fn == "gelu":
                     __snake_case       	=							GELU(_UpperCamelCase      , _UpperCamelCase   )
              if activation_fn == "gelu-approximate":
                     __snake_case       	=							GELU(_UpperCamelCase      , _UpperCamelCase      , approximate="""tanh"""   )
              elif activation_fn == "geglu":
                     __snake_case       	=							GEGLU(_UpperCamelCase      , _UpperCamelCase   )
              elif activation_fn == "geglu-approximate":
                     __snake_case       	=							ApproximateGELU(_UpperCamelCase      , _UpperCamelCase   )

              __snake_case       	=							nn.ModuleList([]   )
              # project in
              self.net.append(_UpperCamelCase   )
              # project dropout
              self.net.append(nn.Dropout(_UpperCamelCase   )   )
              # project out
              self.net.append(nn.Linear(_UpperCamelCase      , _UpperCamelCase   )   )
              # FF as used in Vision Transformer, MLP-Mixer, etc. have a final dropout
              if final_dropout:
                     self.net.append(nn.Dropout(_UpperCamelCase   )   )






       def 			a		(		self      , _UpperCamelCase   )      ->							Any:






              """simple docstring"""


              for module in self.net:
                     __snake_case       	=							module(_UpperCamelCase   )
              return hidden_states






class     __snake_case    (				nn.Module  ):
       """simple docstring"""







       def __init__(		self      , _UpperCamelCase      , _UpperCamelCase      , _UpperCamelCase = "none"   )      ->							Dict:






              """simple docstring"""


              super().__init__()
              __snake_case       	=							nn.Linear(_UpperCamelCase      , _UpperCamelCase   )
              __snake_case       	=							approximate


       def 			a		(		self      , _UpperCamelCase   )      ->							Any:






              """simple docstring"""


              if gate.device.type != "mps":
                     return F.gelu(_UpperCamelCase      , approximate=self.approximate   )
              # mps: gelu is not implemented for float16
              return F.gelu(gate.to(dtype=torch.floataa   )      , approximate=self.approximate   ).to(dtype=gate.dtype   )






       def 			a		(		self      , _UpperCamelCase   )      ->							Dict:






              """simple docstring"""


              __snake_case       	=							self.proj(_UpperCamelCase   )
              __snake_case       	=							self.gelu(_UpperCamelCase   )
              return hidden_states






class     __snake_case    (				nn.Module  ):
       """simple docstring"""







       def __init__(		self      , _UpperCamelCase      , _UpperCamelCase   )      ->							List[Any]:






              """simple docstring"""


              super().__init__()
              __snake_case       	=							nn.Linear(_UpperCamelCase      , dim_out * 2   )


       def 			a		(		self      , _UpperCamelCase   )      ->							str:






              """simple docstring"""


              if gate.device.type != "mps":
                     return F.gelu(_UpperCamelCase   )
              # mps: gelu is not implemented for float16
              return F.gelu(gate.to(dtype=torch.floataa   )   ).to(dtype=gate.dtype   )






       def 			a		(		self      , _UpperCamelCase   )      ->							int:






              """simple docstring"""


              __snake_case	,    __snake_case       	=							self.proj(_UpperCamelCase   ).chunk(2      , dim=-1   )
              return hidden_states * self.gelu(_UpperCamelCase   )






class     __snake_case    (				nn.Module  ):
       """simple docstring"""







       def __init__(		self      , _UpperCamelCase      , _UpperCamelCase   )      ->							int:






              """simple docstring"""


              super().__init__()
              __snake_case       	=							nn.Linear(_UpperCamelCase      , _UpperCamelCase   )






       def 			a		(		self      , _UpperCamelCase   )      ->							List[Any]:






              """simple docstring"""


              __snake_case       	=							self.proj(_UpperCamelCase   )
              return x * torch.sigmoid(1.702 * x   )






class     __snake_case    (				nn.Module  ):
       """simple docstring"""







       def __init__(		self      , _UpperCamelCase      , _UpperCamelCase   )      ->							Dict:






              """simple docstring"""


              super().__init__()
              __snake_case       	=							nn.Embedding(_UpperCamelCase      , _UpperCamelCase   )
              __snake_case       	=							nn.SiLU()
              __snake_case       	=							nn.Linear(_UpperCamelCase      , embedding_dim * 2   )
              __snake_case       	=							nn.LayerNorm(_UpperCamelCase      , elementwise_affine=_UpperCamelCase   )






       def 			a		(		self      , _UpperCamelCase      , _UpperCamelCase   )      ->							Optional[int]:






              """simple docstring"""


              __snake_case       	=							self.linear(self.silu(self.emb(_UpperCamelCase   )   )   )
              __snake_case	,    __snake_case       	=							torch.chunk(_UpperCamelCase      , 2   )
              __snake_case       	=							self.norm(_UpperCamelCase   ) * (1 + scale) + shift
              return x






class     __snake_case    (				nn.Module  ):
       """simple docstring"""







       def __init__(		self      , _UpperCamelCase      , _UpperCamelCase   )      ->							List[str]:






              """simple docstring"""


              super().__init__()

              __snake_case       	=							CombinedTimestepLabelEmbeddings(_UpperCamelCase      , _UpperCamelCase   )

              __snake_case       	=							nn.SiLU()
              __snake_case       	=							nn.Linear(_UpperCamelCase      , 6 * embedding_dim      , bias=_UpperCamelCase   )
              __snake_case       	=							nn.LayerNorm(_UpperCamelCase      , elementwise_affine=_UpperCamelCase      , eps=1E-6   )






       def 			a		(		self      , _UpperCamelCase      , _UpperCamelCase      , _UpperCamelCase      , _UpperCamelCase=None   )      ->							Optional[Any]:






              """simple docstring"""


              __snake_case       	=							self.linear(self.silu(self.emb(_UpperCamelCase      , _UpperCamelCase      , hidden_dtype=_UpperCamelCase   )   )   )
              __snake_case	,    __snake_case	,    __snake_case	,    __snake_case	,    __snake_case	,    __snake_case       	=							emb.chunk(6      , dim=1   )
              __snake_case       	=							self.norm(_UpperCamelCase   ) * (1 + scale_msa[:, None]) + shift_msa[:, None]
              return x, gate_msa, shift_mlp, scale_mlp, gate_mlp






class     __snake_case    (				nn.Module  ):
       """simple docstring"""







       def __init__(		self      , _UpperCamelCase      , _UpperCamelCase      , _UpperCamelCase      , _UpperCamelCase = None      , _UpperCamelCase = 1E-5   )      ->							List[str]:






              """simple docstring"""


              super().__init__()
              __snake_case       	=							num_groups
              __snake_case       	=							eps

              if act_fn is None:
                     __snake_case       	=							None
              else:
                     __snake_case       	=							get_activation(_UpperCamelCase   )

              __snake_case       	=							nn.Linear(_UpperCamelCase      , out_dim * 2   )






       def 			a		(		self      , _UpperCamelCase      , _UpperCamelCase   )      ->							Optional[Any]:






              """simple docstring"""


              if self.act:
                     __snake_case       	=							self.act(_UpperCamelCase   )
              __snake_case       	=							self.linear(_UpperCamelCase   )
              __snake_case       	=							emb[:, :, None, None]
              __snake_case	,    __snake_case       	=							emb.chunk(2      , dim=1   )

              __snake_case       	=							F.group_norm(_UpperCamelCase      , self.num_groups      , eps=self.eps   )
              __snake_case       	=							x * (1 + scale) + shift
              return x




# Copyright 2021 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from pathlib import Path

import torch

from ...utils import is_npu_available, is_xpu_available
from .config_args import ClusterConfig, default_json_config_file
from .config_utils import SubcommandHelpFormatter


UpperCamelCase__		 =     '''Create a default config file for Accelerate with only a few flags set.'''







def 						lowerCamelCase__      ( __A    :List[Any]="no"	,__A    :str = default_json_config_file	,__A    :bool = False		):


       """simple docstring"""




       __snake_case       	=							Path(__A		)
       path.parent.mkdir(parents=__A	,exist_ok=__A		)
       if path.exists():
              print(
                  F'Configuration already exists at {save_location}, will not override. Run `accelerate config` manually or pass a different `save_location`.'		)
              return False
       __snake_case       	=							mixed_precision.lower()
       if mixed_precision not in ["no", "fp16", "bf16", "fp8"]:
              raise ValueError(
                  F'`mixed_precision` should be one of \'no\', \'fp16\', \'bf16\', or \'fp8\'. Received {mixed_precision}'		)
       __snake_case       	=							{
           """compute_environment""": """LOCAL_MACHINE""",
           """mixed_precision""": mixed_precision,
       }
       if torch.cuda.is_available():
              __snake_case       	=							torch.cuda.device_count()
              __snake_case       	=							num_gpus
              __snake_case       	=							False
              if num_gpus > 1:
                     __snake_case       	=							"""MULTI_GPU"""
              else:
                     __snake_case       	=							"""NO"""
       elif is_xpu_available() and use_xpu:
              __snake_case       	=							torch.xpu.device_count()
              __snake_case       	=							num_xpus
              __snake_case       	=							False
              if num_xpus > 1:
                     __snake_case       	=							"""MULTI_XPU"""
              else:
                     __snake_case       	=							"""NO"""
       elif is_npu_available():
              __snake_case       	=							torch.npu.device_count()
              __snake_case       	=							num_npus
              __snake_case       	=							False
              if num_npus > 1:
                     __snake_case       	=							"""MULTI_NPU"""
              else:
                     __snake_case       	=							"""NO"""
       else:
              __snake_case       	=							0
              __snake_case       	=							True
              __snake_case       	=							1
              __snake_case       	=							"""NO"""
       __snake_case       	=							ClusterConfig(**__A		)
       config.to_json_file(__A		)
       return path







def 						lowerCamelCase__      ( __A    :Dict	,__A    :List[Any]		):


       """simple docstring"""




       __snake_case       	=							parser.add_parser("""default"""	,parents=__A	,help=__A	,formatter_class=__A		)
       parser.add_argument(
           """--config_file"""	,default=__A	,help=(
               """The path to use to store the config file. Will default to a file named default_config.yaml in the cache """
               """location, which is the content of the environment `HF_HOME` suffixed with 'accelerate', or if you don't have """
               """such an environment variable, your cache directory ('~/.cache' or the content of `XDG_CACHE_HOME`) suffixed """
               """with 'huggingface'."""
           )	,dest="""save_location"""	,)

       parser.add_argument(
           """--mixed_precision"""	,choices=["""no""", """fp16""", """bf16"""]	,type=__A	,help="""Whether or not to use mixed precision training. """
           """Choose between FP16 and BF16 (bfloat16) training. """
           """BF16 training is only supported on Nvidia Ampere GPUs and PyTorch 1.10 or later."""	,default="""no"""	,)
       parser.set_defaults(func=__A		)
       return parser







def 						lowerCamelCase__      ( __A    :Optional[Any]		):


       """simple docstring"""




       __snake_case       	=							write_basic_config(args.mixed_precision	,args.save_location		)
       if config_file:
              print(F'accelerate configuration saved at {config_file}'		)

