




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       UpperCAmelCase__  (     lowerCamelCase,			lowerCamelCase,			lowerCamelCase,			lowerCamelCase="attention"   ):
  lowercase    :Union[str, Any]      	=						params[F"{prefix}/layers_{i}/{layer_name}/key/kernel"]
  lowercase    :List[Any]      	=						params[F"{prefix}/layers_{i}/{layer_name}/out/kernel"]
  lowercase    :List[Any]      	=						params[F"{prefix}/layers_{i}/{layer_name}/query/kernel"]
  lowercase    :List[str]      	=						params[F"{prefix}/layers_{i}/{layer_name}/value/kernel"]
  return k, o, q, v



def       UpperCAmelCase__  (     lowerCamelCase,			lowerCamelCase,			lowerCamelCase,			lowerCamelCase=False   ):
  if split_mlp_wi:
    lowercase    :int      	=						params[F"{prefix}/layers_{i}/mlp/wi_0/kernel"]
    lowercase    :Dict      	=						params[F"{prefix}/layers_{i}/mlp/wi_1/kernel"]
    lowercase    :Optional[Any]      	=						(wi_a, wi_a)
  else:
    lowercase    :Union[str, Any]      	=						params[F"{prefix}/layers_{i}/mlp/wi/kernel"]

  lowercase    :str      	=						params[F"{prefix}/layers_{i}/mlp/wo/kernel"]
  return wi, wo



def       UpperCAmelCase__  (     lowerCamelCase,			lowerCamelCase,			lowerCamelCase,			lowerCamelCase   ):
  return params[F"{prefix}/layers_{i}/{layer_name}/scale"]



def       UpperCAmelCase__  (     lowerCamelCase,			*, lowerCamelCase,			lowerCamelCase   ):
  lowercase    :Tuple      	=						traverse_util.flatten_dict(variables["target"]   )
  lowercase    :List[str]      	=						{"/".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
  lowercase    :Dict      	=						"encoder/layers_0/mlp/wi_0/kernel" in old
  print("Split MLP:",			lowerCamelCase   )

  lowercase    :Optional[Any]      	=						collections.OrderedDict()

  # Shared embeddings.
  lowercase    :List[str]      	=						old["token_embedder/embedding"]

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

    # Block i, layer 1 (MLP).
    lowercase    :Any      	=						tax_layer_norm_lookup(lowerCamelCase,			lowerCamelCase,			"encoder",			"pre_mlp_layer_norm"   )
    lowercase	,    lowercase    :List[str]      	=						tax_mlp_lookup(lowerCamelCase,			lowerCamelCase,			"encoder",			lowerCamelCase   )
    lowercase    :Tuple      	=						layer_norm
    if split_mlp_wi:
      lowercase    :Union[str, Any]      	=						wi[0].T
      lowercase    :Optional[Any]      	=						wi[1].T
    else:
      lowercase    :Tuple      	=						wi.T
    lowercase    :Union[str, Any]      	=						wo.T

  lowercase    :List[Any]      	=						old[
      "encoder/relpos_bias/rel_embedding"
  ].T
  lowercase    :str      	=						old["encoder/encoder_norm/scale"]

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

      # Block i, layer 1 (Cross Attention).
      lowercase    :Optional[Any]      	=						tax_layer_norm_lookup(lowerCamelCase,			lowerCamelCase,			"decoder",			"pre_cross_attention_layer_norm"   )
      lowercase	,    lowercase	,    lowercase	,    lowercase    :Optional[Any]      	=						tax_attention_lookup(lowerCamelCase,			lowerCamelCase,			"decoder",			"encoder_decoder_attention"   )
      lowercase    :str      	=						layer_norm
      lowercase    :Optional[Any]      	=						k.T
      lowercase    :List[Any]      	=						o.T
      lowercase    :str      	=						q.T
      lowercase    :List[Any]      	=						v.T

      # Block i, layer 2 (MLP).
      lowercase    :Optional[Any]      	=						tax_layer_norm_lookup(lowerCamelCase,			lowerCamelCase,			"decoder",			"pre_mlp_layer_norm"   )
      lowercase	,    lowercase    :int      	=						tax_mlp_lookup(lowerCamelCase,			lowerCamelCase,			"decoder",			lowerCamelCase   )
      lowercase    :int      	=						layer_norm
      if split_mlp_wi:
        lowercase    :Optional[int]      	=						wi[0].T
        lowercase    :List[str]      	=						wi[1].T
      else:
        lowercase    :int      	=						wi.T
      lowercase    :Optional[Any]      	=						wo.T

    lowercase    :int      	=						old["decoder/decoder_norm/scale"]
    lowercase    :str      	=						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:
      lowercase    :List[Any]      	=						old["decoder/logits_dense/kernel"].T

  return new



def       UpperCAmelCase__  (     lowerCamelCase,			lowerCamelCase   ):
  lowercase    :Optional[int]      	=						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:
    lowercase    :Optional[Any]      	=						state_dict["shared.weight"]

  if not is_encoder_only:
    if "decoder.embed_tokens.weight" not in state_dict:
      lowercase    :Tuple      	=						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."   )
      lowercase    :Optional[Any]      	=						state_dict["shared.weight"]

  return state_dict



def       UpperCAmelCase__  (     lowerCamelCase,			lowerCamelCase,			lowerCamelCase,			lowerCamelCase   ):
  lowercase    :Tuple      	=						checkpoints.load_tax_checkpoint(lowerCamelCase   )
  lowercase    :Optional[int]      	=						convert_tax_to_pytorch(lowerCamelCase,			num_layers=config.num_layers,			is_encoder_only=lowerCamelCase   )
  lowercase    :str      	=						make_state_dict(lowerCamelCase,			lowerCamelCase   )
  model.load_state_dict(lowerCamelCase,			strict=lowerCamelCase   )



def       UpperCAmelCase__  (     lowerCamelCase,			lowerCamelCase,			lowerCamelCase,			lowerCamelCase = False   ):
  lowercase    :Tuple      	=						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:
    lowercase    :str      	=						TaEncoderModel(lowerCamelCase   )
  else:
    lowercase    :List[Any]      	=						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__":
     _UpperCAmelCase	:						str			=     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
     )
     _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
     )









def       UpperCAmelCase__  (     lowerCamelCase,			lowerCamelCase   ):
  if discount_rate < 0:
    raise ValueError("Discount rate cannot be negative"   )
  if not cash_flows:
    raise ValueError("Cash flows list cannot be empty"   )
  lowercase    :Dict      	=						sum(
      cash_flow / ((1 + discount_rate) ** i) for i, cash_flow in enumerate(lowerCamelCase   )   )
  return round(lowerCamelCase,			ndigits=2   )


if __name__ == "__main__":
     import doctest

     doctest.testmod()



