


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 			lowerCAmelCase (		lowerCAmelCase_ ,   lowerCAmelCase_ ,   lowerCAmelCase_ )-> Optional[Any]:
				return params[f"""{prefix}/{prefix}/relpos_bias/rel_embedding"""][:, i, :]



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



def 			lowerCAmelCase (		lowerCAmelCase_ ,   lowerCAmelCase_ ,   lowerCAmelCase_ ,   lowerCAmelCase_=False )-> Any:
				if split_mlp_wi:
								lowerCAmelCase_ :      List[Any]    				=				params[f"""{prefix}/{prefix}/mlp/wi_0/kernel"""][:, i, :]
								lowerCAmelCase_ :      Optional[int]    				=				params[f"""{prefix}/{prefix}/mlp/wi_1/kernel"""][:, i, :]
								lowerCAmelCase_ :      Optional[Any]    				=				(wi_a, wi_a)
				else:
								lowerCAmelCase_ :      List[str]    				=				params[f"""{prefix}/{prefix}/mlp/wi/kernel"""][:, i, :]

				lowerCAmelCase_ :      int    				=				params[f"""{prefix}/{prefix}/mlp/wo/kernel"""][:, i, :]
				return wi, wo



def 			lowerCAmelCase (		lowerCAmelCase_ ,   lowerCAmelCase_ ,   lowerCAmelCase_ ,   lowerCAmelCase_ )-> Union[str, Any]:
				return params[f"""{prefix}/{prefix}/{layer_name}/scale"""][:, i]



def 			lowerCAmelCase (		lowerCAmelCase_ ,   *, lowerCAmelCase_ ,   lowerCAmelCase_ ,   lowerCAmelCase_ = False )-> Dict:
				lowerCAmelCase_ :      Optional[int]    				=				traverse_util.flatten_dict(variables['''target'''] )
				lowerCAmelCase_ :      List[Any]    				=				{'''/'''.join(lowerCAmelCase_ ): v for k, v in old.items()}

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

				lowerCAmelCase_ :      Dict    				=				collections.OrderedDict()

				# Shared embeddings.
				lowerCAmelCase_ :      Union[str, Any]    				=				old['''token_embedder/embedding''']

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

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

				lowerCAmelCase_ :      Tuple    				=				old['''encoder/encoder_norm/scale''']

				if not scalable_attention:
								lowerCAmelCase_ :      Dict    				=				tax_relpos_bias_lookup(
								    lowerCAmelCase_ ,   0 ,   '''encoder''' ).T
								lowerCAmelCase_ :      Any    				=				tax_relpos_bias_lookup(
								    lowerCAmelCase_ ,   0 ,   '''decoder''' ).T

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

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

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

												if scalable_attention:
																# convert the rel_embedding of each layer
																lowerCAmelCase_ :      int    				=				tax_relpos_bias_lookup(lowerCAmelCase_ ,   lowerCAmelCase_ ,   '''decoder''' ).T

								lowerCAmelCase_ :      int    				=				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:
												lowerCAmelCase_ :      Union[str, Any]    				=				old['''decoder/logits_dense/kernel'''].T

				return new



def 			lowerCAmelCase (		lowerCAmelCase_ ,   lowerCAmelCase_ )-> int:
				lowerCAmelCase_ :      Dict    				=				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:
								lowerCAmelCase_ :      Tuple    				=				state_dict['''shared.weight''']

				if not is_encoder_only:
								if "decoder.embed_tokens.weight" not in state_dict:
												lowerCAmelCase_ :      Union[str, Any]    				=				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.''' )
												lowerCAmelCase_ :      Tuple    				=				state_dict['''shared.weight''']

				return state_dict



def 			lowerCAmelCase (		lowerCAmelCase_ ,   lowerCAmelCase_ ,   lowerCAmelCase_ ,   lowerCAmelCase_ ,   lowerCAmelCase_ )-> Tuple:
				lowerCAmelCase_ :      Union[str, Any]    				=				checkpoints.load_tax_checkpoint(lowerCAmelCase_ )
				lowerCAmelCase_ :      Tuple    				=				convert_tax_to_pytorch(
				    lowerCAmelCase_ ,   num_layers=config.num_layers ,   is_encoder_only=lowerCAmelCase_ ,   scalable_attention=lowerCAmelCase_ )
				lowerCAmelCase_ :      Optional[int]    				=				make_state_dict(lowerCAmelCase_ ,   lowerCAmelCase_ )
				model.load_state_dict(lowerCAmelCase_ ,   strict=lowerCAmelCase_ )



def 			lowerCAmelCase (		lowerCAmelCase_ ,   lowerCAmelCase_ ,   lowerCAmelCase_ ,   lowerCAmelCase_ = False ,   lowerCAmelCase_ = False ,   )-> Optional[Any]:
				lowerCAmelCase_ :      Union[str, Any]    				=				MTaConfig.from_json_file(lowerCAmelCase_ )
				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:
								lowerCAmelCase_ :      Tuple    				=				UMTaEncoderModel(lowerCAmelCase_ )
				else:
								lowerCAmelCase_ :      Tuple    				=				UMTaForConditionalGeneration(lowerCAmelCase_ )

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

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

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


if __name__ == "__main__":
						_UpperCAmelCase			:  Dict     =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,
						)
						_UpperCAmelCase			:  Optional[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 __future__ import annotations



def 			lowerCAmelCase (		lowerCAmelCase_ ,   lowerCAmelCase_ ,   lowerCAmelCase_ ,   )-> tuple:
				if (electron_conc, hole_conc, intrinsic_conc).count(0 ) != 1:
								raise ValueError('''You cannot supply more or less than 2 values''' )
				elif electron_conc < 0:
								raise ValueError('''Electron concentration cannot be negative in a semiconductor''' )
				elif hole_conc < 0:
								raise ValueError('''Hole concentration cannot be negative in a semiconductor''' )
				elif intrinsic_conc < 0:
								raise ValueError(
								    '''Intrinsic concentration cannot be negative in a semiconductor''' )
				elif electron_conc == 0:
								return (
								    "electron_conc",
								    intrinsic_conc**2 / hole_conc,
								)
				elif hole_conc == 0:
								return (
								    "hole_conc",
								    intrinsic_conc**2 / electron_conc,
								)
				elif intrinsic_conc == 0:
								return (
								    "intrinsic_conc",
								    (electron_conc * hole_conc) ** 0.5,
								)
				else:
								return (-1, -1)


if __name__ == "__main__":
						import doctest

						doctest.testmod()