


import argparse
import json
import os
from collections import OrderedDict

import numpy as np
import tensorflow as tf
import torch
def 				UpperCamelCase__					(  SCREAMING_SNAKE_CASE__						):
 __lowerCamelCase		:							str		 =						os.path.join(args.tf_model_dir      ,	'parameters.json'						)
 __lowerCamelCase		:							List[Any]		 =						json.loads(open(SCREAMING_SNAKE_CASE__						).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'						):
  __lowerCamelCase		:							Optional[int]		 =						args.output + '.pt'
 __lowerCamelCase		:							List[Any]		 =						OrderedDict()
 with tf.device('/CPU:0'						):
  __lowerCamelCase		:							Optional[Any]		 =						tf.train.load_checkpoint(args.tf_model_dir						)
  __lowerCamelCase		:							Optional[int]		 =						reader.get_variable_to_shape_map()
  for key_name in shapes.keys():
   __lowerCamelCase		:							Tuple		 =						reader.get_tensor(SCREAMING_SNAKE_CASE__						).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'						):
     __lowerCamelCase		:							List[str]		 =						int(key_name[9]						)
    elif key_name.startswith('pasts/out'						):
     __lowerCamelCase		:							Any		 =						8
    __lowerCamelCase		:							Tuple		 =						'model.sqout.%d.weight' % (player * 2)  # enter to nn.Sequencial with Tanh, so 2 at a time
    __lowerCamelCase		:							Optional[int]		 =						vnp.transpose([1, 0]						).copy()  # Mesh-Tensorflow is a diagonal matrix
    __lowerCamelCase		:							Union[str, Any]		 =						torch.tensor(SCREAMING_SNAKE_CASE__						)
   elif key_name.startswith('model/moe'						):
    __lowerCamelCase		:							Any		 =						int(key_name[9:].split('/'						)[0]						)
    if key_name.endswith('/switch_gating/kernel'						):
     __lowerCamelCase		:							List[Any]		 =						'model.blocks.%d.feed_forward.mlp.router.classifier.weight' % player
     __lowerCamelCase		:							List[Any]		 =						vnp.transpose([1, 0]						).copy()  # Mesh-Tensorflow is a diagonal matrix
     __lowerCamelCase		:							Any		 =						torch.tensor(SCREAMING_SNAKE_CASE__						)
    elif key_name.endswith('/softmlp/kernel'						):
     __lowerCamelCase		:							int		 =						'model.blocks.%d.feed_forward.soft_bypass_mlp.weight' % player
     __lowerCamelCase		:							Any		 =						vnp.transpose([1, 0]						).copy()  # Mesh-Tensorflow is a diagonal matrix
     __lowerCamelCase		:							Tuple		 =						torch.tensor(SCREAMING_SNAKE_CASE__						)
    elif key_name.endswith('/wo/kernel'						) or key_name.endswith('/wi/kernel'						):
     __lowerCamelCase		:							Any		 =						key_name[-9:-7]
     for i in range(16						):
      __lowerCamelCase		:							Optional[Any]		 =						'model.blocks.%d.feed_forward.mlp.experts.expert_%d.%s.weight' % (player, i, nlayer)
      __lowerCamelCase		:							int		 =						(
          vnp[i].transpose([1, 0]						).copy()
      )  # In Mesh-Tensorflow, it is one array, so it is divided
      __lowerCamelCase		:							List[Any]		 =						torch.tensor(SCREAMING_SNAKE_CASE__						)
   elif key_name.startswith('model/mlp'						):
    __lowerCamelCase		:							Optional[Any]		 =						int(key_name[9:].split('/'						)[0]						)
    if key_name.endswith('/p1/kernel'						):
     __lowerCamelCase		:							Optional[Any]		 =						'model.blocks.%d.feed_forward.mlp.wi.weight' % player
     __lowerCamelCase		:							Optional[Any]		 =						vnp.transpose([1, 0]						).copy()  # Mesh-Tensorflow is a diagonal matrix
     __lowerCamelCase		:							Optional[Any]		 =						torch.tensor(SCREAMING_SNAKE_CASE__						)
    elif key_name.endswith('/p1/bias'						):
     __lowerCamelCase		:							Any		 =						'model.blocks.%d.feed_forward.mlp.wi.bias' % player
     __lowerCamelCase		:							Optional[Any]		 =						vnp.copy()  # same because it is one dimensional
     __lowerCamelCase		:							int		 =						torch.tensor(SCREAMING_SNAKE_CASE__						)
    elif key_name.endswith('/p2/kernel'						):
     __lowerCamelCase		:							int		 =						'model.blocks.%d.feed_forward.mlp.wo.weight' % player
     __lowerCamelCase		:							Any		 =						vnp.transpose([1, 0]						).copy()  # Mesh-Tensorflow is a diagonal matrix
     __lowerCamelCase		:							Optional[Any]		 =						torch.tensor(SCREAMING_SNAKE_CASE__						)
    elif key_name.endswith('/p2/bias'						):
     __lowerCamelCase		:							Optional[Any]		 =						'model.blocks.%d.feed_forward.mlp.wo.bias' % player
     __lowerCamelCase		:							Any		 =						vnp.copy()  # same because it is one dimensional
     __lowerCamelCase		:							List[str]		 =						torch.tensor(SCREAMING_SNAKE_CASE__						)
   elif key_name.startswith('model/ln'						):
    __lowerCamelCase		:							List[Any]		 =						int(key_name[8:].split('/'						)[0]						)
    if key_name.endswith('/b'						):
     __lowerCamelCase		:							Union[str, Any]		 =						'model.blocks.%d.feed_forward.norm.bias' % player
     __lowerCamelCase		:							List[str]		 =						vnp.copy()  # same because it is one dimensional
     __lowerCamelCase		:							Tuple		 =						torch.tensor(SCREAMING_SNAKE_CASE__						)
    elif key_name.endswith('/g'						):
     __lowerCamelCase		:							str		 =						'model.blocks.%d.feed_forward.norm.weight' % player
     __lowerCamelCase		:							Any		 =						vnp.copy()  # same because it is one dimensional
     __lowerCamelCase		:							List[str]		 =						torch.tensor(SCREAMING_SNAKE_CASE__						)
   elif key_name.startswith('model/att'						):
    __lowerCamelCase		:							List[Any]		 =						int(key_name[9:].split('/'						)[0]						)
    if key_name.endswith('/qkv/kernel'						):
     __lowerCamelCase		:							Tuple		 =						vnp.copy()  # Compute same dimension as Mesh-tensorflow using einsum
     __lowerCamelCase		:							Optional[Any]		 =						state[:, 0, :, :]
     __lowerCamelCase		:							Any		 =						state[:, 1, :, :]
     __lowerCamelCase		:							str		 =						state[:, 2, :, :]
     __lowerCamelCase		:							str		 =						(
         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
     __lowerCamelCase		:							Tuple		 =						(
         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
     __lowerCamelCase		:							List[str]		 =						(
         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
     __lowerCamelCase		:							Optional[int]		 =						'model.blocks.%d.self_attn.self_attn.q_proj.weight' % player
     __lowerCamelCase		:							List[Any]		 =						torch.tensor(SCREAMING_SNAKE_CASE__						)
     __lowerCamelCase		:							Optional[int]		 =						'model.blocks.%d.self_attn.self_attn.k_proj.weight' % player
     __lowerCamelCase		:							str		 =						torch.tensor(SCREAMING_SNAKE_CASE__						)
     __lowerCamelCase		:							List[str]		 =						'model.blocks.%d.self_attn.self_attn.v_proj.weight' % player
     __lowerCamelCase		:							str		 =						torch.tensor(SCREAMING_SNAKE_CASE__						)
    elif key_name.endswith('/o/kernel'						):
     __lowerCamelCase		:							List[str]		 =						'model.blocks.%d.self_attn.self_attn.out_proj.weight' % player
     __lowerCamelCase		:							List[str]		 =						(
         vnp.reshape([vnp.shape[0] * vnp.shape[1], vnp.shape[2]]						).transpose([1, 0]						).copy()
     )  # Mesh-Tensorflow is a diagonal matrix
     __lowerCamelCase		:							int		 =						torch.tensor(SCREAMING_SNAKE_CASE__						)
   elif key_name.startswith('model/an'						):
    __lowerCamelCase		:							int		 =						int(key_name[8:].split('/'						)[0]						)
    if key_name.endswith('/b'						):
     __lowerCamelCase		:							List[Any]		 =						'model.blocks.%d.self_attn.norm.bias' % player
     __lowerCamelCase		:							str		 =						vnp.copy()  # same because it is one dimensional
     __lowerCamelCase		:							Dict		 =						torch.tensor(SCREAMING_SNAKE_CASE__						)
    elif key_name.endswith('/g'						):
     __lowerCamelCase		:							List[str]		 =						'model.blocks.%d.self_attn.norm.weight' % player
     __lowerCamelCase		:							Any		 =						vnp.copy()  # same because it is one dimensional
     __lowerCamelCase		:							str		 =						torch.tensor(SCREAMING_SNAKE_CASE__						)
   elif (
       key_name.startswith('model/wte'						)
       or key_name.startswith('model/wpe'						)
       or key_name.startswith('model/ete'						)
   ):
    __lowerCamelCase		:							Optional[Any]		 =						{'wte': 'embed_tokens', 'wpe': 'position_embeddings', 'ete': 'extra_position_embeddings'}[
        key_name[-3:]
    ]
    __lowerCamelCase		:							Optional[int]		 =						'model.%s.weight' % nlayer
    __lowerCamelCase		:							List[Any]		 =						vnp.copy()  # same in embedded
    __lowerCamelCase		:							Tuple		 =						torch.tensor(SCREAMING_SNAKE_CASE__						)
    if key_name.startswith('model/wte'						):
     __lowerCamelCase		:							Optional[int]		 =						'lm_head.weight'
     __lowerCamelCase		:							Tuple		 =						vnp.copy()  # same in embedded
     __lowerCamelCase		:							str		 =						torch.tensor(SCREAMING_SNAKE_CASE__						)
   elif key_name.startswith('model/wob'						):
    __lowerCamelCase		:							Optional[Any]		 =						'final_logits_bias'
    __lowerCamelCase		:							List[str]		 =						vnp.copy()  # same in embedded
    __lowerCamelCase		:							Dict		 =						state.reshape((1, -1)						)
    __lowerCamelCase		:							Dict		 =						torch.tensor(SCREAMING_SNAKE_CASE__						)
   elif key_name == "model/dense/kernel":
    __lowerCamelCase		:							str		 =						'model.last_project.weight'
    __lowerCamelCase		:							str		 =						vnp.transpose([1, 0]						).copy()  # Mesh-Tensorflow is a diagonal matrix
    __lowerCamelCase		:							Union[str, Any]		 =						torch.tensor(SCREAMING_SNAKE_CASE__						)
   elif key_name == "model/dense_1/bias":
    __lowerCamelCase		:							List[Any]		 =						'model.last_project.bias'
    __lowerCamelCase		:							Optional[Any]		 =						vnp.copy()  # same because it is one dimensional
    __lowerCamelCase		:							Any		 =						torch.tensor(SCREAMING_SNAKE_CASE__						)
 torch.save(SCREAMING_SNAKE_CASE__      ,	args.output						)


if __name__ == "__main__":
       lowercase_	   =     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')
       lowercase_	   =     parser.parse_args()
       convert_tf_gptsan_to_pt(args)





from maths.is_square_free import is_square_free
from maths.prime_factors import prime_factors
def 				UpperCamelCase__					(  SCREAMING_SNAKE_CASE__						):
 __lowerCamelCase		:							Dict		 =						prime_factors(SCREAMING_SNAKE_CASE__						)
 if is_square_free(SCREAMING_SNAKE_CASE__						):
  return -1 if len(SCREAMING_SNAKE_CASE__						) % 2 else 1
 return 0


if __name__ == "__main__":
       import doctest

       doctest.testmod()

