


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 							_UpperCamelCase (						nn.Module						):

			'''simple docstring'''







			def __init__(  self  : List[str]       ,  _lowerCamelCase  : int       ,  _lowerCamelCase  : int       ,  _lowerCamelCase  : int       ,  _lowerCamelCase  : List[str]=0.0       ,  _lowerCamelCase  : Optional[int] = None       ,  _lowerCamelCase  : str = "geglu"       ,  _lowerCamelCase  : Optional[int] = None       ,  _lowerCamelCase  : bool = False       ,  _lowerCamelCase  : bool = False       ,  _lowerCamelCase  : bool = False       ,  _lowerCamelCase  : bool = False       ,  _lowerCamelCase  : bool = True       ,  _lowerCamelCase  : str = "layer_norm"       ,  _lowerCamelCase  : bool = False       ,  ):






									'''simple docstring'''



									super().__init__()
									__lowerCamelCase     :      List[Any]       						=						only_cross_attention

									__lowerCamelCase     :      Any       						=						(num_embeds_ada_norm is not None) and norm_type == """ada_norm_zero"""
									__lowerCamelCase     :      Any       						=						(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:
															__lowerCamelCase     :      List[str]       						=						AdaLayerNorm(_lowerCamelCase       ,  _lowerCamelCase							)
									elif self.use_ada_layer_norm_zero:
															__lowerCamelCase     :      Optional[int]       						=						AdaLayerNormZero(_lowerCamelCase       ,  _lowerCamelCase							)
									else:
															__lowerCamelCase     :      Tuple       						=						nn.LayerNorm(_lowerCamelCase       ,  elementwise_affine=_lowerCamelCase							)
									__lowerCamelCase     :      Any       						=						Attention(
									    query_dim=_lowerCamelCase       ,  heads=_lowerCamelCase       ,  dim_head=_lowerCamelCase       ,  dropout=_lowerCamelCase       ,  bias=_lowerCamelCase       ,  cross_attention_dim=cross_attention_dim if only_cross_attention else None       ,  upcast_attention=_lowerCamelCase       ,  )

									# 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.
															__lowerCamelCase     :      Dict       						=						(
															    AdaLayerNorm(_lowerCamelCase       ,  _lowerCamelCase							)
															    if self.use_ada_layer_norm
															    else nn.LayerNorm(_lowerCamelCase       ,  elementwise_affine=_lowerCamelCase							)
															)
															__lowerCamelCase     :      List[Any]       						=						Attention(
															    query_dim=_lowerCamelCase       ,  cross_attention_dim=cross_attention_dim if not double_self_attention else None       ,  heads=_lowerCamelCase       ,  dim_head=_lowerCamelCase       ,  dropout=_lowerCamelCase       ,  bias=_lowerCamelCase       ,  upcast_attention=_lowerCamelCase       ,  )  # is self-attn if encoder_hidden_states is none
									else:
															__lowerCamelCase     :      Any       						=						None
															__lowerCamelCase     :      Union[str, Any]       						=						None

									# 3. Feed-forward
									__lowerCamelCase     :      Union[str, Any]       						=						nn.LayerNorm(_lowerCamelCase       ,  elementwise_affine=_lowerCamelCase							)
									__lowerCamelCase     :      int       						=						FeedForward(_lowerCamelCase       ,  dropout=_lowerCamelCase       ,  activation_fn=_lowerCamelCase       ,  final_dropout=_lowerCamelCase							)

									# let chunk size default to None
									__lowerCamelCase     :      List[Any]       						=						None
									__lowerCamelCase     :      str       						=						0

			def   _snake_case    (  self  : str       ,  _lowerCamelCase  : Optional[int]       ,  _lowerCamelCase  : int							):






									'''simple docstring'''



									__lowerCamelCase     :      int       						=						chunk_size
									__lowerCamelCase     :      Optional[Any]       						=						dim


			def   _snake_case    (  self  : List[Any]       ,  _lowerCamelCase  : torch.FloatTensor       ,  _lowerCamelCase  : Optional[torch.FloatTensor] = None       ,  _lowerCamelCase  : Optional[torch.FloatTensor] = None       ,  _lowerCamelCase  : Optional[torch.FloatTensor] = None       ,  _lowerCamelCase  : Optional[torch.LongTensor] = None       ,  _lowerCamelCase  : Dict[str, Any] = None       ,  _lowerCamelCase  : Optional[torch.LongTensor] = None       ,  ):






									'''simple docstring'''



									if self.use_ada_layer_norm:
															__lowerCamelCase     :      Dict       						=						self.norma(_lowerCamelCase       ,  _lowerCamelCase							)
									elif self.use_ada_layer_norm_zero:
															__lowerCamelCase     :      List[Any]       						=						self.norma(
															    _lowerCamelCase       ,  _lowerCamelCase       ,  _lowerCamelCase       ,  hidden_dtype=hidden_states.dtype							)
									else:
															__lowerCamelCase     :      Any       						=						self.norma(_lowerCamelCase							)

									__lowerCamelCase     :      Tuple       						=						cross_attention_kwargs if cross_attention_kwargs is not None else {}

									__lowerCamelCase     :      Union[str, Any]       						=						self.attna(
									    _lowerCamelCase       ,  encoder_hidden_states=encoder_hidden_states if self.only_cross_attention else None       ,  attention_mask=_lowerCamelCase       ,  **_lowerCamelCase       ,  )
									if self.use_ada_layer_norm_zero:
															__lowerCamelCase     :      Optional[int]       						=						gate_msa.unsqueeze(1							) * attn_output
									__lowerCamelCase     :      Union[str, Any]       						=						attn_output + hidden_states

									# 2. Cross-Attention
									if self.attna is not None:
															__lowerCamelCase     :      Union[str, Any]       						=						(
															    self.norma(_lowerCamelCase       ,  _lowerCamelCase							) if self.use_ada_layer_norm else self.norma(_lowerCamelCase							)
															)

															__lowerCamelCase     :      Union[str, Any]       						=						self.attna(
															    _lowerCamelCase       ,  encoder_hidden_states=_lowerCamelCase       ,  attention_mask=_lowerCamelCase       ,  **_lowerCamelCase       ,  )
															__lowerCamelCase     :      Optional[int]       						=						attn_output + hidden_states

									# 3. Feed-forward
									__lowerCamelCase     :      List[str]       						=						self.norma(_lowerCamelCase							)

									if self.use_ada_layer_norm_zero:
															__lowerCamelCase     :      str       						=						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`."""							)

															__lowerCamelCase     :      Optional[int]       						=						norm_hidden_states.shape[self._chunk_dim] // self._chunk_size
															__lowerCamelCase     :      Tuple       						=						torch.cat(
															    [self.ff(_lowerCamelCase							) for hid_slice in norm_hidden_states.chunk(_lowerCamelCase       ,  dim=self._chunk_dim							)]       ,  dim=self._chunk_dim       ,  )
									else:
															__lowerCamelCase     :      Any       						=						self.ff(_lowerCamelCase							)

									if self.use_ada_layer_norm_zero:
															__lowerCamelCase     :      Union[str, Any]       						=						gate_mlp.unsqueeze(1							) * ff_output

									__lowerCamelCase     :      Any       						=						ff_output + hidden_states

									return hidden_states



class 							_UpperCamelCase (						nn.Module						):

			'''simple docstring'''







			def __init__(  self  : List[str]       ,  _lowerCamelCase  : int       ,  _lowerCamelCase  : Optional[int] = None       ,  _lowerCamelCase  : int = 4       ,  _lowerCamelCase  : float = 0.0       ,  _lowerCamelCase  : str = "geglu"       ,  _lowerCamelCase  : bool = False       ,  ):






									'''simple docstring'''



									super().__init__()
									__lowerCamelCase     :      Optional[Any]       						=						int(dim * mult							)
									__lowerCamelCase     :      Optional[int]       						=						dim_out if dim_out is not None else dim

									if activation_fn == "gelu":
															__lowerCamelCase     :      List[str]       						=						GELU(_lowerCamelCase       ,  _lowerCamelCase							)
									if activation_fn == "gelu-approximate":
															__lowerCamelCase     :      Optional[Any]       						=						GELU(_lowerCamelCase       ,  _lowerCamelCase       ,  approximate="""tanh"""							)
									elif activation_fn == "geglu":
															__lowerCamelCase     :      Any       						=						GEGLU(_lowerCamelCase       ,  _lowerCamelCase							)
									elif activation_fn == "geglu-approximate":
															__lowerCamelCase     :      List[Any]       						=						ApproximateGELU(_lowerCamelCase       ,  _lowerCamelCase							)

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


			def   _snake_case    (  self  : Optional[Any]       ,  _lowerCamelCase  : List[Any]							):






									'''simple docstring'''



									for module in self.net:
															__lowerCamelCase     :      List[str]       						=						module(_lowerCamelCase							)
									return hidden_states



class 							_UpperCamelCase (						nn.Module						):

			'''simple docstring'''







			def __init__(  self  : Any       ,  _lowerCamelCase  : int       ,  _lowerCamelCase  : int       ,  _lowerCamelCase  : str = "none"							):






									'''simple docstring'''



									super().__init__()
									__lowerCamelCase     :      Tuple       						=						nn.Linear(_lowerCamelCase       ,  _lowerCamelCase							)
									__lowerCamelCase     :      Dict       						=						approximate

			def   _snake_case    (  self  : Union[str, Any]       ,  _lowerCamelCase  : str							):






									'''simple docstring'''



									if gate.device.type != "mps":
															return F.gelu(_lowerCamelCase       ,  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   _snake_case    (  self  : Dict       ,  _lowerCamelCase  : List[str]							):






									'''simple docstring'''



									__lowerCamelCase     :      int       						=						self.proj(_lowerCamelCase							)
									__lowerCamelCase     :      Any       						=						self.gelu(_lowerCamelCase							)
									return hidden_states



class 							_UpperCamelCase (						nn.Module						):

			'''simple docstring'''







			def __init__(  self  : Optional[Any]       ,  _lowerCamelCase  : int       ,  _lowerCamelCase  : int							):






									'''simple docstring'''



									super().__init__()
									__lowerCamelCase     :      Optional[int]       						=						nn.Linear(_lowerCamelCase       ,  dim_out * 2							)

			def   _snake_case    (  self  : List[str]       ,  _lowerCamelCase  : List[str]							):






									'''simple docstring'''



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


			def   _snake_case    (  self  : Optional[int]       ,  _lowerCamelCase  : Optional[int]							):






									'''simple docstring'''



									__lowerCamelCase     :      Dict       						=						self.proj(_lowerCamelCase							).chunk(2       ,  dim=-1							)
									return hidden_states * self.gelu(_lowerCamelCase							)



class 							_UpperCamelCase (						nn.Module						):

			'''simple docstring'''







			def __init__(  self  : Union[str, Any]       ,  _lowerCamelCase  : int       ,  _lowerCamelCase  : int							):






									'''simple docstring'''



									super().__init__()
									__lowerCamelCase     :      str       						=						nn.Linear(_lowerCamelCase       ,  _lowerCamelCase							)


			def   _snake_case    (  self  : Dict       ,  _lowerCamelCase  : List[Any]							):






									'''simple docstring'''



									__lowerCamelCase     :      str       						=						self.proj(_lowerCamelCase							)
									return x * torch.sigmoid(1.702 * x							)



class 							_UpperCamelCase (						nn.Module						):

			'''simple docstring'''







			def __init__(  self  : Optional[Any]       ,  _lowerCamelCase  : str       ,  _lowerCamelCase  : Dict							):






									'''simple docstring'''



									super().__init__()
									__lowerCamelCase     :      Tuple       						=						nn.Embedding(_lowerCamelCase       ,  _lowerCamelCase							)
									__lowerCamelCase     :      str       						=						nn.SiLU()
									__lowerCamelCase     :      str       						=						nn.Linear(_lowerCamelCase       ,  embedding_dim * 2							)
									__lowerCamelCase     :      Optional[Any]       						=						nn.LayerNorm(_lowerCamelCase       ,  elementwise_affine=_lowerCamelCase							)


			def   _snake_case    (  self  : Optional[Any]       ,  _lowerCamelCase  : Optional[int]       ,  _lowerCamelCase  : Dict							):






									'''simple docstring'''



									__lowerCamelCase     :      List[str]       						=						self.linear(self.silu(self.emb(_lowerCamelCase							)							)							)
									__lowerCamelCase     :      int       						=						torch.chunk(_lowerCamelCase       ,  2							)
									__lowerCamelCase     :      Union[str, Any]       						=						self.norm(_lowerCamelCase							) * (1 + scale) + shift
									return x



class 							_UpperCamelCase (						nn.Module						):

			'''simple docstring'''







			def __init__(  self  : Union[str, Any]       ,  _lowerCamelCase  : str       ,  _lowerCamelCase  : List[str]							):






									'''simple docstring'''



									super().__init__()

									__lowerCamelCase     :      Optional[Any]       						=						CombinedTimestepLabelEmbeddings(_lowerCamelCase       ,  _lowerCamelCase							)

									__lowerCamelCase     :      Dict       						=						nn.SiLU()
									__lowerCamelCase     :      Any       						=						nn.Linear(_lowerCamelCase       ,  6 * embedding_dim       ,  bias=_lowerCamelCase							)
									__lowerCamelCase     :      Union[str, Any]       						=						nn.LayerNorm(_lowerCamelCase       ,  elementwise_affine=_lowerCamelCase       ,  eps=1E-6							)


			def   _snake_case    (  self  : Optional[Any]       ,  _lowerCamelCase  : Union[str, Any]       ,  _lowerCamelCase  : Optional[Any]       ,  _lowerCamelCase  : List[str]       ,  _lowerCamelCase  : Tuple=None							):






									'''simple docstring'''



									__lowerCamelCase     :      Dict       						=						self.linear(self.silu(self.emb(_lowerCamelCase       ,  _lowerCamelCase       ,  hidden_dtype=_lowerCamelCase							)							)							)
									__lowerCamelCase     :      List[Any]       						=						emb.chunk(6       ,  dim=1							)
									__lowerCamelCase     :      Optional[int]       						=						self.norm(_lowerCamelCase							) * (1 + scale_msa[:, None]) + shift_msa[:, None]
									return x, gate_msa, shift_mlp, scale_mlp, gate_mlp



class 							_UpperCamelCase (						nn.Module						):

			'''simple docstring'''







			def __init__(  self  : Dict       ,  _lowerCamelCase  : int       ,  _lowerCamelCase  : int       ,  _lowerCamelCase  : int       ,  _lowerCamelCase  : Optional[str] = None       ,  _lowerCamelCase  : float = 1E-5							):






									'''simple docstring'''



									super().__init__()
									__lowerCamelCase     :      Tuple       						=						num_groups
									__lowerCamelCase     :      Tuple       						=						eps

									if act_fn is None:
															__lowerCamelCase     :      Any       						=						None
									else:
															__lowerCamelCase     :      Union[str, Any]       						=						get_activation(_lowerCamelCase							)

									__lowerCamelCase     :      Union[str, Any]       						=						nn.Linear(_lowerCamelCase       ,  out_dim * 2							)


			def   _snake_case    (  self  : List[str]       ,  _lowerCamelCase  : Tuple       ,  _lowerCamelCase  : Optional[Any]							):






									'''simple docstring'''



									if self.act:
															__lowerCamelCase     :      Any       						=						self.act(_lowerCamelCase							)
									__lowerCamelCase     :      Tuple       						=						self.linear(_lowerCamelCase							)
									__lowerCamelCase     :      int       						=						emb[:, :, None, None]
									__lowerCamelCase     :      List[str]       						=						emb.chunk(2       ,  dim=1							)

									__lowerCamelCase     :      Optional[Any]       						=						F.group_norm(_lowerCamelCase       ,  self.num_groups       ,  eps=self.eps							)
									__lowerCamelCase     :      Dict       						=						x * (1 + scale) + shift
									return x







import argparse
import hashlib
import os
import urllib
import warnings

import torch
from torch import nn
from tqdm import tqdm

from transformers import WhisperConfig, WhisperForConditionalGeneration


__UpperCamelCase    :						Tuple     =							{
    'tiny.en': 'https://openaipublic.azureedge.net/main/whisper/models/d3dd57d32accea0b295c96e26691aa14d8822fac7d9d27d5dc00b4ca2826dd03/tiny.en.pt',
    'tiny': 'https://openaipublic.azureedge.net/main/whisper/models/65147644a518d12f04e32d6f3b26facc3f8dd46e5390956a9424a650c0ce22b9/tiny.pt',
    'base.en': 'https://openaipublic.azureedge.net/main/whisper/models/25a8566e1d0c1e2231d1c762132cd20e0f96a85d16145c3a00adf5d1ac670ead/base.en.pt',
    'base': 'https://openaipublic.azureedge.net/main/whisper/models/ed3a0b6b1c0edf879ad9b11b1af5a0e6ab5db9205f891f668f8b0e6c6326e34e/base.pt',
    'small.en': 'https://openaipublic.azureedge.net/main/whisper/models/f953ad0fd29cacd07d5a9eda5624af0f6bcf2258be67c92b79389873d91e0872/small.en.pt',
    'small': 'https://openaipublic.azureedge.net/main/whisper/models/9ecf779972d90ba49c06d968637d720dd632c55bbf19d441fb42bf17a411e794/small.pt',
    'medium.en': 'https://openaipublic.azureedge.net/main/whisper/models/d7440d1dc186f76616474e0ff0b3b6b879abc9d1a4926b7adfa41db2d497ab4f/medium.en.pt',
    'medium': 'https://openaipublic.azureedge.net/main/whisper/models/345ae4da62f9b3d59415adc60127b97c714f32e89e936602e85993674d08dcb1/medium.pt',
    'large': 'https://openaipublic.azureedge.net/main/whisper/models/e4b87e7e0bf463eb8e6956e646f1e277e901512310def2c24bf0e11bd3c28e9a/large.pt',
    'large-v2': 'https://openaipublic.azureedge.net/main/whisper/models/81f7c96c852ee8fc832187b0132e569d6c3065a3252ed18e56effd0b6a73e524/large-v2.pt',
}





def   _UpperCAmelCase       (     UpperCAmelCase      :			Dict      ):
      """simple docstring"""




      __lowerCamelCase     :      int       						=						["""layers""", """blocks"""]
      for k in ignore_keys:
            state_dict.pop(UpperCAmelCase						,	UpperCAmelCase      )


__UpperCamelCase    :						str     =							{
    'blocks': 'layers',
    'mlp.0': 'fc1',
    'mlp.2': 'fc2',
    'mlp_ln': 'final_layer_norm',
    '.attn.query': '.self_attn.q_proj',
    '.attn.key': '.self_attn.k_proj',
    '.attn.value': '.self_attn.v_proj',
    '.attn_ln': '.self_attn_layer_norm',
    '.attn.out': '.self_attn.out_proj',
    '.cross_attn.query': '.encoder_attn.q_proj',
    '.cross_attn.key': '.encoder_attn.k_proj',
    '.cross_attn.value': '.encoder_attn.v_proj',
    '.cross_attn_ln': '.encoder_attn_layer_norm',
    '.cross_attn.out': '.encoder_attn.out_proj',
    'decoder.ln.': 'decoder.layer_norm.',
    'encoder.ln.': 'encoder.layer_norm.',
    'token_embedding': 'embed_tokens',
    'encoder.positional_embedding': 'encoder.embed_positions.weight',
    'decoder.positional_embedding': 'decoder.embed_positions.weight',
    'ln_post': 'layer_norm',
}





def   _UpperCAmelCase       (     UpperCAmelCase      :			Dict      ):
      """simple docstring"""




      __lowerCamelCase     :      List[str]       						=						list(s_dict.keys()      )
      for key in keys:
            __lowerCamelCase     :      Union[str, Any]       						=						key
            for k, v in WHISPER_MAPPING.items():
                  if k in key:
                        __lowerCamelCase     :      Optional[int]       						=						new_key.replace(UpperCAmelCase						,	UpperCAmelCase      )

            print(f"""{key} -> {new_key}"""      )

            __lowerCamelCase     :      Dict       						=						s_dict.pop(UpperCAmelCase      )
      return s_dict





def   _UpperCAmelCase       (     UpperCAmelCase      :			Optional[int]      ):
      """simple docstring"""




      __lowerCamelCase						, __lowerCamelCase     :      Dict       						=						emb.weight.shape
      __lowerCamelCase     :      Tuple       						=						nn.Linear(UpperCAmelCase						,	UpperCAmelCase						,	bias=UpperCAmelCase      )
      __lowerCamelCase     :      Union[str, Any]       						=						emb.weight.data
      return lin_layer





def   _UpperCAmelCase       (     UpperCAmelCase      :			str						,	UpperCAmelCase      :			str      ):
      """simple docstring"""




      os.makedirs(UpperCAmelCase						,	exist_ok=UpperCAmelCase      )
      __lowerCamelCase     :      Any       						=						os.path.basename(UpperCAmelCase      )

      __lowerCamelCase     :      int       						=						url.split("""/"""      )[-2]
      __lowerCamelCase     :      str       						=						os.path.join(UpperCAmelCase						,	UpperCAmelCase      )

      if os.path.exists(UpperCAmelCase      ) and not os.path.isfile(UpperCAmelCase      ):
            raise RuntimeError(f"""{download_target} exists and is not a regular file"""      )

      if os.path.isfile(UpperCAmelCase      ):
            __lowerCamelCase     :      Any       						=						open(UpperCAmelCase						,	"""rb"""      ).read()
            if hashlib.shaaaa(UpperCAmelCase      ).hexdigest() == expected_shaaaa:
                  return model_bytes
            else:
                  warnings.warn(f"""{download_target} exists, but the SHA256 checksum does not match; re-downloading the file"""      )

      with urllib.request.urlopen(UpperCAmelCase      ) as source, open(UpperCAmelCase						,	"""wb"""      ) as output:
            with tqdm(
                total=int(source.info().get("""Content-Length"""      )      )						,	ncols=80						,	unit="""iB"""						,	unit_scale=UpperCAmelCase						,	unit_divisor=1_024      ) as loop:
                  while True:
                        __lowerCamelCase     :      Union[str, Any]       						=						source.read(8_192      )
                        if not buffer:
                              break

                        output.write(UpperCAmelCase      )
                        loop.update(len(UpperCAmelCase      )      )

      __lowerCamelCase     :      List[str]       						=						open(UpperCAmelCase						,	"""rb"""      ).read()
      if hashlib.shaaaa(UpperCAmelCase      ).hexdigest() != expected_shaaaa:
            raise RuntimeError(
                """Model has been downloaded but the SHA256 checksum does not not match. Please retry loading the model."""      )

      return model_bytes





def   _UpperCAmelCase       (     UpperCAmelCase      :			List[Any]						,	UpperCAmelCase      :			Optional[int]      ):
      """simple docstring"""




      if ".pt" not in checkpoint_path:
            __lowerCamelCase     :      Optional[int]       						=						_download(_MODELS[checkpoint_path]      )
      else:
            __lowerCamelCase     :      Union[str, Any]       						=						torch.load(UpperCAmelCase						,	map_location="""cpu"""      )
      __lowerCamelCase     :      Any       						=						original_checkpoint["""dims"""]
      __lowerCamelCase     :      int       						=						original_checkpoint["""model_state_dict"""]
      __lowerCamelCase     :      Tuple       						=						state_dict["""decoder.token_embedding.weight"""]
      remove_ignore_keys_(UpperCAmelCase      )
      rename_keys(UpperCAmelCase      )
      __lowerCamelCase     :      int       						=						True
      __lowerCamelCase     :      Tuple       						=						state_dict["""decoder.layers.0.fc1.weight"""].shape[0]

      __lowerCamelCase     :      Any       						=						WhisperConfig(
          vocab_size=dimensions["""n_vocab"""]						,	encoder_ffn_dim=UpperCAmelCase						,	decoder_ffn_dim=UpperCAmelCase						,	num_mel_bins=dimensions["""n_mels"""]						,	d_model=dimensions["""n_audio_state"""]						,	max_target_positions=dimensions["""n_text_ctx"""]						,	encoder_layers=dimensions["""n_audio_layer"""]						,	encoder_attention_heads=dimensions["""n_audio_head"""]						,	decoder_layers=dimensions["""n_text_layer"""]						,	decoder_attention_heads=dimensions["""n_text_state"""]						,	max_source_positions=dimensions["""n_audio_ctx"""]						,	)

      __lowerCamelCase     :      List[str]       						=						WhisperForConditionalGeneration(UpperCAmelCase      )
      __lowerCamelCase						, __lowerCamelCase     :      str       						=						model.model.load_state_dict(UpperCAmelCase						,	strict=UpperCAmelCase      )
      if len(UpperCAmelCase      ) > 0 and not set(UpperCAmelCase      ) <= {
          "encoder.embed_positions.weights",
          "decoder.embed_positions.weights",
      }:
            raise ValueError(
                """Only `encoder.embed_positions.weights` and `decoder.embed_positions.weights`  are allowed to be missing,"""
                f""" but all the following weights are missing {missing}"""      )

      if tie_embeds:
            __lowerCamelCase     :      Tuple       						=						make_linear_from_emb(model.model.decoder.embed_tokens      )
      else:
            __lowerCamelCase     :      Tuple       						=						proj_out_weights

      model.save_pretrained(UpperCAmelCase      )


if __name__ == "__main__":
    __UpperCamelCase    :						Union[str, Any]     =							argparse.ArgumentParser()
    # # Required parameters
    parser.add_argument('--checkpoint_path', type=str, help='Patht to the downloaded checkpoints')
    parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.')
    __UpperCamelCase    :						Tuple     =							parser.parse_args()

    convert_openai_whisper_to_tfms(args.checkpoint_path, args.pytorch_dump_folder_path)



