
"""simple docstring"""



import argparse
import collections

import torch
from flax import traverse_util
from tax import checkpoints

from transformers import TaConfig, TaEncoderModel, TaForConditionalGeneration
from transformers.utils import logging


logging.set_verbosity_info()






def 	__snake_case  (    SCREAMING_SNAKE_CASE:					int     ,  SCREAMING_SNAKE_CASE:					List[Any]     ,  SCREAMING_SNAKE_CASE:					int     ,  SCREAMING_SNAKE_CASE:					Any="attention"						):






							"""simple docstring"""



							_lowerCAmelCase  	=			params[f"""{prefix}/layers_{i}/{layer_name}/key/kernel"""]
							_lowerCAmelCase  	=			params[f"""{prefix}/layers_{i}/{layer_name}/out/kernel"""]
							_lowerCAmelCase  	=			params[f"""{prefix}/layers_{i}/{layer_name}/query/kernel"""]
							_lowerCAmelCase  	=			params[f"""{prefix}/layers_{i}/{layer_name}/value/kernel"""]
							return k, o, q, v






def 	__snake_case  (    SCREAMING_SNAKE_CASE:					Union[str, Any]     ,  SCREAMING_SNAKE_CASE:					Optional[int]     ,  SCREAMING_SNAKE_CASE:					Optional[Any]     ,  SCREAMING_SNAKE_CASE:					Optional[int]=False						):






							"""simple docstring"""



							if split_mlp_wi:
														_lowerCAmelCase  	=			params[f"""{prefix}/layers_{i}/mlp/wi_0/kernel"""]
														_lowerCAmelCase  	=			params[f"""{prefix}/layers_{i}/mlp/wi_1/kernel"""]
														_lowerCAmelCase  	=			(wi_a, wi_a)
							else:
														_lowerCAmelCase  	=			params[f"""{prefix}/layers_{i}/mlp/wi/kernel"""]

							_lowerCAmelCase  	=			params[f"""{prefix}/layers_{i}/mlp/wo/kernel"""]
							return wi, wo






def 	__snake_case  (    SCREAMING_SNAKE_CASE:					Any     ,  SCREAMING_SNAKE_CASE:					int     ,  SCREAMING_SNAKE_CASE:					Tuple     ,  SCREAMING_SNAKE_CASE:					Optional[Any]						):






							"""simple docstring"""



							return params[f"""{prefix}/layers_{i}/{layer_name}/scale"""]






def 	__snake_case  (    SCREAMING_SNAKE_CASE:					Union[str, Any]     ,  *, SCREAMING_SNAKE_CASE:					Any     ,  SCREAMING_SNAKE_CASE:					Dict						):






							"""simple docstring"""



							_lowerCAmelCase  	=			traverse_util.flatten_dict(variables['target']						)
							_lowerCAmelCase  	=			{"/".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  	=			"encoder/layers_0/mlp/wi_0/kernel" in old
							print('Split MLP:'     ,  lowerCamelCase__						)

							_lowerCAmelCase  	=			collections.OrderedDict()

							# Shared embeddings.
							_lowerCAmelCase  	=			old["token_embedder/embedding"]

							# Encoder.
							for i in range(lowerCamelCase__						):
														# Block i, layer 0 (Self Attention).
														_lowerCAmelCase  	=			tax_layer_norm_lookup(lowerCamelCase__     ,  lowerCamelCase__     ,  'encoder'     ,  'pre_attention_layer_norm'						)
														_lowerCAmelCase  	=			tax_attention_lookup(lowerCamelCase__     ,  lowerCamelCase__     ,  'encoder'     ,  'attention'						)
														_lowerCAmelCase  	=			layer_norm
														_lowerCAmelCase  	=			k.T
														_lowerCAmelCase  	=			o.T
														_lowerCAmelCase  	=			q.T
														_lowerCAmelCase  	=			v.T

														# Block i, layer 1 (MLP).
														_lowerCAmelCase  	=			tax_layer_norm_lookup(lowerCamelCase__     ,  lowerCamelCase__     ,  'encoder'     ,  'pre_mlp_layer_norm'						)
														_lowerCAmelCase  	=			tax_mlp_lookup(lowerCamelCase__     ,  lowerCamelCase__     ,  'encoder'     ,  lowerCamelCase__						)
														_lowerCAmelCase  	=			layer_norm
														if split_mlp_wi:
																					_lowerCAmelCase  	=			wi[0].T
																					_lowerCAmelCase  	=			wi[1].T
														else:
																					_lowerCAmelCase  	=			wi.T
														_lowerCAmelCase  	=			wo.T

							_lowerCAmelCase  	=			old[
							    "encoder/relpos_bias/rel_embedding"
							].T
							_lowerCAmelCase  	=			old["encoder/encoder_norm/scale"]

							if not is_encoder_only:
														# Decoder.
														for i in range(lowerCamelCase__						):
																					# Block i, layer 0 (Self Attention).
																					_lowerCAmelCase  	=			tax_layer_norm_lookup(lowerCamelCase__     ,  lowerCamelCase__     ,  'decoder'     ,  'pre_self_attention_layer_norm'						)
																					_lowerCAmelCase  	=			tax_attention_lookup(lowerCamelCase__     ,  lowerCamelCase__     ,  'decoder'     ,  'self_attention'						)
																					_lowerCAmelCase  	=			layer_norm
																					_lowerCAmelCase  	=			k.T
																					_lowerCAmelCase  	=			o.T
																					_lowerCAmelCase  	=			q.T
																					_lowerCAmelCase  	=			v.T

																					# Block i, layer 1 (Cross Attention).
																					_lowerCAmelCase  	=			tax_layer_norm_lookup(lowerCamelCase__     ,  lowerCamelCase__     ,  'decoder'     ,  'pre_cross_attention_layer_norm'						)
																					_lowerCAmelCase  	=			tax_attention_lookup(lowerCamelCase__     ,  lowerCamelCase__     ,  'decoder'     ,  'encoder_decoder_attention'						)
																					_lowerCAmelCase  	=			layer_norm
																					_lowerCAmelCase  	=			k.T
																					_lowerCAmelCase  	=			o.T
																					_lowerCAmelCase  	=			q.T
																					_lowerCAmelCase  	=			v.T

																					# Block i, layer 2 (MLP).
																					_lowerCAmelCase  	=			tax_layer_norm_lookup(lowerCamelCase__     ,  lowerCamelCase__     ,  'decoder'     ,  'pre_mlp_layer_norm'						)
																					_lowerCAmelCase  	=			tax_mlp_lookup(lowerCamelCase__     ,  lowerCamelCase__     ,  'decoder'     ,  lowerCamelCase__						)
																					_lowerCAmelCase  	=			layer_norm
																					if split_mlp_wi:
																												_lowerCAmelCase  	=			wi[0].T
																												_lowerCAmelCase  	=			wi[1].T
																					else:
																												_lowerCAmelCase  	=			wi.T
																					_lowerCAmelCase  	=			wo.T

														_lowerCAmelCase  	=			old["decoder/decoder_norm/scale"]
														_lowerCAmelCase  	=			old[
														    "decoder/relpos_bias/rel_embedding"
														].T

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

							return new






def 	__snake_case  (    SCREAMING_SNAKE_CASE:					Optional[Any]     ,  SCREAMING_SNAKE_CASE:					Union[str, Any]						):






							"""simple docstring"""



							_lowerCAmelCase  	=			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  	=			state_dict["shared.weight"]

							if not is_encoder_only:
														if "decoder.embed_tokens.weight" not in state_dict:
																					_lowerCAmelCase  	=			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  	=			state_dict["shared.weight"]

							return state_dict






def 	__snake_case  (    SCREAMING_SNAKE_CASE:					int     ,  SCREAMING_SNAKE_CASE:					Tuple     ,  SCREAMING_SNAKE_CASE:					Optional[Any]     ,  SCREAMING_SNAKE_CASE:					List[Any]						):






							"""simple docstring"""



							_lowerCAmelCase  	=			checkpoints.load_tax_checkpoint(lowerCamelCase__						)
							_lowerCAmelCase  	=			convert_tax_to_pytorch(lowerCamelCase__     ,  num_layers=config.num_layers     ,  is_encoder_only=lowerCamelCase__						)
							_lowerCAmelCase  	=			make_state_dict(lowerCamelCase__     ,  lowerCamelCase__						)
							model.load_state_dict(lowerCamelCase__     ,  strict=lowerCamelCase__						)






def 	__snake_case  (    SCREAMING_SNAKE_CASE:					List[Any]     ,  SCREAMING_SNAKE_CASE:					Optional[int]     ,  SCREAMING_SNAKE_CASE:					int     ,  SCREAMING_SNAKE_CASE:					List[Any] = False						):






							"""simple docstring"""



							_lowerCAmelCase  	=			TaConfig.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  	=			TaEncoderModel(lowerCamelCase__						)
							else:
														_lowerCAmelCase  	=			TaForConditionalGeneration(lowerCamelCase__						)

							# Load weights from tf checkpoint
							load_tax_weights_in_ta(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__":
	_snake_case          =						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
	)
	_snake_case          =						parser.parse_args()
	convert_tax_checkpoint_to_pytorch(
	    args.tax_checkpoint_path, args.config_file, args.pytorch_dump_path, args.is_encoder_only
	)








"""simple docstring"""



def 	__snake_case  (    SCREAMING_SNAKE_CASE:					int						):






							"""simple docstring"""



							_lowerCAmelCase  	=			generate_pascal_triangle(SCREAMING_SNAKE_CASE						)
							for row_idx in range(SCREAMING_SNAKE_CASE						):
														# Print left spaces
														for _ in range(num_rows - row_idx - 1						):
																					print(end=' '						)
														# Print row values
														for col_idx in range(row_idx + 1						):
																					if col_idx != row_idx:
																												print(triangle[row_idx][col_idx]     ,  end=' '						)
																					else:
																												print(triangle[row_idx][col_idx]     ,  end=''						)
														print()






def 	__snake_case  (    SCREAMING_SNAKE_CASE:					int						):






							"""simple docstring"""



							if not isinstance(SCREAMING_SNAKE_CASE     ,  SCREAMING_SNAKE_CASE						):
														raise TypeError('The input value of \'num_rows\' should be \'int\''						)

							if num_rows == 0:
														return []
							elif num_rows < 0:
														raise ValueError(
														    'The input value of \'num_rows\' should be greater than or equal to 0'						)

							_lowerCAmelCase  	=			[]
							for current_row_idx in range(SCREAMING_SNAKE_CASE						):
														_lowerCAmelCase  	=			populate_current_row(SCREAMING_SNAKE_CASE     ,  SCREAMING_SNAKE_CASE						)
														triangle.append(SCREAMING_SNAKE_CASE						)
							return triangle






def 	__snake_case  (    SCREAMING_SNAKE_CASE:					list[list[int]]     ,  SCREAMING_SNAKE_CASE:					int						):






							"""simple docstring"""



							_lowerCAmelCase  	=			[-1] * (current_row_idx + 1)
							# first and last elements of current row are equal to 1
							_lowerCAmelCase	,		_lowerCAmelCase  	=			1, 1
							for current_col_idx in range(1     ,  SCREAMING_SNAKE_CASE						):
														calculate_current_element(
														    SCREAMING_SNAKE_CASE     ,  SCREAMING_SNAKE_CASE     ,  SCREAMING_SNAKE_CASE     ,  SCREAMING_SNAKE_CASE						)
							return current_row






def 	__snake_case  (    SCREAMING_SNAKE_CASE:					list[list[int]]     ,  SCREAMING_SNAKE_CASE:					list[int]     ,  SCREAMING_SNAKE_CASE:					int     ,  SCREAMING_SNAKE_CASE:					int     ,  ):






							"""simple docstring"""



							_lowerCAmelCase  	=			triangle[current_row_idx - 1][current_col_idx - 1]
							_lowerCAmelCase  	=			triangle[current_row_idx - 1][current_col_idx]
							_lowerCAmelCase  	=			above_to_left_elt + above_to_right_elt






def 	__snake_case  (    SCREAMING_SNAKE_CASE:					int						):






							"""simple docstring"""



							if not isinstance(SCREAMING_SNAKE_CASE     ,  SCREAMING_SNAKE_CASE						):
														raise TypeError('The input value of \'num_rows\' should be \'int\''						)

							if num_rows == 0:
														return []
							elif num_rows < 0:
														raise ValueError(
														    'The input value of \'num_rows\' should be greater than or equal to 0'						)

							_lowerCAmelCase  	=			[[1]]

							for row_index in range(1     ,  SCREAMING_SNAKE_CASE						):
														_lowerCAmelCase  	=			[0] + result[-1] + [0]
														_lowerCAmelCase  	=			row_index + 1
														# Calculate the number of distinct elements in a row
														_lowerCAmelCase  	=			sum(divmod(SCREAMING_SNAKE_CASE     ,  2						)						)
														_lowerCAmelCase  	=			[
														    temp_row[i - 1] + temp_row[i] for i in range(1     ,  distinct_elements + 1						)
														]
														_lowerCAmelCase  	=			row_first_half[: (row_index + 1) // 2]
														row_second_half.reverse()
														_lowerCAmelCase  	=			row_first_half + row_second_half
														result.append(SCREAMING_SNAKE_CASE						)

							return result






def 	__snake_case  (    ):






							"""simple docstring"""



							from collections.abc import Callable
							from timeit import timeit

							def benchmark_a_function(SCREAMING_SNAKE_CASE:					Callable     ,  SCREAMING_SNAKE_CASE:					int						) -> None:
														_lowerCAmelCase  	=			f"""{func.__name__}({value})"""
														_lowerCAmelCase  	=			timeit(f"""__main__.{call}"""     ,  setup='import __main__'						)
														# print(f"{call:38} = {func(value)} -- {timing:.4f} seconds")
														print(f"""{call:38} -- {timing:.4f} seconds"""						)

							for value in range(15						):  # (1, 7, 14):
														for func in (generate_pascal_triangle, generate_pascal_triangle_optimized):
																					benchmark_a_function(SCREAMING_SNAKE_CASE     ,  SCREAMING_SNAKE_CASE						)
														print()


if __name__ == "__main__":
	import doctest

	doctest.testmod()
	benchmark()






