


"""simple docstring"""


import inspect

import jax
import jax.lax as lax
import jax.numpy as jnp

from ..utils import add_start_docstrings
from ..utils.logging import get_logger


a_       							=    get_logger(__name__)


a_       							=    R"\n    Args:\n        input_ids (`jnp.ndarray` of shape `(batch_size, sequence_length)`):\n            Indices of input sequence tokens in the vocabulary.\n\n            Indices can be obtained using [`PreTrainedTokenizer`]. See [`PreTrainedTokenizer.encode`] and\n            [`PreTrainedTokenizer.__call__`] for details.\n\n            [What are input IDs?](../glossary#input-ids)\n        scores (`jnp.ndarray` of shape `(batch_size, config.vocab_size)`):\n            Prediction scores of a language modeling head. These can be logits for each vocabulary when not using beam\n            search or log softmax for each vocabulary token when using beam search\n        kwargs (`Dict[str, Any]`, *optional*):\n            Additional logits processor specific kwargs.\n\n    Return:\n        `jnp.ndarray` of shape `(batch_size, config.vocab_size)`: The processed prediction scores.\n\n"
class snake_case      :







		@add_start_docstrings(a__		)
		def __call__(					self      :       Tuple    ,   a__      :       jnp.ndarray    ,   a__      :       jnp.ndarray		)       ->						jnp.ndarray:





						'''simple docstring'''







						raise NotImplementedError(
						    F"""{self.__class__} is an abstract class. Only classes inheriting this class can be called."""		)





class snake_case      :







		@add_start_docstrings(a__		)
		def __call__(					self      :       Any    ,   a__      :       jnp.ndarray    ,   a__      :       jnp.ndarray		)       ->						jnp.ndarray:





						'''simple docstring'''







						raise NotImplementedError(
						    F"""{self.__class__} is an abstract class. Only classes inheriting this class can be called."""		)





class snake_case      (  _UpperCamelCase):







		@add_start_docstrings(a__		)
		def __call__(					self      :       Optional[int]    ,   a__      :       jnp.ndarray    ,   a__      :       jnp.ndarray    ,   a__      :       int    ,   **a__      :       str		)       ->						jnp.ndarray:





						'''simple docstring'''







						for processor in self:
										_A					  =			inspect.signature(processor.__call__		).parameters
										if len(a__		) > 3:
														if not all(arg in kwargs for arg in list(function_args.keys()		)[2:]		):
																		raise ValueError(
																		    F"""Make sure that all the required parameters: {list(function_args.keys()		)} for """
																		    F"""{processor.__class__} are passed to the logits processor."""		)
														_A					  =			processor(a__    ,   a__    ,   a__    ,   **a__		)
										else:
														_A					  =			processor(a__    ,   a__    ,   a__		)
						return scores





class snake_case      (  _UpperCamelCase):







		def __init__(					self      :       Optional[Any]    ,   a__      :       float		)       ->						int:





						'''simple docstring'''







						if not isinstance(a__    ,   a__		) or not (temperature > 0):
										raise ValueError(F"""`temperature` has to be a strictly positive float, but is {temperature}"""		)

						_A					  =			temperature







		def __call__(					self      :       str    ,   a__      :       jnp.ndarray    ,   a__      :       jnp.ndarray    ,   a__      :       int		)       ->						jnp.ndarray:





						'''simple docstring'''







						_A					  =			scores / self.temperature
						return scores





class snake_case      (  _UpperCamelCase):







		def __init__(					self      :       Any    ,   a__      :       float    ,   a__      :       float = -float("Inf"		)    ,   a__      :       int = 1		)       ->						List[Any]:





						'''simple docstring'''







						if not isinstance(a__    ,   a__		) or (top_p < 0 or top_p > 1.0):
										raise ValueError(F"""`top_p` has to be a float > 0 and < 1, but is {top_p}"""		)
						if not isinstance(a__    ,   a__		) or (min_tokens_to_keep < 1):
										raise ValueError(F"""`min_tokens_to_keep` has to be a positive integer, but is {min_tokens_to_keep}"""		)

						_A					  =			top_p
						_A					  =			filter_value
						_A					  =			min_tokens_to_keep







		def __call__(					self      :       str    ,   a__      :       jnp.ndarray    ,   a__      :       jnp.ndarray    ,   a__      :       int		)       ->						jnp.ndarray:





						'''simple docstring'''







						_A  ,		_A					  =			lax.top_k(a__    ,   scores.shape[-1]		)

						_A					  =			jnp.full_like(a__    ,   self.filter_value		)
						_A					  =			jax.nn.softmax(a__    ,   axis=-1		).cumsum(axis=-1		)
						_A					  =			cumulative_probs < self.top_p

						# include the token that is higher than top_p as well
						_A					  =			jnp.roll(a__    ,   1		)
						score_mask |= score_mask.at[:, 0].set(a__		)

						# min tokens to keep
						_A					  =			score_mask.at[:, : self.min_tokens_to_keep].set(a__		)

						_A					  =			jnp.where(a__    ,   a__    ,   a__		)
						_A					  =			jax.lax.sort_key_val(a__    ,   a__		)[-1]

						return next_scores





class snake_case      (  _UpperCamelCase):







		def __init__(					self      :       Union[str, Any]    ,   a__      :       int    ,   a__      :       float = -float("Inf"		)    ,   a__      :       int = 1		)       ->						Optional[Any]:





						'''simple docstring'''







						if not isinstance(a__    ,   a__		) or top_k <= 0:
										raise ValueError(F"""`top_k` has to be a strictly positive integer, but is {top_k}"""		)

						_A					  =			max(a__    ,   a__		)
						_A					  =			filter_value







		def __call__(					self      :       Union[str, Any]    ,   a__      :       jnp.ndarray    ,   a__      :       jnp.ndarray    ,   a__      :       int		)       ->						jnp.ndarray:





						'''simple docstring'''







						_A  ,		_A					  =			scores.shape
						_A					  =			jnp.full(batch_size * vocab_size    ,   self.filter_value		)

						_A					  =			min(self.top_k    ,   scores.shape[-1]		)  # Safety check
						_A  ,		_A					  =			lax.top_k(a__    ,   a__		)
						_A					  =			jnp.broadcast_to((jnp.arange(a__		) * vocab_size)[:, None]    ,   (batch_size, topk)		).flatten()
						_A					  =			topk_scores.flatten()
						_A					  =			topk_indices.flatten() + shift

						_A					  =			next_scores_flat.at[topk_indices_flat].set(a__		)
						_A					  =			next_scores_flat.reshape(a__    ,   a__		)
						return next_scores





class snake_case      (  _UpperCamelCase):







		def __init__(					self      :       Any    ,   a__      :       int		)       ->						Any:





						'''simple docstring'''







						_A					  =			bos_token_id







		def __call__(					self      :       str    ,   a__      :       jnp.ndarray    ,   a__      :       jnp.ndarray    ,   a__      :       int		)       ->						jnp.ndarray:





						'''simple docstring'''







						_A					  =			jnp.full(scores.shape    ,   -float("inf"		)		)

						_A					  =			1 - jnp.bool_(cur_len - 1		)

						_A					  =			jnp.where(a__    ,   new_scores.at[:, self.bos_token_id].set(0		)    ,   a__		)

						return scores





class snake_case      (  _UpperCamelCase):







		def __init__(					self      :       int    ,   a__      :       int    ,   a__      :       int		)       ->						Dict:





						'''simple docstring'''







						_A					  =			max_length
						_A					  =			eos_token_id







		def __call__(					self      :       Any    ,   a__      :       jnp.ndarray    ,   a__      :       jnp.ndarray    ,   a__      :       int		)       ->						jnp.ndarray:





						'''simple docstring'''







						_A					  =			jnp.full(scores.shape    ,   -float("inf"		)		)

						_A					  =			1 - jnp.bool_(cur_len - self.max_length + 1		)

						_A					  =			jnp.where(a__    ,   new_scores.at[:, self.eos_token_id].set(0		)    ,   a__		)

						return scores





class snake_case      (  _UpperCamelCase):







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





						'''simple docstring'''







						if not isinstance(a__    ,   a__		) or min_length < 0:
										raise ValueError(F"""`min_length` has to be a positive integer, but is {min_length}"""		)

						if not isinstance(a__    ,   a__		) or eos_token_id < 0:
										raise ValueError(F"""`eos_token_id` has to be a positive integer, but is {eos_token_id}"""		)

						_A					  =			min_length
						_A					  =			eos_token_id







		def __call__(					self      :       int    ,   a__      :       jnp.ndarray    ,   a__      :       jnp.ndarray    ,   a__      :       int		)       ->						jnp.ndarray:





						'''simple docstring'''







						_A					  =			1 - jnp.clip(cur_len - self.min_length    ,   0    ,   1		)

						_A					  =			jnp.where(a__    ,   scores.at[:, self.eos_token_id].set(-float("inf"		)		)    ,   a__		)

						return scores





class snake_case      (  _UpperCamelCase):







		def __init__(					self      :       Any    ,   a__      :       int    ,   a__      :       str		)       ->						List[Any]:





						'''simple docstring'''







						_A					  =			list(a__		)
						_A					  =			begin_index







		def __call__(					self      :       List[Any]    ,   a__      :       Tuple    ,   a__      :       Tuple    ,   a__      :       int		)       ->						Dict:





						'''simple docstring'''







						_A					  =			1 - jnp.bool_(cur_len - self.begin_index		)

						_A					  =			jnp.where(a__    ,   scores.at[:, self.begin_suppress_tokens].set(-float("inf"		)		)    ,   a__		)

						return scores





class snake_case      (  _UpperCamelCase):







		def __init__(					self      :       List[str]    ,   a__      :       list		)       ->						Union[str, Any]:





						'''simple docstring'''







						_A					  =			list(a__		)







		def __call__(					self      :       List[Any]    ,   a__      :       jnp.ndarray    ,   a__      :       jnp.ndarray    ,   a__      :       int		)       ->						jnp.ndarray:





						'''simple docstring'''







						_A					  =			scores.at[..., self.suppress_tokens].set(-float("inf"		)		)

						return scores





class snake_case      (  _UpperCamelCase):







		def __init__(					self      :       int    ,   a__      :       Optional[int]		)       ->						Optional[int]:





						'''simple docstring'''







						_A					  =			dict(a__		)
						# Converts the dictionary of format {index: token} containing the tokens to be forced to an array, where the
						# index of the array corresponds to the index of the token to be forced, for XLA compatibility.
						# Indexes without forced tokens will have a negative value.
						_A					  =			jnp.ones((max(force_token_map.keys()		) + 1)    ,   dtype=jnp.intaa		) * -1
						for index, token in force_token_map.items():
										if token is not None:
														_A					  =			force_token_array.at[index].set(a__		)
						_A					  =			jnp.intaa(a__		)







		def __call__(					self      :       Union[str, Any]    ,   a__      :       jnp.ndarray    ,   a__      :       jnp.ndarray    ,   a__      :       int		)       ->						jnp.ndarray:





						'''simple docstring'''







						def _force_token(a__      :       Tuple		):
										_A					  =			scores.shape[0]
										_A					  =			self.force_token_array[generation_idx]

										_A					  =			jnp.ones_like(a__    ,   dtype=scores.dtype		) * -float("inf"		)
										_A					  =			jnp.zeros((batch_size, 1)    ,   dtype=scores.dtype		)
										_A					  =			lax.dynamic_update_slice(a__    ,   a__    ,   (0, current_token)		)
										return new_scores

						_A					  =			lax.cond(
						    cur_len >= self.force_token_array.shape[0]    ,   lambda: scores    ,   lambda: lax.cond(
						        self.force_token_array[cur_len] >= 0    ,   lambda: _force_token(a__		)    ,   lambda: scores    ,   )    ,   )
						return scores





class snake_case      (  _UpperCamelCase):







		def __init__(					self      :       int    ,   a__      :       Any    ,   a__      :       Dict    ,   a__      :       List[str]		)       ->						str:





						'''simple docstring'''







						_A					  =			generate_config.eos_token_id
						_A					  =			generate_config.no_timestamps_token_id
						_A					  =			generate_config.no_timestamps_token_id + 1

						_A					  =			decoder_input_length + 1

						if generate_config.is_multilingual:
										# room for language token and task token
										self.begin_index += 2
						if hasattr(a__    ,   "max_initial_timestamp_index"		):
										_A					  =			generate_config.max_initial_timestamp_index
						else:
										_A					  =			model_config.vocab_size
						if self.max_initial_timestamp_index is None:
										_A					  =			model_config.vocab_size







		def __call__(					self      :       Dict    ,   a__      :       Any    ,   a__      :       int    ,   a__      :       List[str]		)       ->						Dict:





						'''simple docstring'''







						_A					  =			scores.at[:, self.no_timestamps_token_id].set(-float("inf"		)		)

						def handle_pairs(a__      :       Optional[Any]    ,   a__      :       Dict		):
										_A					  =			jnp.where((cur_len - self.begin_index) >= 1    ,   a__    ,   a__		)
										_A					  =			jnp.where(
										    input_ids_k[cur_len - 1] >= self.timestamp_begin    ,   True and last_was_timestamp    ,   a__    ,   )

										_A					  =			jnp.where((cur_len - self.begin_index) < 2    ,   a__    ,   a__		)
										_A					  =			jnp.where(
										    input_ids_k[cur_len - 2] >= self.timestamp_begin    ,   a__    ,   a__    ,   )

										return jnp.where(
										    a__    ,   jnp.where(
										        penultimate_was_timestamp > 0    ,   scores_k.at[self.timestamp_begin :].set(-float("inf"		)		)    ,   scores_k.at[: self.eos_token_id].set(-float("inf"		)		)    ,   )    ,   a__    ,   )

						_A					  =			jax.vmap(a__		)(a__    ,   a__		)

						_A					  =			jnp.where(cur_len == self.begin_index    ,   a__    ,   a__		)
						_A					  =			jnp.where(
						    self.max_initial_timestamp_index is not None    ,   True and apply_max_initial_timestamp    ,   a__    ,   )

						_A					  =			self.timestamp_begin + self.max_initial_timestamp_index

						_A					  =			jnp.where(
						    a__    ,   scores.at[:, last_allowed + 1 :].set(-float("inf"		)		)    ,   a__    ,   )

						# if sum of probability over timestamps is above any other token, sample timestamp
						_A					  =			jax.nn.log_softmax(a__    ,   axis=-1		)

						def handle_cumulative_probs(a__      :       int    ,   a__      :       Tuple		):
										_A					  =			jax.nn.logsumexp(logprobs_k[self.timestamp_begin :]    ,   axis=-1		)
										_A					  =			jnp.max(logprobs_k[: self.timestamp_begin]		)
										return jnp.where(
										    timestamp_logprob > max_text_token_logprob    ,   scores_k.at[: self.timestamp_begin].set(-float("inf"		)		)    ,   a__    ,   )

						_A					  =			jax.vmap(a__		)(a__    ,   a__		)

						return scores



"""simple docstring"""


import argparse
import json
import os
from collections import OrderedDict

import numpy as np
import tensorflow as tf
import torch






def      a__ (				__lowercase   )	->	List[Any]:
				_A					  =			os.path.join(args.tf_model_dir     ,			"parameters.json"   )
				_A					  =			json.loads(open(__lowercase   ).read()   )
				if not params:
								raise ValueError(
								    f"""It seems that the json file at {parameter_file} is empty. Make sure you have a correct json file."""   )
				if not args.output.endswith(".pt"   ):
								_A					  =			args.output + ".pt"
				_A					  =			OrderedDict()
				with tf.device("/CPU:0"   ):
								_A					  =			tf.train.load_checkpoint(args.tf_model_dir   )
								_A					  =			reader.get_variable_to_shape_map()
								for key_name in shapes.keys():
												_A					  =			reader.get_tensor(__lowercase   ).astype(np.floataa   )
												if key_name.endswith("/adam_m"   ) or key_name.endswith("/adam_v"   ):
																continue
												if key_name.startswith("pasts/"   ):
																if key_name.startswith("pasts/mlp"   ):
																				_A					  =			int(key_name[9]   )
																elif key_name.startswith("pasts/out"   ):
																				_A					  =			8
																_A					  =			"model.sqout.%d.weight" % (player * 2)  # enter to nn.Sequencial with Tanh, so 2 at a time
																_A					  =			vnp.transpose([1, 0]   ).copy()  # Mesh-Tensorflow is a diagonal matrix
																_A					  =			torch.tensor(__lowercase   )
												elif key_name.startswith("model/moe"   ):
																_A					  =			int(key_name[9:].split("/"   )[0]   )
																if key_name.endswith("/switch_gating/kernel"   ):
																				_A					  =			"model.blocks.%d.feed_forward.mlp.router.classifier.weight" % player
																				_A					  =			vnp.transpose([1, 0]   ).copy()  # Mesh-Tensorflow is a diagonal matrix
																				_A					  =			torch.tensor(__lowercase   )
																elif key_name.endswith("/softmlp/kernel"   ):
																				_A					  =			"model.blocks.%d.feed_forward.soft_bypass_mlp.weight" % player
																				_A					  =			vnp.transpose([1, 0]   ).copy()  # Mesh-Tensorflow is a diagonal matrix
																				_A					  =			torch.tensor(__lowercase   )
																elif key_name.endswith("/wo/kernel"   ) or key_name.endswith("/wi/kernel"   ):
																				_A					  =			key_name[-9:-7]
																				for i in range(16   ):
																								_A					  =			"model.blocks.%d.feed_forward.mlp.experts.expert_%d.%s.weight" % (player, i, nlayer)
																								_A					  =			(
																								    vnp[i].transpose([1, 0]   ).copy()
																								)  # In Mesh-Tensorflow, it is one array, so it is divided
																								_A					  =			torch.tensor(__lowercase   )
												elif key_name.startswith("model/mlp"   ):
																_A					  =			int(key_name[9:].split("/"   )[0]   )
																if key_name.endswith("/p1/kernel"   ):
																				_A					  =			"model.blocks.%d.feed_forward.mlp.wi.weight" % player
																				_A					  =			vnp.transpose([1, 0]   ).copy()  # Mesh-Tensorflow is a diagonal matrix
																				_A					  =			torch.tensor(__lowercase   )
																elif key_name.endswith("/p1/bias"   ):
																				_A					  =			"model.blocks.%d.feed_forward.mlp.wi.bias" % player
																				_A					  =			vnp.copy()  # same because it is one dimensional
																				_A					  =			torch.tensor(__lowercase   )
																elif key_name.endswith("/p2/kernel"   ):
																				_A					  =			"model.blocks.%d.feed_forward.mlp.wo.weight" % player
																				_A					  =			vnp.transpose([1, 0]   ).copy()  # Mesh-Tensorflow is a diagonal matrix
																				_A					  =			torch.tensor(__lowercase   )
																elif key_name.endswith("/p2/bias"   ):
																				_A					  =			"model.blocks.%d.feed_forward.mlp.wo.bias" % player
																				_A					  =			vnp.copy()  # same because it is one dimensional
																				_A					  =			torch.tensor(__lowercase   )
												elif key_name.startswith("model/ln"   ):
																_A					  =			int(key_name[8:].split("/"   )[0]   )
																if key_name.endswith("/b"   ):
																				_A					  =			"model.blocks.%d.feed_forward.norm.bias" % player
																				_A					  =			vnp.copy()  # same because it is one dimensional
																				_A					  =			torch.tensor(__lowercase   )
																elif key_name.endswith("/g"   ):
																				_A					  =			"model.blocks.%d.feed_forward.norm.weight" % player
																				_A					  =			vnp.copy()  # same because it is one dimensional
																				_A					  =			torch.tensor(__lowercase   )
												elif key_name.startswith("model/att"   ):
																_A					  =			int(key_name[9:].split("/"   )[0]   )
																if key_name.endswith("/qkv/kernel"   ):
																				_A					  =			vnp.copy()  # Compute same dimension as Mesh-tensorflow using einsum
																				_A					  =			state[:, 0, :, :]
																				_A					  =			state[:, 1, :, :]
																				_A					  =			state[:, 2, :, :]
																				_A					  =			(
																				    state_q.reshape([state_q.shape[0], state_q.shape[1] * state_q.shape[2]]   )
																				    .transpose([1, 0]   )
																				    .copy()
																				)  # Mesh-Tensorflow is a diagonal matrix
																				_A					  =			(
																				    state_k.reshape([state_k.shape[0], state_k.shape[1] * state_k.shape[2]]   )
																				    .transpose([1, 0]   )
																				    .copy()
																				)  # Mesh-Tensorflow is a diagonal matrix
																				_A					  =			(
																				    state_v.reshape([state_v.shape[0], state_v.shape[1] * state_v.shape[2]]   )
																				    .transpose([1, 0]   )
																				    .copy()
																				)  # Mesh-Tensorflow is a diagonal matrix
																				_A					  =			"model.blocks.%d.self_attn.self_attn.q_proj.weight" % player
																				_A					  =			torch.tensor(__lowercase   )
																				_A					  =			"model.blocks.%d.self_attn.self_attn.k_proj.weight" % player
																				_A					  =			torch.tensor(__lowercase   )
																				_A					  =			"model.blocks.%d.self_attn.self_attn.v_proj.weight" % player
																				_A					  =			torch.tensor(__lowercase   )
																elif key_name.endswith("/o/kernel"   ):
																				_A					  =			"model.blocks.%d.self_attn.self_attn.out_proj.weight" % player
																				_A					  =			(
																				    vnp.reshape([vnp.shape[0] * vnp.shape[1], vnp.shape[2]]   ).transpose([1, 0]   ).copy()
																				)  # Mesh-Tensorflow is a diagonal matrix
																				_A					  =			torch.tensor(__lowercase   )
												elif key_name.startswith("model/an"   ):
																_A					  =			int(key_name[8:].split("/"   )[0]   )
																if key_name.endswith("/b"   ):
																				_A					  =			"model.blocks.%d.self_attn.norm.bias" % player
																				_A					  =			vnp.copy()  # same because it is one dimensional
																				_A					  =			torch.tensor(__lowercase   )
																elif key_name.endswith("/g"   ):
																				_A					  =			"model.blocks.%d.self_attn.norm.weight" % player
																				_A					  =			vnp.copy()  # same because it is one dimensional
																				_A					  =			torch.tensor(__lowercase   )
												elif (
												    key_name.startswith("model/wte"   )
												    or key_name.startswith("model/wpe"   )
												    or key_name.startswith("model/ete"   )
												):
																_A					  =			{"wte": "embed_tokens", "wpe": "position_embeddings", "ete": "extra_position_embeddings"}[
																    key_name[-3:]
																]
																_A					  =			"model.%s.weight" % nlayer
																_A					  =			vnp.copy()  # same in embedded
																_A					  =			torch.tensor(__lowercase   )
																if key_name.startswith("model/wte"   ):
																				_A					  =			"lm_head.weight"
																				_A					  =			vnp.copy()  # same in embedded
																				_A					  =			torch.tensor(__lowercase   )
												elif key_name.startswith("model/wob"   ):
																_A					  =			"final_logits_bias"
																_A					  =			vnp.copy()  # same in embedded
																_A					  =			state.reshape((1, -1)   )
																_A					  =			torch.tensor(__lowercase   )
												elif key_name == "model/dense/kernel":
																_A					  =			"model.last_project.weight"
																_A					  =			vnp.transpose([1, 0]   ).copy()  # Mesh-Tensorflow is a diagonal matrix
																_A					  =			torch.tensor(__lowercase   )
												elif key_name == "model/dense_1/bias":
																_A					  =			"model.last_project.bias"
																_A					  =			vnp.copy()  # same because it is one dimensional
																_A					  =			torch.tensor(__lowercase   )
				torch.save(__lowercase     ,			args.output   )


if __name__ == "__main__":
		a_       							=    argparse.ArgumentParser(
		    description="model converter.", formatter_class=argparse.ArgumentDefaultsHelpFormatter
		)
		parser.add_argument("--tf_model_dir", metavar="PATH", type=str, required=True, help="import model")
		parser.add_argument("--output", metavar="PATH", type=str, required=True, help="output model")
		a_       							=    parser.parse_args()
		convert_tf_gptsan_to_pt(args)