




"""simple docstring"""







from dataclasses import dataclass
from typing import Dict, Optional, Union

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

from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import BaseOutput
from .attention import BasicTransformerBlock
from .attention_processor import AttentionProcessor, AttnProcessor
from .embeddings import TimestepEmbedding, Timesteps
from .modeling_utils import ModelMixin






@dataclass
class    SCREAMING_SNAKE_CASE__       (       UpperCAmelCase__       ):
						_a         =    42






class    SCREAMING_SNAKE_CASE__       (       UpperCAmelCase__    ,					UpperCAmelCase__       ):


						@register_to_config
						def __init__(				self					:      Union[str, Any]    ,    lowerCAmelCase					:      str = 32    ,    lowerCAmelCase					:      Dict = 64    ,    lowerCAmelCase					:      Union[str, Any] = 20    ,    lowerCAmelCase					:      List[Any] = 768    ,    lowerCAmelCase					:      List[Any]=77    ,    lowerCAmelCase					:      Optional[int]=4    ,    lowerCAmelCase					:      Optional[Any] = 0.0    ,    lowerCAmelCase					:      str = "silu"    ,    lowerCAmelCase					:      Optional[int] = None    ,    lowerCAmelCase					:      int = None    ,    lowerCAmelCase					:      int = "linear"    ,    lowerCAmelCase					:      str = "prd"    ,    lowerCAmelCase					:      Tuple = None    ,    lowerCAmelCase					:      Optional[Any] = None    ,    lowerCAmelCase					:      Any = None    ,    ):
										super().__init__()
										lowerCAmelCase						=					num_attention_heads
										lowerCAmelCase						=					attention_head_dim
										lowerCAmelCase						=					num_attention_heads * attention_head_dim
										lowerCAmelCase						=					additional_embeddings

										lowerCAmelCase						=					time_embed_dim or inner_dim
										lowerCAmelCase						=					embedding_proj_dim or embedding_dim
										lowerCAmelCase						=					clip_embed_dim or embedding_dim

										lowerCAmelCase						=					Timesteps(_UpperCAmelCase    ,    _UpperCAmelCase    ,    0       )
										lowerCAmelCase						=					TimestepEmbedding(_UpperCAmelCase    ,    _UpperCAmelCase    ,    out_dim=_UpperCAmelCase    ,    act_fn=_UpperCAmelCase       )

										lowerCAmelCase						=					nn.Linear(_UpperCAmelCase    ,    _UpperCAmelCase       )

										if embedding_proj_norm_type is None:
														lowerCAmelCase						=					None
										elif embedding_proj_norm_type == "layer":
														lowerCAmelCase						=					nn.LayerNorm(_UpperCAmelCase       )
										else:
														raise ValueError(f'''unsupported embedding_proj_norm_type: {embedding_proj_norm_type}'''       )

										lowerCAmelCase						=					nn.Linear(_UpperCAmelCase    ,    _UpperCAmelCase       )

										if encoder_hid_proj_type is None:
														lowerCAmelCase						=					None
										elif encoder_hid_proj_type == "linear":
														lowerCAmelCase						=					nn.Linear(_UpperCAmelCase    ,    _UpperCAmelCase       )
										else:
														raise ValueError(f'''unsupported encoder_hid_proj_type: {encoder_hid_proj_type}'''       )

										lowerCAmelCase						=					nn.Parameter(torch.zeros(1    ,    num_embeddings + additional_embeddings    ,    _UpperCAmelCase       )       )

										if added_emb_type == "prd":
														lowerCAmelCase						=					nn.Parameter(torch.zeros(1    ,    1    ,    _UpperCAmelCase       )       )
										elif added_emb_type is None:
														lowerCAmelCase						=					None
										else:
														raise ValueError(
														    f'''`added_emb_type`: {added_emb_type} is not supported. Make sure to choose one of `\'prd\'` or `None`.'''       )

										lowerCAmelCase						=					nn.ModuleList(
										    [
										        BasicTransformerBlock(
										            _UpperCAmelCase    ,    _UpperCAmelCase    ,    _UpperCAmelCase    ,    dropout=_UpperCAmelCase    ,    activation_fn="""gelu"""    ,    attention_bias=_UpperCAmelCase    ,    )
										        for d in range(_UpperCAmelCase       )
										    ]       )

										if norm_in_type == "layer":
														lowerCAmelCase						=					nn.LayerNorm(_UpperCAmelCase       )
										elif norm_in_type is None:
														lowerCAmelCase						=					None
										else:
														raise ValueError(f'''Unsupported norm_in_type: {norm_in_type}.'''       )

										lowerCAmelCase						=					nn.LayerNorm(_UpperCAmelCase       )

										lowerCAmelCase						=					nn.Linear(_UpperCAmelCase    ,    _UpperCAmelCase       )

										lowerCAmelCase						=					torch.full(
										    [num_embeddings + additional_embeddings, num_embeddings + additional_embeddings]    ,    -1_0000.0       )
										causal_attention_mask.triu_(1       )
										lowerCAmelCase						=					causal_attention_mask[None, ...]
										self.register_buffer("""causal_attention_mask"""    ,    _UpperCAmelCase    ,    persistent=_UpperCAmelCase       )

										lowerCAmelCase						=					nn.Parameter(torch.zeros(1    ,    _UpperCAmelCase       )       )
										lowerCAmelCase						=					nn.Parameter(torch.zeros(1    ,    _UpperCAmelCase       )       )


						@property
						# Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.attn_processors
						def 	__lowercase			(				self					:      str       ):
										lowerCAmelCase						=					{}

										def fn_recursive_add_processors(lowerCAmelCase					:      Optional[Any]    ,    lowerCAmelCase					:      Any    ,    lowerCAmelCase					:      List[Any]       ):
														if hasattr(_UpperCAmelCase    ,    """set_processor"""       ):
																		lowerCAmelCase						=					module.processor

														for sub_name, child in module.named_children():
																		fn_recursive_add_processors(f'''{name}.{sub_name}'''    ,    _UpperCAmelCase    ,    _UpperCAmelCase       )

														return processors

										for name, module in self.named_children():
														fn_recursive_add_processors(_UpperCAmelCase    ,    _UpperCAmelCase    ,    _UpperCAmelCase       )

										return processors


						def 	__lowercase			(				self					:      Any    ,    lowerCAmelCase					:      str       ):
										lowerCAmelCase						=					len(self.attn_processors.keys()       )

										if isinstance(_UpperCAmelCase    ,    _UpperCAmelCase       ) and len(_UpperCAmelCase       ) != count:
														raise ValueError(
														    f'''A dict of processors was passed, but the number of processors {len(_UpperCAmelCase       )} does not match the'''
														    f''' number of attention layers: {count}. Please make sure to pass {count} processor classes.'''       )

										def fn_recursive_attn_processor(lowerCAmelCase					:      str    ,    lowerCAmelCase					:      Tuple    ,    lowerCAmelCase					:      Union[str, Any]       ):
														if hasattr(_UpperCAmelCase    ,    """set_processor"""       ):
																		if not isinstance(_UpperCAmelCase    ,    _UpperCAmelCase       ):
																						module.set_processor(_UpperCAmelCase       )
																		else:
																						module.set_processor(processor.pop(f'''{name}.processor'''       )       )

														for sub_name, child in module.named_children():
																		fn_recursive_attn_processor(f'''{name}.{sub_name}'''    ,    _UpperCAmelCase    ,    _UpperCAmelCase       )

										for name, module in self.named_children():
														fn_recursive_attn_processor(_UpperCAmelCase    ,    _UpperCAmelCase    ,    _UpperCAmelCase       )


						def 	__lowercase			(				self					:      Dict       ):
										self.set_attn_processor(AttnProcessor()       )


						def 	__lowercase			(				self					:      Tuple    ,    lowerCAmelCase					:      Optional[int]    ,    lowerCAmelCase					:      Tuple    ,    lowerCAmelCase					:      Dict    ,    lowerCAmelCase					:      str = None    ,    lowerCAmelCase					:      Optional[Any] = None    ,    lowerCAmelCase					:      str = True    ,    ):
										lowerCAmelCase						=					hidden_states.shape[0]

										lowerCAmelCase						=					timestep
										if not torch.is_tensor(_UpperCAmelCase       ):
														lowerCAmelCase						=					torch.tensor([timesteps]    ,    dtype=torch.long    ,    device=hidden_states.device       )
										elif torch.is_tensor(_UpperCAmelCase       ) and len(timesteps.shape       ) == 0:
														lowerCAmelCase						=					timesteps[None].to(hidden_states.device       )

										# broadcast to batch dimension in a way that's compatible with ONNX/Core ML
										lowerCAmelCase						=					timesteps * torch.ones(_UpperCAmelCase    ,    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 be fp16, so we need to cast here.
										lowerCAmelCase						=					timesteps_projected.to(dtype=self.dtype       )
										lowerCAmelCase						=					self.time_embedding(_UpperCAmelCase       )

										if self.embedding_proj_norm is not None:
														lowerCAmelCase						=					self.embedding_proj_norm(_UpperCAmelCase       )

										lowerCAmelCase						=					self.embedding_proj(_UpperCAmelCase       )
										if self.encoder_hidden_states_proj is not None and encoder_hidden_states is not None:
														lowerCAmelCase						=					self.encoder_hidden_states_proj(_UpperCAmelCase       )
										elif self.encoder_hidden_states_proj is not None and encoder_hidden_states is None:
														raise ValueError("""`encoder_hidden_states_proj` requires `encoder_hidden_states` to be set"""       )

										lowerCAmelCase						=					self.proj_in(_UpperCAmelCase       )

										lowerCAmelCase						=					self.positional_embedding.to(hidden_states.dtype       )

										lowerCAmelCase						=					[]
										lowerCAmelCase						=					0

										if encoder_hidden_states is not None:
														additional_embeds.append(_UpperCAmelCase       )
														additional_embeddings_len += encoder_hidden_states.shape[1]

										if len(proj_embeddings.shape       ) == 2:
														lowerCAmelCase						=					proj_embeddings[:, None, :]

										if len(hidden_states.shape       ) == 2:
														lowerCAmelCase						=					hidden_states[:, None, :]

										lowerCAmelCase						=					additional_embeds + [
										    proj_embeddings,
										    time_embeddings[:, None, :],
										    hidden_states,
										]

										if self.prd_embedding is not None:
														lowerCAmelCase						=					self.prd_embedding.to(hidden_states.dtype       ).expand(_UpperCAmelCase    ,    -1    ,    -1       )
														additional_embeds.append(_UpperCAmelCase       )

										lowerCAmelCase						=					torch.cat(
										    _UpperCAmelCase    ,    dim=1    ,    )

										# Allow positional_embedding to not include the `addtional_embeddings` and instead pad it with zeros for these additional tokens
										lowerCAmelCase						=					additional_embeddings_len + proj_embeddings.shape[1] + 1
										if positional_embeddings.shape[1] < hidden_states.shape[1]:
														lowerCAmelCase						=					F.pad(
														    _UpperCAmelCase    ,    (
														        0,
														        0,
														        additional_embeddings_len,
														        self.prd_embedding.shape[1] if self.prd_embedding is not None else 0,
														    )    ,    value=0.0    ,    )

										lowerCAmelCase						=					hidden_states + positional_embeddings

										if attention_mask is not None:
														lowerCAmelCase						=					(1 - attention_mask.to(hidden_states.dtype       )) * -1_0000.0
														lowerCAmelCase						=					F.pad(_UpperCAmelCase    ,    (0, self.additional_embeddings)    ,    value=0.0       )
														lowerCAmelCase						=					(attention_mask[:, None, :] + self.causal_attention_mask).to(hidden_states.dtype       )
														lowerCAmelCase						=					attention_mask.repeat_interleave(self.config.num_attention_heads    ,    dim=0       )

										if self.norm_in is not None:
														lowerCAmelCase						=					self.norm_in(_UpperCAmelCase       )

										for block in self.transformer_blocks:
														lowerCAmelCase						=					block(_UpperCAmelCase    ,    attention_mask=_UpperCAmelCase       )

										lowerCAmelCase						=					self.norm_out(_UpperCAmelCase       )

										if self.prd_embedding is not None:
														lowerCAmelCase						=					hidden_states[:, -1]
										else:
														lowerCAmelCase						=					hidden_states[:, additional_embeddings_len:]

										lowerCAmelCase						=					self.proj_to_clip_embeddings(_UpperCAmelCase       )

										if not return_dict:
														return (predicted_image_embedding,)

										return PriorTransformerOutput(predicted_image_embedding=_UpperCAmelCase       )




						def 	__lowercase			(				self					:      Optional[int]    ,    lowerCAmelCase					:      Optional[Any]       ):
										lowerCAmelCase						=					(prior_latents * self.clip_std) + self.clip_mean
										return prior_latents













import argparse

import torch

from ...utils import logging
from . import AlbertConfig, AlbertForPreTraining, load_tf_weights_in_albert


logging.set_verbosity_info()






def      _snake_case     (__lowercase     ,   __lowercase     ,   __lowercase):
   # Initialise PyTorch model
   UpperCamelCase_						=  AlbertConfig.from_json_file(__lowercase)
   print(f"""Building PyTorch model from configuration: {config}""")
   UpperCamelCase_						=  AlbertForPreTraining(__lowercase)

   # Load weights from tf checkpoint
   load_tf_weights_in_albert(__lowercase     ,   __lowercase     ,   __lowercase)

   # Save pytorch-model
   print(f"""Save PyTorch model to {pytorch_dump_path}""")
   torch.save(model.state_dict()     ,   __lowercase)


if __name__ == "__main__":
 snake_case__   :						Tuple													=   argparse.ArgumentParser()
 # Required parameters
 parser.add_argument(
     """--tf_checkpoint_path""", default=None, type=str, required=True, help="""Path to the TensorFlow checkpoint path."""
 )
 parser.add_argument(
     """--albert_config_file""",
     default=None,
     type=str,
     required=True,
     help=(
         """The config json file corresponding to the pre-trained ALBERT model. \n"""
         """This specifies the model architecture."""
     ),
 )
 parser.add_argument(
     """--pytorch_dump_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model."""
 )
 snake_case__   :						str													=   parser.parse_args()
 convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.albert_config_file, args.pytorch_dump_path)





