


'''simple docstring'''







import argparse
import json
import os
from collections import OrderedDict

import numpy as np
import tensorflow as tf
import torch






def       lowercase					(_A       ):







       """simple docstring"""







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


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





'''simple docstring'''







import os
import shutil
import tempfile
from unittest import TestCase
from unittest.mock import patch

import numpy as np
from datasets import Dataset

from transformers.models.realm.configuration_realm import RealmConfig
from transformers.models.realm.retrieval_realm import _REALM_BLOCK_RECORDS_FILENAME, RealmRetriever
from transformers.models.realm.tokenization_realm import VOCAB_FILES_NAMES, RealmTokenizer
class 						UpperCamelCase__       (			SCREAMING_SNAKE_CASE_						):



     """simple docstring"""






     def a						(			self ):

            '''simple docstring'''

            _lowerCAmelCase     :				Dict       =							tempfile.mkdtemp()
            _lowerCAmelCase     :				List[str]       =							5

            # Realm tok
            _lowerCAmelCase     :				str       =							[
                '[UNK]',
                '[CLS]',
                '[SEP]',
                '[PAD]',
                '[MASK]',
                'test',
                'question',
                'this',
                'is',
                'the',
                'first',
                'second',
                'third',
                'fourth',
                'fifth',
                'record',
                'want',
                '##want',
                '##ed',
                'wa',
                'un',
                'runn',
                '##ing',
                ',',
                'low',
                'lowest',
            ]
            _lowerCAmelCase     :				Union[str, Any]       =							os.path.join(self.tmpdirname   ,						'realm_tokenizer' )
            os.makedirs(snake_case__   ,						exist_ok=snake_case__ )
            _lowerCAmelCase     :				Dict       =							os.path.join(snake_case__   ,						VOCAB_FILES_NAMES['vocab_file'] )
            with open(self.vocab_file   ,						'w'   ,						encoding='utf-8' ) as vocab_writer:
                   vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) )

            _lowerCAmelCase     :				List[str]       =							os.path.join(self.tmpdirname   ,						'realm_block_records' )
            os.makedirs(snake_case__   ,						exist_ok=snake_case__ )







     def a						(			self ):

            '''simple docstring'''

            return RealmTokenizer.from_pretrained(os.path.join(self.tmpdirname   ,						'realm_tokenizer' ) )







     def a						(			self ):

            '''simple docstring'''

            shutil.rmtree(self.tmpdirname )







     def a						(			self ):

            '''simple docstring'''

            _lowerCAmelCase     :				Dict       =							RealmConfig(num_block_records=self.num_block_records )
            return config







     def a						(			self ):

            '''simple docstring'''

            _lowerCAmelCase     :				List[Any]       =							Dataset.from_dict(
                {
                    'id': ['0', '1'],
                    'question': ['foo', 'bar'],
                    'answers': [['Foo', 'Bar'], ['Bar']],
                } )
            return dataset







     def a						(			self ):

            '''simple docstring'''

            _lowerCAmelCase     :				str       =							np.array(
                [
                    b'This is the first record',
                    b'This is the second record',
                    b'This is the third record',
                    b'This is the fourth record',
                    b'This is the fifth record',
                    b'This is a longer longer longer record',
                ]   ,						dtype=snake_case__   ,						)
            return block_records







     def a						(			self ):

            '''simple docstring'''

            _lowerCAmelCase     :				Tuple       =							RealmRetriever(
                block_records=self.get_dummy_block_records()   ,						tokenizer=self.get_tokenizer()   ,						)
            return retriever







     def a						(			self ):

            '''simple docstring'''

            _lowerCAmelCase     :				Optional[int]       =							self.get_config()
            _lowerCAmelCase     :				List[Any]       =							self.get_dummy_retriever()
            _lowerCAmelCase     :				Any       =							retriever.tokenizer

            _lowerCAmelCase     :				Tuple       =							np.array([0, 3]   ,						dtype='long' )
            _lowerCAmelCase     :				Dict       =							tokenizer(['Test question'] ).input_ids
            _lowerCAmelCase     :				int       =							tokenizer(
                ['the fourth']   ,						add_special_tokens=snake_case__   ,						return_token_type_ids=snake_case__   ,						return_attention_mask=snake_case__   ,						).input_ids
            _lowerCAmelCase     :				Tuple       =							config.reader_seq_len

            _lowerCAmelCase      ,  _lowerCAmelCase      ,  _lowerCAmelCase      ,  _lowerCAmelCase     :				Union[str, Any]       =							retriever(
                snake_case__   ,						snake_case__   ,						answer_ids=snake_case__   ,						max_length=snake_case__   ,						return_tensors='np' )

            self.assertEqual(len(snake_case__ )   ,						2 )
            self.assertEqual(len(snake_case__ )   ,						2 )
            self.assertEqual(len(snake_case__ )   ,						2 )
            self.assertEqual(concat_inputs.input_ids.shape   ,						(2, 10) )
            self.assertEqual(concat_inputs.attention_mask.shape   ,						(2, 10) )
            self.assertEqual(concat_inputs.token_type_ids.shape   ,						(2, 10) )
            self.assertEqual(concat_inputs.special_tokens_mask.shape   ,						(2, 10) )
            self.assertEqual(
                tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[0] )   ,						['[CLS]', 'test', 'question', '[SEP]', 'this', 'is', 'the', 'first', 'record', '[SEP]']   ,						)
            self.assertEqual(
                tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[1] )   ,						['[CLS]', 'test', 'question', '[SEP]', 'this', 'is', 'the', 'fourth', 'record', '[SEP]']   ,						)







     def a						(			self ):

            '''simple docstring'''

            _lowerCAmelCase     :				int       =							self.get_config()
            _lowerCAmelCase     :				int       =							self.get_dummy_retriever()
            _lowerCAmelCase     :				List[str]       =							retriever.tokenizer

            _lowerCAmelCase     :				List[Any]       =							np.array([0, 3, 5]   ,						dtype='long' )
            _lowerCAmelCase     :				str       =							tokenizer(['Test question'] ).input_ids
            _lowerCAmelCase     :				Union[str, Any]       =							tokenizer(
                ['the fourth', 'longer longer']   ,						add_special_tokens=snake_case__   ,						return_token_type_ids=snake_case__   ,						return_attention_mask=snake_case__   ,						).input_ids
            _lowerCAmelCase     :				Optional[int]       =							config.reader_seq_len

            _lowerCAmelCase      ,  _lowerCAmelCase      ,  _lowerCAmelCase      ,  _lowerCAmelCase     :				List[str]       =							retriever(
                snake_case__   ,						snake_case__   ,						answer_ids=snake_case__   ,						max_length=snake_case__   ,						return_tensors='np' )

            self.assertEqual([False, True, True]   ,						snake_case__ )
            self.assertEqual([[-1, -1, -1], [6, -1, -1], [6, 7, 8]]   ,						snake_case__ )
            self.assertEqual([[-1, -1, -1], [7, -1, -1], [7, 8, 9]]   ,						snake_case__ )







     def a						(			self ):

            '''simple docstring'''

            _lowerCAmelCase     :				List[str]       =							self.get_dummy_retriever()
            retriever.save_pretrained(os.path.join(self.tmpdirname   ,						'realm_block_records' ) )

            # Test local path
            _lowerCAmelCase     :				Union[str, Any]       =							retriever.from_pretrained(os.path.join(self.tmpdirname   ,						'realm_block_records' ) )
            self.assertEqual(retriever.block_records[0]   ,						b'This is the first record' )

            # Test mocked remote path
            with patch('transformers.models.realm.retrieval_realm.hf_hub_download' ) as mock_hf_hub_download:
                   _lowerCAmelCase     :				Any       =							os.path.join(
                       os.path.join(self.tmpdirname   ,						'realm_block_records' )   ,						_REALM_BLOCK_RECORDS_FILENAME )
                   _lowerCAmelCase     :				str       =							RealmRetriever.from_pretrained('google/realm-cc-news-pretrained-openqa' )

            self.assertEqual(retriever.block_records[0]   ,						b'This is the first record' )

