

'''simple docstring'''
import torch
from torch import nn
from torch.nn import CrossEntropyLoss, MSELoss

from transformers.file_utils import add_start_docstrings, add_start_docstrings_to_model_forward
from transformers.models.bert.modeling_bert import (
    BERT_INPUTS_DOCSTRING,
    BERT_START_DOCSTRING,
    BertEmbeddings,
    BertLayer,
    BertPooler,
    BertPreTrainedModel,
)


def 	_lowerCAmelCase (						_UpperCamelCase						:					Dict    )				->      Tuple:
     """simple docstring"""




     _SCREAMING_SNAKE_CASE							   =torch.exp(_UpperCamelCase    )
     _SCREAMING_SNAKE_CASE							   =torch.sum(_UpperCamelCase							,			dim=1    )  # sum of exp(x_i)
     _SCREAMING_SNAKE_CASE							   =torch.sum(x * exp_x							,			dim=1    )  # sum of x_i * exp(x_i)
     return torch.log(_UpperCamelCase    ) - B / A







class 							A__   (	nn.Module  ):





  def __init__(		self				:     Tuple							, _a				:     Union[str, Any]			)     ->   Tuple:





       '''simple docstring'''






       super().__init__()
       _SCREAMING_SNAKE_CASE							   =config.output_attentions
       _SCREAMING_SNAKE_CASE							   =config.output_hidden_states
       _SCREAMING_SNAKE_CASE							   =nn.ModuleList([BertLayer(_a			) for _ in range(config.num_hidden_layers			)]			)
       _SCREAMING_SNAKE_CASE							   =nn.ModuleList([BertHighway(_a			) for _ in range(config.num_hidden_layers			)]			)

       _SCREAMING_SNAKE_CASE							   =[-1 for _ in range(config.num_hidden_layers			)]





  def 						A  (		self				:     Union[str, Any]							, _a				:     int			)     ->   Optional[Any]:





       '''simple docstring'''






       if (type(_a			) is float) or (type(_a			) is int):
            for i in range(len(self.early_exit_entropy			)			):
                 _SCREAMING_SNAKE_CASE							   =x
       else:
            _SCREAMING_SNAKE_CASE							   =x





  def 						A  (		self				:     Any							, _a				:     Optional[Any]			)     ->   int:





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE							   =pooler.state_dict()
       for highway in self.highway:
            for name, param in highway.pooler.state_dict().items():
                 param.copy_(loaded_model[name]			)





  def 						A  (		self				:     Union[str, Any]							, _a				:     Tuple							, _a				:     Tuple=None							, _a				:     Tuple=None							, _a				:     List[Any]=None							, _a				:     Optional[Any]=None							, )     ->   str:





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE							   =()
       _SCREAMING_SNAKE_CASE							   =()
       _SCREAMING_SNAKE_CASE							   =()
       for i, layer_module in enumerate(self.layer			):
            if self.output_hidden_states:
                 _SCREAMING_SNAKE_CASE							   =all_hidden_states + (hidden_states,)

            _SCREAMING_SNAKE_CASE							   =layer_module(
                _a							, _a							, head_mask[i]							, _a							, _a			)
            _SCREAMING_SNAKE_CASE							   =layer_outputs[0]

            if self.output_attentions:
                 _SCREAMING_SNAKE_CASE							   =all_attentions + (layer_outputs[1],)

            _SCREAMING_SNAKE_CASE							   =(hidden_states,)
            if self.output_hidden_states:
                 _SCREAMING_SNAKE_CASE							   =current_outputs + (all_hidden_states,)
            if self.output_attentions:
                 _SCREAMING_SNAKE_CASE							   =current_outputs + (all_attentions,)

            _SCREAMING_SNAKE_CASE							   =self.highway[i](_a			)
            # logits, pooled_output

            if not self.training:
                 _SCREAMING_SNAKE_CASE							   =highway_exit[0]
                 _SCREAMING_SNAKE_CASE							   =entropy(_a			)
                 _SCREAMING_SNAKE_CASE							   =highway_exit + (highway_entropy,)  # logits, hidden_states(?), entropy
                 _SCREAMING_SNAKE_CASE							   =all_highway_exits + (highway_exit,)

                 if highway_entropy < self.early_exit_entropy[i]:
                      _SCREAMING_SNAKE_CASE							   =(highway_logits,) + current_outputs[1:] + (all_highway_exits,)
                      raise HighwayException(_a							, i + 1			)
            else:
                 _SCREAMING_SNAKE_CASE							   =all_highway_exits + (highway_exit,)

        # Add last layer
       if self.output_hidden_states:
            _SCREAMING_SNAKE_CASE							   =all_hidden_states + (hidden_states,)

       _SCREAMING_SNAKE_CASE							   =(hidden_states,)
       if self.output_hidden_states:
            _SCREAMING_SNAKE_CASE							   =outputs + (all_hidden_states,)
       if self.output_attentions:
            _SCREAMING_SNAKE_CASE							   =outputs + (all_attentions,)

       _SCREAMING_SNAKE_CASE							   =outputs + (all_highway_exits,)
       return outputs  # last-layer hidden state, (all hidden states), (all attentions), all highway exits







@add_start_docstrings(
    'The Bert Model transformer with early exiting (DeeBERT). '					,       A__					,       )
class 							A__   (	A__  ):





  def __init__(		self				:     Dict							, _a				:     Dict			)     ->   Tuple:





       '''simple docstring'''






       super().__init__(_a			)
       _SCREAMING_SNAKE_CASE							   =config

       _SCREAMING_SNAKE_CASE							   =BertEmbeddings(_a			)
       _SCREAMING_SNAKE_CASE							   =DeeBertEncoder(_a			)
       _SCREAMING_SNAKE_CASE							   =BertPooler(_a			)

       self.init_weights()





  def 						A  (		self				:     int			)     ->   Any:





       '''simple docstring'''






       self.encoder.init_highway_pooler(self.pooler			)





  def 						A  (		self				:     str			)     ->   Union[str, Any]:





       '''simple docstring'''






       return self.embeddings.word_embeddings





  def 						A  (		self				:     str							, _a				:     List[str]			)     ->   Tuple:





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE							   =value





  def 						A  (		self				:     Union[str, Any]							, _a				:     Optional[Any]			)     ->   Optional[int]:





       '''simple docstring'''






       for layer, heads in heads_to_prune.items():
            self.encoder.layer[layer].attention.prune_heads(_a			)





  @add_start_docstrings_to_model_forward(_a			)
  def 						A  (		self				:     int							, _a				:     List[str]=None							, _a				:     int=None							, _a				:     List[str]=None							, _a				:     List[Any]=None							, _a				:     List[str]=None							, _a				:     Any=None							, _a				:     List[str]=None							, _a				:     List[Any]=None							, )     ->   List[Any]:





       '''simple docstring'''






       if input_ids is not None and inputs_embeds is not None:
            raise ValueError('You cannot specify both input_ids and inputs_embeds at the same time'			)
       elif input_ids is not None:
            _SCREAMING_SNAKE_CASE							   =input_ids.size()
       elif inputs_embeds is not None:
            _SCREAMING_SNAKE_CASE							   =inputs_embeds.size()[:-1]
       else:
            raise ValueError('You have to specify either input_ids or inputs_embeds'			)

       _SCREAMING_SNAKE_CASE							   =input_ids.device if input_ids is not None else inputs_embeds.device

       if attention_mask is None:
            _SCREAMING_SNAKE_CASE							   =torch.ones(_a							, device=_a			)
       if encoder_attention_mask is None:
            _SCREAMING_SNAKE_CASE							   =torch.ones(_a							, device=_a			)
       if token_type_ids is None:
            _SCREAMING_SNAKE_CASE							   =torch.zeros(_a							, dtype=torch.long							, device=_a			)

       # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
       # ourselves in which case we just need to make it broadcastable to all heads.
       _SCREAMING_SNAKE_CASE							   =self.get_extended_attention_mask(_a							, _a							, _a			)

       # If a 2D ou 3D attention mask is provided for the cross-attention
       # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
       if encoder_attention_mask.dim() == 3:
            _SCREAMING_SNAKE_CASE							   =encoder_attention_mask[:, None, :, :]
       if encoder_attention_mask.dim() == 2:
            _SCREAMING_SNAKE_CASE							   =encoder_attention_mask[:, None, None, :]

       _SCREAMING_SNAKE_CASE							   =encoder_extended_attention_mask.to(
           dtype=next(self.parameters()			).dtype			)  # fp16 compatibility
       _SCREAMING_SNAKE_CASE							   =(1.0 - encoder_extended_attention_mask) * -1_00_00.0

       # Prepare head mask if needed
       # 1.0 in head_mask indicate we keep the head
       # attention_probs has shape bsz x n_heads x N x N
       # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
       # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
       _SCREAMING_SNAKE_CASE							   =self.get_head_mask(_a							, self.config.num_hidden_layers			)

       _SCREAMING_SNAKE_CASE							   =self.embeddings(
           input_ids=_a							, position_ids=_a							, token_type_ids=_a							, inputs_embeds=_a			)
       _SCREAMING_SNAKE_CASE							   =self.encoder(
           _a							, attention_mask=_a							, head_mask=_a							, encoder_hidden_states=_a							, encoder_attention_mask=_a							, )
       _SCREAMING_SNAKE_CASE							   =encoder_outputs[0]
       _SCREAMING_SNAKE_CASE							   =self.pooler(_a			)

       _SCREAMING_SNAKE_CASE							   =(
           sequence_output,
           pooled_output,
       ) + encoder_outputs[
           1:
       ]  # add hidden_states and attentions if they are here
       return outputs  # sequence_output, pooled_output, (hidden_states), (attentions), highway exits







class 							A__   (	A__  ):





  def __init__(		self				:     Any							, _a				:     Tuple							, _a				:     Union[str, Any]			)     ->   str:





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE							   =message
       _SCREAMING_SNAKE_CASE							   =exit_layer  # start from 1!







class 							A__   (	nn.Module  ):





  def __init__(		self				:     Optional[Any]							, _a				:     List[str]			)     ->   Any:





       '''simple docstring'''






       super().__init__()
       _SCREAMING_SNAKE_CASE							   =BertPooler(_a			)
       _SCREAMING_SNAKE_CASE							   =nn.Dropout(config.hidden_dropout_prob			)
       _SCREAMING_SNAKE_CASE							   =nn.Linear(config.hidden_size							, config.num_labels			)





  def 						A  (		self				:     Dict							, _a				:     List[str]			)     ->   int:





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE							   =encoder_outputs[0]
       _SCREAMING_SNAKE_CASE							   =self.pooler(_a			)
       # "return" pooler_output

       # BertModel
       _SCREAMING_SNAKE_CASE							   =(pooler_input, pooler_output) + encoder_outputs[1:]
       # "return" bmodel_output

       # Dropout and classification
       _SCREAMING_SNAKE_CASE							   =bmodel_output[1]

       _SCREAMING_SNAKE_CASE							   =self.dropout(_a			)
       _SCREAMING_SNAKE_CASE							   =self.classifier(_a			)

       return logits, pooled_output







@add_start_docstrings(
    'Bert Model (with early exiting - DeeBERT) with a classifier on top,\n    also takes care of multi-layer training. '					,       A__					,       )
class 							A__   (	A__  ):





  def __init__(		self				:     Optional[int]							, _a				:     Union[str, Any]			)     ->   Union[str, Any]:





       '''simple docstring'''






       super().__init__(_a			)
       _SCREAMING_SNAKE_CASE							   =config.num_labels
       _SCREAMING_SNAKE_CASE							   =config.num_hidden_layers

       _SCREAMING_SNAKE_CASE							   =DeeBertModel(_a			)
       _SCREAMING_SNAKE_CASE							   =nn.Dropout(config.hidden_dropout_prob			)
       _SCREAMING_SNAKE_CASE							   =nn.Linear(config.hidden_size							, self.config.num_labels			)

       self.init_weights()





  @add_start_docstrings_to_model_forward(_a			)
  def 						A  (		self				:     str							, _a				:     List[str]=None							, _a				:     Optional[Any]=None							, _a				:     List[Any]=None							, _a				:     List[Any]=None							, _a				:     Optional[Any]=None							, _a				:     int=None							, _a				:     str=None							, _a				:     Optional[int]=-1							, _a				:     Optional[int]=False							, )     ->   Optional[Any]:





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE							   =self.num_layers
       try:
            _SCREAMING_SNAKE_CASE							   =self.bert(
                _a							, attention_mask=_a							, token_type_ids=_a							, position_ids=_a							, head_mask=_a							, inputs_embeds=_a							, )
            # sequence_output, pooled_output, (hidden_states), (attentions), highway exits

            _SCREAMING_SNAKE_CASE							   =outputs[1]

            _SCREAMING_SNAKE_CASE							   =self.dropout(_a			)
            _SCREAMING_SNAKE_CASE							   =self.classifier(_a			)
            _SCREAMING_SNAKE_CASE							   =(logits,) + outputs[2:]  # add hidden states and attention if they are here
       except HighwayException as e:
            _SCREAMING_SNAKE_CASE							   =e.message
            _SCREAMING_SNAKE_CASE							   =e.exit_layer
            _SCREAMING_SNAKE_CASE							   =outputs[0]

       if not self.training:
            _SCREAMING_SNAKE_CASE							   =entropy(_a			)
            _SCREAMING_SNAKE_CASE							   =[]
            _SCREAMING_SNAKE_CASE							   =[]
       if labels is not None:
            if self.num_labels == 1:
                 #  We are doing regression
                 _SCREAMING_SNAKE_CASE							   =MSELoss()
                 _SCREAMING_SNAKE_CASE							   =loss_fct(logits.view(-1			)							, labels.view(-1			)			)
            else:
                 _SCREAMING_SNAKE_CASE							   =CrossEntropyLoss()
                 _SCREAMING_SNAKE_CASE							   =loss_fct(logits.view(-1							, self.num_labels			)							, labels.view(-1			)			)

            # work with highway exits
            _SCREAMING_SNAKE_CASE							   =[]
            for highway_exit in outputs[-1]:
                 _SCREAMING_SNAKE_CASE							   =highway_exit[0]
                 if not self.training:
                      highway_logits_all.append(_a			)
                      highway_entropy.append(highway_exit[2]			)
                 if self.num_labels == 1:
                      #  We are doing regression
                      _SCREAMING_SNAKE_CASE							   =MSELoss()
                      _SCREAMING_SNAKE_CASE							   =loss_fct(highway_logits.view(-1			)							, labels.view(-1			)			)
                 else:
                      _SCREAMING_SNAKE_CASE							   =CrossEntropyLoss()
                      _SCREAMING_SNAKE_CASE							   =loss_fct(highway_logits.view(-1							, self.num_labels			)							, labels.view(-1			)			)
                 highway_losses.append(_a			)

            if train_highway:
                 _SCREAMING_SNAKE_CASE							   =(sum(highway_losses[:-1]			),) + outputs
                 # exclude the final highway, of course
            else:
                 _SCREAMING_SNAKE_CASE							   =(loss,) + outputs
       if not self.training:
            _SCREAMING_SNAKE_CASE							   =outputs + ((original_entropy, highway_entropy), exit_layer)
            if output_layer >= 0:
                 _SCREAMING_SNAKE_CASE							   =(
                     (outputs[0],) + (highway_logits_all[output_layer],) + outputs[2:]
                 )  # use the highway of the last layer

       return outputs  # (loss), logits, (hidden_states), (attentions), (highway_exits)



'''simple docstring'''
import argparse
import io

import requests
import torch
from omegaconf import OmegaConf

from diffusers import AutoencoderKL
from diffusers.pipelines.stable_diffusion.convert_from_ckpt import (
    assign_to_checkpoint,
    conv_attn_to_linear,
    create_vae_diffusers_config,
    renew_vae_attention_paths,
    renew_vae_resnet_paths,
)


def 	_lowerCAmelCase (						_UpperCamelCase						:					Tuple							,			_UpperCamelCase						:					List[Any]    )				->      Dict:
     """simple docstring"""




     _SCREAMING_SNAKE_CASE							   =checkpoint

     _SCREAMING_SNAKE_CASE							   ={}

     _SCREAMING_SNAKE_CASE							   =vae_state_dict['encoder.conv_in.weight']
     _SCREAMING_SNAKE_CASE							   =vae_state_dict['encoder.conv_in.bias']
     _SCREAMING_SNAKE_CASE							   =vae_state_dict['encoder.conv_out.weight']
     _SCREAMING_SNAKE_CASE							   =vae_state_dict['encoder.conv_out.bias']
     _SCREAMING_SNAKE_CASE							   =vae_state_dict['encoder.norm_out.weight']
     _SCREAMING_SNAKE_CASE							   =vae_state_dict['encoder.norm_out.bias']

     _SCREAMING_SNAKE_CASE							   =vae_state_dict['decoder.conv_in.weight']
     _SCREAMING_SNAKE_CASE							   =vae_state_dict['decoder.conv_in.bias']
     _SCREAMING_SNAKE_CASE							   =vae_state_dict['decoder.conv_out.weight']
     _SCREAMING_SNAKE_CASE							   =vae_state_dict['decoder.conv_out.bias']
     _SCREAMING_SNAKE_CASE							   =vae_state_dict['decoder.norm_out.weight']
     _SCREAMING_SNAKE_CASE							   =vae_state_dict['decoder.norm_out.bias']

     _SCREAMING_SNAKE_CASE							   =vae_state_dict['quant_conv.weight']
     _SCREAMING_SNAKE_CASE							   =vae_state_dict['quant_conv.bias']
     _SCREAMING_SNAKE_CASE							   =vae_state_dict['post_quant_conv.weight']
     _SCREAMING_SNAKE_CASE							   =vae_state_dict['post_quant_conv.bias']

     # Retrieves the keys for the encoder down blocks only
     _SCREAMING_SNAKE_CASE							   =len({'.'.join(layer.split('.'    )[:3]    ) for layer in vae_state_dict if 'encoder.down' in layer}    )
     _SCREAMING_SNAKE_CASE							   ={
         layer_id: [key for key in vae_state_dict if f"down.{layer_id}" in key] for layer_id in range(_UpperCamelCase    )
     }

     # Retrieves the keys for the decoder up blocks only
     _SCREAMING_SNAKE_CASE							   =len({'.'.join(layer.split('.'    )[:3]    ) for layer in vae_state_dict if 'decoder.up' in layer}    )
     _SCREAMING_SNAKE_CASE							   ={
         layer_id: [key for key in vae_state_dict if f"up.{layer_id}" in key] for layer_id in range(_UpperCamelCase    )
     }

     for i in range(_UpperCamelCase    ):
          _SCREAMING_SNAKE_CASE							   =[key for key in down_blocks[i] if f"down.{i}" in key and f"down.{i}.downsample" not in key]

          if f"encoder.down.{i}.downsample.conv.weight" in vae_state_dict:
               _SCREAMING_SNAKE_CASE							   =vae_state_dict.pop(
                   f"encoder.down.{i}.downsample.conv.weight"    )
               _SCREAMING_SNAKE_CASE							   =vae_state_dict.pop(
                   f"encoder.down.{i}.downsample.conv.bias"    )

          _SCREAMING_SNAKE_CASE							   =renew_vae_resnet_paths(_UpperCamelCase    )
          _SCREAMING_SNAKE_CASE							   ={'old': f"down.{i}.block", 'new': f"down_blocks.{i}.resnets"}
          assign_to_checkpoint(_UpperCamelCase							,			_UpperCamelCase							,			_UpperCamelCase							,			additional_replacements=[meta_path]							,			config=_UpperCamelCase    )

     _SCREAMING_SNAKE_CASE							   =[key for key in vae_state_dict if 'encoder.mid.block' in key]
     _SCREAMING_SNAKE_CASE							   =2
     for i in range(1							,			num_mid_res_blocks + 1    ):
          _SCREAMING_SNAKE_CASE							   =[key for key in mid_resnets if f"encoder.mid.block_{i}" in key]

          _SCREAMING_SNAKE_CASE							   =renew_vae_resnet_paths(_UpperCamelCase    )
          _SCREAMING_SNAKE_CASE							   ={'old': f"mid.block_{i}", 'new': f"mid_block.resnets.{i - 1}"}
          assign_to_checkpoint(_UpperCamelCase							,			_UpperCamelCase							,			_UpperCamelCase							,			additional_replacements=[meta_path]							,			config=_UpperCamelCase    )

     _SCREAMING_SNAKE_CASE							   =[key for key in vae_state_dict if 'encoder.mid.attn' in key]
     _SCREAMING_SNAKE_CASE							   =renew_vae_attention_paths(_UpperCamelCase    )
     _SCREAMING_SNAKE_CASE							   ={'old': 'mid.attn_1', 'new': 'mid_block.attentions.0'}
     assign_to_checkpoint(_UpperCamelCase							,			_UpperCamelCase							,			_UpperCamelCase							,			additional_replacements=[meta_path]							,			config=_UpperCamelCase    )
     conv_attn_to_linear(_UpperCamelCase    )

     for i in range(_UpperCamelCase    ):
          _SCREAMING_SNAKE_CASE							   =num_up_blocks - 1 - i
          _SCREAMING_SNAKE_CASE							   =[
              key for key in up_blocks[block_id] if f"up.{block_id}" in key and f"up.{block_id}.upsample" not in key
          ]

          if f"decoder.up.{block_id}.upsample.conv.weight" in vae_state_dict:
               _SCREAMING_SNAKE_CASE							   =vae_state_dict[
                   f"decoder.up.{block_id}.upsample.conv.weight"
               ]
               _SCREAMING_SNAKE_CASE							   =vae_state_dict[
                   f"decoder.up.{block_id}.upsample.conv.bias"
               ]

          _SCREAMING_SNAKE_CASE							   =renew_vae_resnet_paths(_UpperCamelCase    )
          _SCREAMING_SNAKE_CASE							   ={'old': f"up.{block_id}.block", 'new': f"up_blocks.{i}.resnets"}
          assign_to_checkpoint(_UpperCamelCase							,			_UpperCamelCase							,			_UpperCamelCase							,			additional_replacements=[meta_path]							,			config=_UpperCamelCase    )

     _SCREAMING_SNAKE_CASE							   =[key for key in vae_state_dict if 'decoder.mid.block' in key]
     _SCREAMING_SNAKE_CASE							   =2
     for i in range(1							,			num_mid_res_blocks + 1    ):
          _SCREAMING_SNAKE_CASE							   =[key for key in mid_resnets if f"decoder.mid.block_{i}" in key]

          _SCREAMING_SNAKE_CASE							   =renew_vae_resnet_paths(_UpperCamelCase    )
          _SCREAMING_SNAKE_CASE							   ={'old': f"mid.block_{i}", 'new': f"mid_block.resnets.{i - 1}"}
          assign_to_checkpoint(_UpperCamelCase							,			_UpperCamelCase							,			_UpperCamelCase							,			additional_replacements=[meta_path]							,			config=_UpperCamelCase    )

     _SCREAMING_SNAKE_CASE							   =[key for key in vae_state_dict if 'decoder.mid.attn' in key]
     _SCREAMING_SNAKE_CASE							   =renew_vae_attention_paths(_UpperCamelCase    )
     _SCREAMING_SNAKE_CASE							   ={'old': 'mid.attn_1', 'new': 'mid_block.attentions.0'}
     assign_to_checkpoint(_UpperCamelCase							,			_UpperCamelCase							,			_UpperCamelCase							,			additional_replacements=[meta_path]							,			config=_UpperCamelCase    )
     conv_attn_to_linear(_UpperCamelCase    )
     return new_checkpoint


def 	_lowerCAmelCase (						_UpperCamelCase						:					str							,			_UpperCamelCase						:					str							,			)				->      List[Any]:
     """simple docstring"""




     _SCREAMING_SNAKE_CASE							   =requests.get(
         ' https://raw.githubusercontent.com/CompVis/stable-diffusion/main/configs/stable-diffusion/v1-inference.yaml'    )
     _SCREAMING_SNAKE_CASE							   =io.BytesIO(r.content    )

     _SCREAMING_SNAKE_CASE							   =OmegaConf.load(_UpperCamelCase    )
     _SCREAMING_SNAKE_CASE							   =5_12
     _SCREAMING_SNAKE_CASE							   ='cuda' if torch.cuda.is_available() else 'cpu'
     if checkpoint_path.endswith('safetensors'    ):
          from safetensors import safe_open

          _SCREAMING_SNAKE_CASE							   ={}
          with safe_open(_UpperCamelCase							,			framework='pt'							,			device='cpu'    ) as f:
               for key in f.keys():
                    _SCREAMING_SNAKE_CASE							   =f.get_tensor(_UpperCamelCase    )
     else:
          _SCREAMING_SNAKE_CASE							   =torch.load(_UpperCamelCase							,			map_location=_UpperCamelCase    )['state_dict']

     # Convert the VAE model.
     _SCREAMING_SNAKE_CASE							   =create_vae_diffusers_config(_UpperCamelCase							,			image_size=_UpperCamelCase    )
     _SCREAMING_SNAKE_CASE							   =custom_convert_ldm_vae_checkpoint(_UpperCamelCase							,			_UpperCamelCase    )

     _SCREAMING_SNAKE_CASE							   =AutoencoderKL(**_UpperCamelCase    )
     vae.load_state_dict(_UpperCamelCase    )
     vae.save_pretrained(_UpperCamelCase    )


if __name__ == "__main__":
     lowerCamelCase			:				Union[str, Any] 			=					argparse.ArgumentParser()

     parser.add_argument("--vae_pt_path", default=None, type=str, required=True, help="Path to the VAE.pt to convert.")
     parser.add_argument("--dump_path", default=None, type=str, required=True, help="Path to the VAE.pt to convert.")

     lowerCamelCase			:				List[str] 			=					parser.parse_args()

     vae_pt_to_vae_diffuser(args.vae_pt_path, args.dump_path)
