
"""simple docstring"""

import logging

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,
    BertEncoder,
    BertModel,
    BertPreTrainedModel,
)


_A						=			logging.getLogger(__name__)






class 	_lowercase       (    __UpperCAmelCase		):




	def       _UpperCamelCase   (			self		,			UpperCAmelCase_		,			UpperCAmelCase_		,			UpperCAmelCase_=None		,			UpperCAmelCase_=None )		->							Optional[int]:
			lowerCamelCase					:      Any          =   self.layer[current_layer](UpperCAmelCase_		,			UpperCAmelCase_		,			head_mask[current_layer] )

			lowerCamelCase					:      int          =   layer_outputs[0]

			return hidden_states






@add_start_docstrings(
    'The bare Bert Model transformer with PABEE outputting raw hidden-states without any specific head on top.'    ,	__UpperCAmelCase    ,	)
class 	_lowercase       (    __UpperCAmelCase		):




	def __init__(			self		,			UpperCAmelCase_ )		->							List[Any]:
			super().__init__(UpperCAmelCase_ )

			lowerCamelCase					:      Tuple          =   BertEncoderWithPabee(UpperCAmelCase_ )

			self.init_weights()
			lowerCamelCase					:      List[Any]          =   0
			lowerCamelCase					:      Dict          =   0
			lowerCamelCase					:      Any          =   0

			lowerCamelCase					:      List[str]          =   0




	def       _UpperCamelCase   (			self		,			UpperCAmelCase_ )		->							Tuple:
			lowerCamelCase					:      List[Any]          =   threshold




	def       _UpperCamelCase   (			self		,			UpperCAmelCase_ )		->							List[str]:
			lowerCamelCase					:      Optional[Any]          =   patience




	def       _UpperCamelCase   (			self )		->							Any:
			lowerCamelCase					:      str          =   0
			lowerCamelCase					:      List[str]          =   0




	def       _UpperCamelCase   (			self )		->							List[str]:
			lowerCamelCase					:      Tuple          =   self.inference_layers_num / self.inference_instances_num
			lowerCamelCase					:      str          =   (
			    F"""*** Patience = {self.patience} Avg. Inference Layers = {avg_inf_layers:.2f} Speed Up ="""
			    F""" {1 - avg_inf_layers / self.config.num_hidden_layers:.2f} ***"""
			)
			print(UpperCAmelCase_ )




	@add_start_docstrings_to_model_forward(UpperCAmelCase_ )
	def       _UpperCamelCase   (			self		,			UpperCAmelCase_=None		,			UpperCAmelCase_=None		,			UpperCAmelCase_=None		,			UpperCAmelCase_=None		,			UpperCAmelCase_=None		,			UpperCAmelCase_=None		,			UpperCAmelCase_=None		,			UpperCAmelCase_=None		,			UpperCAmelCase_=None		,			UpperCAmelCase_=None		,			UpperCAmelCase_=False		,			)		->							Tuple:

			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:
					lowerCamelCase					:      Union[str, Any]          =   input_ids.size()
			elif inputs_embeds is not None:
					lowerCamelCase					:      Optional[Any]          =   inputs_embeds.size()[:-1]
			else:
					raise ValueError('You have to specify either input_ids or inputs_embeds' )

			lowerCamelCase					:      Dict          =   input_ids.device if input_ids is not None else inputs_embeds.device

			if attention_mask is None:
					lowerCamelCase					:      Any          =   torch.ones(UpperCAmelCase_		,			device=UpperCAmelCase_ )
			if token_type_ids is None:
					lowerCamelCase					:      Union[str, Any]          =   torch.zeros(UpperCAmelCase_		,			dtype=torch.long		,			device=UpperCAmelCase_ )

			# 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.
			lowerCamelCase					:      torch.Tensor          =   self.get_extended_attention_mask(UpperCAmelCase_		,			UpperCAmelCase_		,			UpperCAmelCase_ )

			# 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 self.config.is_decoder and encoder_hidden_states is not None:
					lowerCamelCase     ,   lowerCamelCase     ,   lowerCamelCase					:      Union[str, Any]          =   encoder_hidden_states.size()
					lowerCamelCase					:      int          =   (encoder_batch_size, encoder_sequence_length)
					if encoder_attention_mask is None:
							lowerCamelCase					:      str          =   torch.ones(UpperCAmelCase_		,			device=UpperCAmelCase_ )
					lowerCamelCase					:      Union[str, Any]          =   self.invert_attention_mask(UpperCAmelCase_ )
			else:
					lowerCamelCase					:      Optional[Any]          =   None

			# 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]
			lowerCamelCase					:      Tuple          =   self.get_head_mask(UpperCAmelCase_		,			self.config.num_hidden_layers )

			lowerCamelCase					:      Tuple          =   self.embeddings(
			    input_ids=UpperCAmelCase_		,			position_ids=UpperCAmelCase_		,			token_type_ids=UpperCAmelCase_		,			inputs_embeds=UpperCAmelCase_ )
			lowerCamelCase					:      Optional[int]          =   embedding_output

			if self.training:
					lowerCamelCase					:      Tuple          =   []
					for i in range(self.config.num_hidden_layers ):
							lowerCamelCase					:      Dict          =   self.encoder.adaptive_forward(
							    UpperCAmelCase_		,			current_layer=UpperCAmelCase_		,			attention_mask=UpperCAmelCase_		,			head_mask=UpperCAmelCase_ )

							lowerCamelCase					:      List[str]          =   self.pooler(UpperCAmelCase_ )
							lowerCamelCase					:      int          =   output_layers[i](output_dropout(UpperCAmelCase_ ) )
							res.append(UpperCAmelCase_ )
			elif self.patience == 0:  # Use all layers for inference
					lowerCamelCase					:      Optional[Any]          =   self.encoder(
					    UpperCAmelCase_		,			attention_mask=UpperCAmelCase_		,			head_mask=UpperCAmelCase_		,			encoder_hidden_states=UpperCAmelCase_		,			encoder_attention_mask=UpperCAmelCase_		,			)
					lowerCamelCase					:      Any          =   self.pooler(encoder_outputs[0] )
					lowerCamelCase					:      str          =   [output_layers[self.config.num_hidden_layers - 1](UpperCAmelCase_ )]
			else:
					lowerCamelCase					:      Union[str, Any]          =   0
					lowerCamelCase					:      Union[str, Any]          =   None
					lowerCamelCase					:      Any          =   0
					for i in range(self.config.num_hidden_layers ):
							calculated_layer_num += 1
							lowerCamelCase					:      int          =   self.encoder.adaptive_forward(
							    UpperCAmelCase_		,			current_layer=UpperCAmelCase_		,			attention_mask=UpperCAmelCase_		,			head_mask=UpperCAmelCase_ )

							lowerCamelCase					:      Optional[Any]          =   self.pooler(UpperCAmelCase_ )
							lowerCamelCase					:      Tuple          =   output_layers[i](UpperCAmelCase_ )
							if regression:
									lowerCamelCase					:      List[Any]          =   logits.detach()
									if patient_result is not None:
											lowerCamelCase					:      str          =   patient_result.detach()
									if (patient_result is not None) and torch.abs(patient_result - labels ) < self.regression_threshold:
											patient_counter += 1
									else:
											lowerCamelCase					:      Tuple          =   0
							else:
									lowerCamelCase					:      str          =   logits.detach().argmax(dim=1 )
									if patient_result is not None:
											lowerCamelCase					:      List[Any]          =   patient_result.detach().argmax(dim=1 )
									if (patient_result is not None) and torch.all(labels.eq(UpperCAmelCase_ ) ):
											patient_counter += 1
									else:
											lowerCamelCase					:      Dict          =   0

							lowerCamelCase					:      Optional[int]          =   logits
							if patient_counter == self.patience:
									break
					lowerCamelCase					:      List[str]          =   [patient_result]
					self.inference_layers_num += calculated_layer_num
					self.inference_instances_num += 1

			return res






@add_start_docstrings(
    'Bert Model transformer with PABEE and a sequence classification/regression head on top (a linear layer on top of\n    the pooled output) e.g. for GLUE tasks. '    ,	__UpperCAmelCase    ,	)
class 	_lowercase       (    __UpperCAmelCase		):




	def __init__(			self		,			UpperCAmelCase_ )		->							Any:
			super().__init__(UpperCAmelCase_ )
			lowerCamelCase					:      Dict          =   config.num_labels

			lowerCamelCase					:      Optional[Any]          =   BertModelWithPabee(UpperCAmelCase_ )
			lowerCamelCase					:      Any          =   nn.Dropout(config.hidden_dropout_prob )
			lowerCamelCase					:      Dict          =   nn.ModuleList(
			    [nn.Linear(config.hidden_size		,			self.config.num_labels ) for _ in range(config.num_hidden_layers )] )

			self.init_weights()




	@add_start_docstrings_to_model_forward(UpperCAmelCase_ )
	def       _UpperCamelCase   (			self		,			UpperCAmelCase_=None		,			UpperCAmelCase_=None		,			UpperCAmelCase_=None		,			UpperCAmelCase_=None		,			UpperCAmelCase_=None		,			UpperCAmelCase_=None		,			UpperCAmelCase_=None		,			)		->							Any:
			lowerCamelCase					:      int          =   self.bert(
			    input_ids=UpperCAmelCase_		,			attention_mask=UpperCAmelCase_		,			token_type_ids=UpperCAmelCase_		,			position_ids=UpperCAmelCase_		,			head_mask=UpperCAmelCase_		,			inputs_embeds=UpperCAmelCase_		,			output_dropout=self.dropout		,			output_layers=self.classifiers		,			regression=self.num_labels == 1		,			)

			lowerCamelCase					:      Any          =   (logits[-1],)

			if labels is not None:
					lowerCamelCase					:      str          =   None
					lowerCamelCase					:      Optional[Any]          =   0
					for ix, logits_item in enumerate(UpperCAmelCase_ ):
							if self.num_labels == 1:
									#  We are doing regression
									lowerCamelCase					:      str          =   MSELoss()
									lowerCamelCase					:      Optional[int]          =   loss_fct(logits_item.view(-1 )		,			labels.view(-1 ) )
							else:
									lowerCamelCase					:      Union[str, Any]          =   CrossEntropyLoss()
									lowerCamelCase					:      Any          =   loss_fct(logits_item.view(-1		,			self.num_labels )		,			labels.view(-1 ) )
							if total_loss is None:
									lowerCamelCase					:      Optional[Any]          =   loss
							else:
									total_loss += loss * (ix + 1)
							total_weights += ix + 1
					lowerCamelCase					:      List[Any]          =   (total_loss / total_weights,) + outputs

			return outputs








"""simple docstring"""

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


_A						=			{
    '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 (		a_      ):





		'''simple docstring'''


		lowerCamelCase					:      str          =   ['layers', 'blocks']
		for k in ignore_keys:
				state_dict.pop(a_,						a_      )


_A						=			{
    '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 (		a_      ):





		'''simple docstring'''


		lowerCamelCase					:      Tuple          =   list(s_dict.keys()      )
		for key in keys:
				lowerCamelCase					:      List[Any]          =   key
				for k, v in WHISPER_MAPPING.items():
						if k in key:
								lowerCamelCase					:      Optional[int]          =   new_key.replace(a_,						a_      )

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

				lowerCamelCase					:      Any          =   s_dict.pop(a_      )
		return s_dict
def 		UpperCAmelCase (		a_      ):





		'''simple docstring'''


		lowerCamelCase     ,   lowerCamelCase					:      int          =   emb.weight.shape
		lowerCamelCase					:      Dict          =   nn.Linear(a_,						a_,						bias=a_      )
		lowerCamelCase					:      Union[str, Any]          =   emb.weight.data
		return lin_layer
def 		UpperCAmelCase (		a_,						a_      ):





		'''simple docstring'''


		os.makedirs(a_,						exist_ok=a_      )
		lowerCamelCase					:      Union[str, Any]          =   os.path.basename(a_      )

		lowerCamelCase					:      Any          =   url.split('/'      )[-2]
		lowerCamelCase					:      Tuple          =   os.path.join(a_,						a_      )

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

		if os.path.isfile(a_      ):
				lowerCamelCase					:      Union[str, Any]          =   open(a_,						'rb'      ).read()
				if hashlib.shaaaa(a_      ).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(a_      ) as source, open(a_,						'wb'      ) as output:
				with tqdm(
				    total=int(source.info().get('Content-Length'      )      ),						ncols=80,						unit='iB',						unit_scale=a_,						unit_divisor=1024      ) as loop:
						while True:
								lowerCamelCase					:      Union[str, Any]          =   source.read(8192      )
								if not buffer:
										break

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

		lowerCamelCase					:      int          =   open(a_,						'rb'      ).read()
		if hashlib.shaaaa(a_      ).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 (		a_,						a_      ):





		'''simple docstring'''


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

		lowerCamelCase					:      Optional[int]          =   WhisperConfig(
		    vocab_size=dimensions['n_vocab'],						encoder_ffn_dim=a_,						decoder_ffn_dim=a_,						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					:      Union[str, Any]          =   WhisperForConditionalGeneration(a_      )
		lowerCamelCase     ,   lowerCamelCase					:      Optional[int]          =   model.model.load_state_dict(a_,						strict=a_      )
		if len(a_      ) > 0 and not set(a_      ) <= {
		    "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					:      List[Any]          =   make_linear_from_emb(model.model.decoder.embed_tokens      )
		else:
				lowerCamelCase					:      Tuple          =   proj_out_weights

		model.save_pretrained(a_      )


if __name__ == "__main__":
					_A						=			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.')
					_A						=			parser.parse_args()

					convert_openai_whisper_to_tfms(args.checkpoint_path, args.pytorch_dump_folder_path)






