






import argparse
import collections

import numpy as np
import torch
from flax import traverse_util
from tax import checkpoints

from transformers import MTaConfig, UMTaEncoderModel, UMTaForConditionalGeneration
from transformers.utils import logging


logging.set_verbosity_info()

def      __lowercase					( snake_case,  snake_case,  snake_case ):







				"""simple docstring"""






				return params[f'''{prefix}/{prefix}/relpos_bias/rel_embedding'''][:, i, :]

def      __lowercase					( snake_case,  snake_case,  snake_case,  snake_case="attention" ):







				"""simple docstring"""






				__magic_name__		:List[str]        =      np.ascontiguousarray(params[f'''{prefix}/{prefix}/{layer_name}/key/kernel'''][:, i, :, :] )
				__magic_name__		:Optional[Any]        =      k_tmp.reshape(k_tmp.shape[0],  k_tmp.shape[1] * k_tmp.shape[2] )
				__magic_name__		:int        =      np.ascontiguousarray(params[f'''{prefix}/{prefix}/{layer_name}/out/kernel'''][:, i, :, :] )
				__magic_name__		:List[Any]        =      o_tmp.reshape(o_tmp.shape[0] * o_tmp.shape[1],  o_tmp.shape[2] )
				__magic_name__		:Tuple        =      np.ascontiguousarray(params[f'''{prefix}/{prefix}/{layer_name}/query/kernel'''][:, i, :, :] )
				__magic_name__		:Dict        =      q_tmp.reshape(q_tmp.shape[0],  q_tmp.shape[1] * q_tmp.shape[2] )
				__magic_name__		:Dict        =      np.ascontiguousarray(params[f'''{prefix}/{prefix}/{layer_name}/value/kernel'''][:, i, :, :] )
				__magic_name__		:Dict        =      v_tmp.reshape(v_tmp.shape[0],  v_tmp.shape[1] * v_tmp.shape[2] )
				return k, o, q, v

def      __lowercase					( snake_case,  snake_case,  snake_case,  snake_case=False ):







				"""simple docstring"""






				if split_mlp_wi:
								__magic_name__		:int        =      params[f'''{prefix}/{prefix}/mlp/wi_0/kernel'''][:, i, :]
								__magic_name__		:List[str]        =      params[f'''{prefix}/{prefix}/mlp/wi_1/kernel'''][:, i, :]
								__magic_name__		:str        =      (wi_a, wi_a)
				else:
								__magic_name__		:Dict        =      params[f'''{prefix}/{prefix}/mlp/wi/kernel'''][:, i, :]

				__magic_name__		:Any        =      params[f'''{prefix}/{prefix}/mlp/wo/kernel'''][:, i, :]
				return wi, wo

def      __lowercase					( snake_case,  snake_case,  snake_case,  snake_case ):







				"""simple docstring"""






				return params[f'''{prefix}/{prefix}/{layer_name}/scale'''][:, i]

def      __lowercase					( snake_case,  *, snake_case,  snake_case,  snake_case = False ):







				"""simple docstring"""






				__magic_name__		:List[Any]        =      traverse_util.flatten_dict(variables['''target'''] )
				__magic_name__		:Dict        =      {'''/'''.join(snake_case ): v for k, v in old.items()}

				# v1.1 models have a gated GeLU with wi_0 and wi_1 instead of wi
				__magic_name__		:Tuple        =      '''encoder/encoder/mlp/wi_0/kernel''' in old
				print('''Split MLP:''',  snake_case )

				__magic_name__		:Any        =      collections.OrderedDict()

				# Shared embeddings.
				__magic_name__		:Dict        =      old['''token_embedder/embedding''']

				# Encoder.
				for i in range(snake_case ):
								# Block i, layer 0 (Self Attention).
								__magic_name__		:List[Any]        =      tax_layer_norm_lookup(snake_case,  snake_case,  '''encoder''',  '''pre_attention_layer_norm''' )
								__magic_name__     ,				__magic_name__     ,				__magic_name__     ,				__magic_name__		:Any        =      tax_attention_lookup(snake_case,  snake_case,  '''encoder''',  '''attention''' )
								__magic_name__		:Dict        =      layer_norm
								__magic_name__		:int        =      k.T
								__magic_name__		:Union[str, Any]        =      o.T
								__magic_name__		:int        =      q.T
								__magic_name__		:int        =      v.T

								# Block i, layer 1 (MLP).
								__magic_name__		:List[Any]        =      tax_layer_norm_lookup(snake_case,  snake_case,  '''encoder''',  '''pre_mlp_layer_norm''' )
								__magic_name__     ,				__magic_name__		:Tuple        =      tax_mlp_lookup(snake_case,  snake_case,  '''encoder''',  snake_case )
								__magic_name__		:List[str]        =      layer_norm
								if split_mlp_wi:
												__magic_name__		:Tuple        =      wi[0].T
												__magic_name__		:Optional[Any]        =      wi[1].T
								else:
												__magic_name__		:Union[str, Any]        =      wi.T
								__magic_name__		:Union[str, Any]        =      wo.T
								if scalable_attention:
												# convert the rel_embedding of each layer
												__magic_name__		:str        =      tax_relpos_bias_lookup(
												    snake_case,  snake_case,  '''encoder''' ).T

				__magic_name__		:List[Any]        =      old['''encoder/encoder_norm/scale''']

				if not scalable_attention:
								__magic_name__		:Optional[int]        =      tax_relpos_bias_lookup(
								    snake_case,  0,  '''encoder''' ).T
								__magic_name__		:Tuple        =      tax_relpos_bias_lookup(
								    snake_case,  0,  '''decoder''' ).T

				if not is_encoder_only:
								# Decoder.
								for i in range(snake_case ):
												# Block i, layer 0 (Self Attention).
												__magic_name__		:List[Any]        =      tax_layer_norm_lookup(snake_case,  snake_case,  '''decoder''',  '''pre_self_attention_layer_norm''' )
												__magic_name__     ,				__magic_name__     ,				__magic_name__     ,				__magic_name__		:str        =      tax_attention_lookup(snake_case,  snake_case,  '''decoder''',  '''self_attention''' )
												__magic_name__		:int        =      layer_norm
												__magic_name__		:Any        =      k.T
												__magic_name__		:Dict        =      o.T
												__magic_name__		:Optional[int]        =      q.T
												__magic_name__		:List[str]        =      v.T

												# Block i, layer 1 (Cross Attention).
												__magic_name__		:Tuple        =      tax_layer_norm_lookup(snake_case,  snake_case,  '''decoder''',  '''pre_cross_attention_layer_norm''' )
												__magic_name__     ,				__magic_name__     ,				__magic_name__     ,				__magic_name__		:List[str]        =      tax_attention_lookup(snake_case,  snake_case,  '''decoder''',  '''encoder_decoder_attention''' )
												__magic_name__		:Optional[Any]        =      layer_norm
												__magic_name__		:Union[str, Any]        =      k.T
												__magic_name__		:str        =      o.T
												__magic_name__		:Union[str, Any]        =      q.T
												__magic_name__		:List[Any]        =      v.T

												# Block i, layer 2 (MLP).
												__magic_name__		:Union[str, Any]        =      tax_layer_norm_lookup(snake_case,  snake_case,  '''decoder''',  '''pre_mlp_layer_norm''' )
												__magic_name__     ,				__magic_name__		:Dict        =      tax_mlp_lookup(snake_case,  snake_case,  '''decoder''',  snake_case )
												__magic_name__		:Any        =      layer_norm
												if split_mlp_wi:
																__magic_name__		:Optional[Any]        =      wi[0].T
																__magic_name__		:List[Any]        =      wi[1].T
												else:
																__magic_name__		:Optional[Any]        =      wi.T
												__magic_name__		:Any        =      wo.T

												if scalable_attention:
																# convert the rel_embedding of each layer
																__magic_name__		:Any        =      tax_relpos_bias_lookup(snake_case,  snake_case,  '''decoder''' ).T

								__magic_name__		:str        =      old['''decoder/decoder_norm/scale''']

								# LM Head (only in v1.1 checkpoints, in v1.0 embeddings are used instead)
								if "decoder/logits_dense/kernel" in old:
												__magic_name__		:Optional[int]        =      old['''decoder/logits_dense/kernel'''].T

				return new

def      __lowercase					( snake_case,  snake_case ):







				"""simple docstring"""






				__magic_name__		:Union[str, Any]        =      collections.OrderedDict([(k, torch.from_numpy(v.copy() )) for (k, v) in converted_params.items()] )

				# Add what is missing.
				if "encoder.embed_tokens.weight" not in state_dict:
								__magic_name__		:Optional[int]        =      state_dict['''shared.weight''']

				if not is_encoder_only:
								if "decoder.embed_tokens.weight" not in state_dict:
												__magic_name__		:int        =      state_dict['''shared.weight''']

								if "lm_head.weight" not in state_dict:  # For old 1.0 models.
												print('''Using shared word embeddings as lm_head.''' )
												__magic_name__		:int        =      state_dict['''shared.weight''']

				return state_dict

def      __lowercase					( snake_case,  snake_case,  snake_case,  snake_case,  snake_case ):







				"""simple docstring"""






				__magic_name__		:Optional[int]        =      checkpoints.load_tax_checkpoint(snake_case )
				__magic_name__		:Optional[Any]        =      convert_tax_to_pytorch(
				    snake_case,  num_layers=config.num_layers,  is_encoder_only=snake_case,  scalable_attention=snake_case )
				__magic_name__		:List[str]        =      make_state_dict(snake_case,  snake_case )
				model.load_state_dict(snake_case,  strict=snake_case )

def      __lowercase					( snake_case,  snake_case,  snake_case,  snake_case = False,  snake_case = False,  ):







				"""simple docstring"""






				__magic_name__		:Optional[int]        =      MTaConfig.from_json_file(snake_case )
				print(f'''Building PyTorch model from configuration: {config}''' )
				# Non-v1.1 checkpoints could also use T5Model, but this works for all.
				# The v1.0 checkpoints will simply have an LM head that is the word embeddings.
				if is_encoder_only:
								__magic_name__		:Tuple        =      UMTaEncoderModel(snake_case )
				else:
								__magic_name__		:Any        =      UMTaForConditionalGeneration(snake_case )

				# Load weights from tf checkpoint
				load_tax_weights_in_ta(snake_case,  snake_case,  snake_case,  snake_case,  snake_case )

				# Save pytorch-model
				print(f'''Save PyTorch model to {pytorch_dump_path}''' )
				model.save_pretrained(snake_case )

				# Verify that we can load the checkpoint.
				model.from_pretrained(snake_case )
				print('''Done''' )


if __name__ == "__main__":
					SCREAMING_SNAKE_CASE__      :			int							=		argparse.ArgumentParser(description="""Converts a native T5X checkpoint into a PyTorch checkpoint.""")
					# Required parameters
					parser.add_argument(
					    """--t5x_checkpoint_path""", default=None, type=str, required=True, help="""Path to the T5X checkpoint."""
					)
					parser.add_argument(
					    """--config_file""",
					    default=None,
					    type=str,
					    required=True,
					    help="""The config json file corresponding to the pre-trained T5 model.\nThis specifies the model architecture.""",
					)
					parser.add_argument(
					    """--pytorch_dump_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model."""
					)
					parser.add_argument(
					    """--is_encoder_only""", action="""store_true""", help="""Check if the model is encoder-decoder model""", default=False
					)
					parser.add_argument(
					    """--scalable_attention""",
					    action="""store_true""",
					    help="""Whether the model uses scaled attention (umt5 model)""",
					    default=False,
					)
					SCREAMING_SNAKE_CASE__      :			Any							=		parser.parse_args()
					convert_tax_checkpoint_to_pytorch(
					    args.tax_checkpoint_path,
					    args.config_file,
					    args.pytorch_dump_path,
					    args.is_encoder_only,
					    args.scalable_attention,
					)














from ...processing_utils import ProcessorMixin
class 						lowerCamelCase_				(      lowerCamelCase ):
				a__					       =  '''WhisperFeatureExtractor'''
				a__					       =  '''WhisperTokenizer'''







				def __init__(						self       ,					__lowerCAmelCase       ,					__lowerCAmelCase     ):
								"""simple docstring"""
								super().__init__(__lowerCAmelCase       ,					__lowerCAmelCase     )
								__magic_name__		:int        =      self.feature_extractor
								__magic_name__		:int        =      False







				def 			A	(						self       ,					__lowerCAmelCase=None       ,					__lowerCAmelCase=None       ,					__lowerCAmelCase=True     ):
								"""simple docstring"""
								return self.tokenizer.get_decoder_prompt_ids(task=__lowerCAmelCase       ,					language=__lowerCAmelCase       ,					no_timestamps=__lowerCAmelCase     )







				def __call__(						self       ,					*__lowerCAmelCase       ,					**__lowerCAmelCase     ):
								"""simple docstring"""
								# For backward compatibility
								if self._in_target_context_manager:
												return self.current_processor(*__lowerCAmelCase       ,					**__lowerCAmelCase     )

								__magic_name__		:List[Any]        =      kwargs.pop('''audio'''       ,					__lowerCAmelCase     )
								__magic_name__		:Any        =      kwargs.pop('''sampling_rate'''       ,					__lowerCAmelCase     )
								__magic_name__		:str        =      kwargs.pop('''text'''       ,					__lowerCAmelCase     )
								if len(__lowerCAmelCase     ) > 0:
												__magic_name__		:Any        =      args[0]
												__magic_name__		:Union[str, Any]        =      args[1:]

								if audio is None and text is None:
												raise ValueError('''You need to specify either an `audio` or `text` input to process.'''     )

								if audio is not None:
												__magic_name__		:Optional[int]        =      self.feature_extractor(__lowerCAmelCase       ,					*__lowerCAmelCase       ,					sampling_rate=__lowerCAmelCase       ,					**__lowerCAmelCase     )
								if text is not None:
												__magic_name__		:Optional[int]        =      self.tokenizer(__lowerCAmelCase       ,					**__lowerCAmelCase     )

								if text is None:
												return inputs

								elif audio is None:
												return encodings
								else:
												__magic_name__		:str        =      encodings['''input_ids''']
												return inputs







				def 			A	(						self       ,					*__lowerCAmelCase       ,					**__lowerCAmelCase     ):
								"""simple docstring"""
								return self.tokenizer.batch_decode(*__lowerCAmelCase       ,					**__lowerCAmelCase     )







				def 			A	(						self       ,					*__lowerCAmelCase       ,					**__lowerCAmelCase     ):
								"""simple docstring"""
								return self.tokenizer.decode(*__lowerCAmelCase       ,					**__lowerCAmelCase     )







				def 			A	(						self       ,					__lowerCAmelCase       ,					__lowerCAmelCase="np"     ):
								"""simple docstring"""
								return self.tokenizer.get_prompt_ids(__lowerCAmelCase       ,					return_tensors=__lowerCAmelCase     )






