


'''simple docstring'''







import tempfile
import unittest

from transformers import TaConfig, is_torch_available
from transformers.testing_utils import (
    require_sentencepiece,
    require_tokenizers,
    require_torch,
    slow,
    torch_device,
)

from ...generation.test_utils import GenerationTesterMixin
from ...test_modeling_common import ModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
   import torch

   from transformers import AutoTokenizer, UMTaForConditionalGeneration, UMTaForQuestionAnswering, UMTaModel







class A__       :






      def __init__( self			:Tuple     ,						SCREAMING_SNAKE_CASE			:Union[str, Any]     ,						SCREAMING_SNAKE_CASE			:List[str]=9_9     ,						SCREAMING_SNAKE_CASE			:List[str]=1_3     ,						SCREAMING_SNAKE_CASE			:Optional[int]=7     ,						SCREAMING_SNAKE_CASE			:Tuple=9     ,						SCREAMING_SNAKE_CASE			:Any=True     ,						SCREAMING_SNAKE_CASE			:str=True     ,						SCREAMING_SNAKE_CASE			:Optional[Any]=False     ,						SCREAMING_SNAKE_CASE			:str=3_2     ,						SCREAMING_SNAKE_CASE			:List[str]=5     ,						SCREAMING_SNAKE_CASE			:Union[str, Any]=4     ,						SCREAMING_SNAKE_CASE			:Tuple=3_7     ,						SCREAMING_SNAKE_CASE			:Optional[int]=8     ,						SCREAMING_SNAKE_CASE			:str=0.1     ,						SCREAMING_SNAKE_CASE			:Tuple=0.002     ,						SCREAMING_SNAKE_CASE			:Optional[Any]=1     ,						SCREAMING_SNAKE_CASE			:Optional[int]=0     ,						SCREAMING_SNAKE_CASE			:Tuple=0     ,						SCREAMING_SNAKE_CASE			:str=None     ,						SCREAMING_SNAKE_CASE			:Optional[Any]=None     ,						)       ->					int:




             '''simple docstring'''
             _a    : int     					=parent
             _a    : Tuple     					=batch_size
             _a    : List[Any]     					=encoder_seq_length
             _a    : List[str]     					=decoder_seq_length
             # For common tests
             _a    : str     					=self.decoder_seq_length
             _a    : Optional[int]     					=is_training
             _a    : List[str]     					=use_attention_mask
             _a    : Union[str, Any]     					=use_labels
             _a    : List[str]     					=vocab_size
             _a    : Union[str, Any]     					=hidden_size
             _a    : int     					=num_hidden_layers
             _a    : Dict     					=num_attention_heads
             _a    : List[str]     					=d_ff
             _a    : Tuple     					=relative_attention_num_buckets
             _a    : List[Any]     					=dropout_rate
             _a    : List[str]     					=initializer_factor
             _a    : str     					=eos_token_id
             _a    : Union[str, Any]     					=pad_token_id
             _a    : Any     					=decoder_start_token_id
             _a    : Union[str, Any]     					=None
             _a    : int     					=decoder_layers






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




             '''simple docstring'''
             return TaConfig.from_pretrained("""google/umt5-base"""	)






      def __UpperCAmelCase       ( self			:List[Any]     ,						SCREAMING_SNAKE_CASE			:Any     ,						SCREAMING_SNAKE_CASE			:Any     ,						SCREAMING_SNAKE_CASE			:Tuple     ,						SCREAMING_SNAKE_CASE			:Optional[int]=None     ,						SCREAMING_SNAKE_CASE			:Optional[Any]=None     ,						SCREAMING_SNAKE_CASE			:Any=None     ,						SCREAMING_SNAKE_CASE			:int=None     ,						SCREAMING_SNAKE_CASE			:List[str]=None     ,						)       ->					List[Any]:




             '''simple docstring'''
             if attention_mask is None:
                    _a    : str     					=input_ids.ne(config.pad_token_id	)
             if decoder_attention_mask is None:
                    _a    : str     					=decoder_input_ids.ne(config.pad_token_id	)
             if head_mask is None:
                    _a    : Optional[int]     					=torch.ones(config.num_hidden_layers     ,						config.num_attention_heads     ,						device=SCREAMING_SNAKE_CASE	)
             if decoder_head_mask is None:
                    _a    : int     					=torch.ones(config.num_decoder_layers     ,						config.num_attention_heads     ,						device=SCREAMING_SNAKE_CASE	)
             if cross_attn_head_mask is None:
                    _a    : Tuple     					=torch.ones(
                        config.num_decoder_layers     ,						config.num_attention_heads     ,						device=SCREAMING_SNAKE_CASE	)
             return {
                 "input_ids": input_ids,
                 "decoder_input_ids": decoder_input_ids,
                 "attention_mask": attention_mask,
                 "decoder_attention_mask": decoder_attention_mask,
                 "head_mask": head_mask,
                 "decoder_head_mask": decoder_head_mask,
                 "cross_attn_head_mask": cross_attn_head_mask,
             }






      def __UpperCAmelCase       ( self			:Union[str, Any]	)       ->					str:




             '''simple docstring'''
             _a    : List[str]     					=ids_tensor([self.batch_size, self.encoder_seq_length]     ,						self.vocab_size	)
             _a    : Optional[int]     					=ids_tensor([self.batch_size, self.decoder_seq_length]     ,						self.vocab_size	)

             # we need to clamp the input ids here to avoid having pad token in between
             # this is because for NllbMoe the position_ids are prepared such that
             # all pad tokens have pos id = 2 and rest are between 2..seq_length
             # and the seq_length here is seq_length - num_pad_tokens
             # but when using past, there is no way of knowing if the past input ids had
             # pad tokens in them, which results in incorrect seq_lenth and which in turn results in
             # position_ids being off by num_pad_tokens in past input
             _a    : Optional[int]     					=input_ids.clamp(self.pad_token_id + 1	)
             _a    : List[str]     					=decoder_input_ids.clamp(self.pad_token_id + 1	)

             _a    : List[Any]     					=self.get_config()
             _a    : int     					=config.num_attention_heads
             _a    : Union[str, Any]     					=self.prepare_inputs_dict(SCREAMING_SNAKE_CASE     ,						SCREAMING_SNAKE_CASE     ,						SCREAMING_SNAKE_CASE	)
             return config, input_dict






      def __UpperCAmelCase       ( self			:int	)       ->					int:




             '''simple docstring'''
             _a					,    _a    : Dict     					=self.prepare_config_and_inputs()
             return config, inputs_dict






      def __UpperCAmelCase       ( self			:List[Any]	)       ->					str:




             '''simple docstring'''
             return TaConfig(
                 vocab_size=1_6_6     ,						d_model=self.hidden_size     ,						d_ff=self.d_ff     ,						d_kv=self.hidden_size // self.num_attention_heads     ,						num_layers=self.num_hidden_layers     ,						num_decoder_layers=self.decoder_layers     ,						num_heads=self.num_attention_heads     ,						relative_attention_num_buckets=self.relative_attention_num_buckets     ,						dropout_rate=self.dropout_rate     ,						initializer_factor=self.initializer_factor     ,						eos_token_id=self.eos_token_id     ,						bos_token_id=self.pad_token_id     ,						pad_token_id=self.pad_token_id     ,						decoder_start_token_id=self.decoder_start_token_id     ,						)






      def __UpperCAmelCase       ( self			:Dict	)       ->					Dict:




             '''simple docstring'''
             return TaConfig(
                 vocab_size=self.vocab_size     ,						d_model=self.hidden_size     ,						d_ff=self.d_ff     ,						d_kv=self.hidden_size // self.num_attention_heads     ,						num_layers=self.num_hidden_layers     ,						num_decoder_layers=self.decoder_layers     ,						num_heads=self.num_attention_heads     ,						relative_attention_num_buckets=self.relative_attention_num_buckets     ,						dropout_rate=self.dropout_rate     ,						initializer_factor=self.initializer_factor     ,						eos_token_id=self.eos_token_id     ,						bos_token_id=self.pad_token_id     ,						pad_token_id=self.pad_token_id     ,						decoder_start_token_id=self.decoder_start_token_id     ,						)






      def __UpperCAmelCase       ( self			:Optional[int]     ,						SCREAMING_SNAKE_CASE			:Optional[int]     ,						SCREAMING_SNAKE_CASE			:Any     ,						SCREAMING_SNAKE_CASE			:Tuple     ,						SCREAMING_SNAKE_CASE			:Dict     ,						SCREAMING_SNAKE_CASE			:List[str]     ,						SCREAMING_SNAKE_CASE			:Tuple     ,						)       ->					Union[str, Any]:




             '''simple docstring'''
             _a    : Optional[Any]     					=UMTaModel(config=SCREAMING_SNAKE_CASE	)
             model.to(SCREAMING_SNAKE_CASE	)
             model.eval()
             _a    : Optional[int]     					=model(
                 input_ids=SCREAMING_SNAKE_CASE     ,						decoder_input_ids=SCREAMING_SNAKE_CASE     ,						attention_mask=SCREAMING_SNAKE_CASE     ,						decoder_attention_mask=SCREAMING_SNAKE_CASE     ,						)
             _a    : Optional[int]     					=model(input_ids=SCREAMING_SNAKE_CASE     ,						decoder_input_ids=SCREAMING_SNAKE_CASE	)
             _a    : Any     					=result.last_hidden_state
             _a    : List[Any]     					=result.past_key_values
             _a    : List[str]     					=result.encoder_last_hidden_state

             self.parent.assertEqual(encoder_output.size()     ,						(self.batch_size, self.encoder_seq_length, self.hidden_size)	)
             self.parent.assertEqual(decoder_output.size()     ,						(self.batch_size, self.decoder_seq_length, self.hidden_size)	)
             # There should be `num_layers` key value embeddings stored in decoder_past
             self.parent.assertEqual(len(SCREAMING_SNAKE_CASE	)     ,						config.num_layers	)
             # There should be a self attn key, a self attn value, a cross attn key and a cross attn value stored in each decoder_past tuple
             self.parent.assertEqual(len(decoder_past[0]	)     ,						4	)






      def __UpperCAmelCase       ( self			:Dict     ,						SCREAMING_SNAKE_CASE			:Union[str, Any]     ,						SCREAMING_SNAKE_CASE			:Tuple     ,						SCREAMING_SNAKE_CASE			:Tuple     ,						SCREAMING_SNAKE_CASE			:List[str]     ,						SCREAMING_SNAKE_CASE			:List[Any]     ,						SCREAMING_SNAKE_CASE			:List[str]     ,						)       ->					List[str]:




             '''simple docstring'''
             _a    : Any     					=UMTaModel(config=SCREAMING_SNAKE_CASE	).get_decoder().to(SCREAMING_SNAKE_CASE	).eval()
             # first forward pass
             _a    : Tuple     					=model(SCREAMING_SNAKE_CASE     ,						use_cache=SCREAMING_SNAKE_CASE	)
             _a    : List[Any]     					=model(SCREAMING_SNAKE_CASE	)
             _a    : str     					=model(SCREAMING_SNAKE_CASE     ,						use_cache=SCREAMING_SNAKE_CASE	)

             self.parent.assertTrue(len(SCREAMING_SNAKE_CASE	) == len(SCREAMING_SNAKE_CASE	)	)
             self.parent.assertTrue(len(SCREAMING_SNAKE_CASE	) == len(SCREAMING_SNAKE_CASE	) + 1	)

             _a					,    _a    : List[Any]     					=outputs.to_tuple()

             # create hypothetical next token and extent to next_input_ids
             _a    : str     					=ids_tensor((self.batch_size, 1)     ,						config.vocab_size	)

             # append to next input_ids and
             _a    : Tuple     					=torch.cat([input_ids, next_tokens]     ,						dim=-1	)

             _a    : Optional[Any]     					=model(SCREAMING_SNAKE_CASE	)["""last_hidden_state"""]
             _a    : Optional[int]     					=model(SCREAMING_SNAKE_CASE     ,						past_key_values=SCREAMING_SNAKE_CASE	)["""last_hidden_state"""]

             # select random slice
             _a    : Union[str, Any]     					=ids_tensor((1,)     ,						output_from_past.shape[-1]	).item()
             _a    : Optional[int]     					=output_from_no_past[:, -1, random_slice_idx].detach()
             _a    : str     					=output_from_past[:, 0, random_slice_idx].detach()

             # test that outputs are equal for slice
             self.parent.assertTrue(torch.allclose(SCREAMING_SNAKE_CASE     ,						SCREAMING_SNAKE_CASE     ,						atol=1e-3	)	)






      def __UpperCAmelCase       ( self			:Dict     ,						SCREAMING_SNAKE_CASE			:Dict     ,						SCREAMING_SNAKE_CASE			:str     ,						)       ->					List[str]:




             '''simple docstring'''
             _a    : Dict     					=UMTaModel(config=SCREAMING_SNAKE_CASE	).to(SCREAMING_SNAKE_CASE	).half().eval()
             _a    : int     					=model(**SCREAMING_SNAKE_CASE	)["""last_hidden_state"""]
             self.parent.assertFalse(torch.isnan(SCREAMING_SNAKE_CASE	).any().item()	)







@require_torch
class A__       (						UpperCAmelCase__ ,     UpperCAmelCase__ ,     UpperCAmelCase__ ,     unittest.TestCase      ):
      __UpperCamelCase       :  Any	       =							(
          (UMTaModel, UMTaForConditionalGeneration, UMTaForQuestionAnswering) if is_torch_available() else ()
      )
      __UpperCamelCase       :  Optional[int]	       =							(UMTaForConditionalGeneration,) if is_torch_available() else ()
      __UpperCamelCase       :  Union[str, Any]	       =							(
          {
              "conversational": UMTaForConditionalGeneration,
              "feature-extraction": UMTaModel,
              "summarization": UMTaForConditionalGeneration,
              "text2text-generation": UMTaForConditionalGeneration,
              "translation": UMTaForConditionalGeneration,
              "question-answering": UMTaForQuestionAnswering,
          }
          if is_torch_available()
          else {}
      )
      __UpperCamelCase       :  Any	       =							True
      __UpperCamelCase       :  Union[str, Any]	       =							False
      __UpperCamelCase       :  int	       =							False
      __UpperCamelCase       :  int	       =							True
      __UpperCamelCase       :  str	       =							True
      # The small UMT5 model needs higher percentages for CPU/MP tests
      __UpperCamelCase       :  Optional[Any]	       =							[0.8, 0.9]






      def __UpperCAmelCase       ( self			:Optional[Any]	)       ->					List[Any]:




             '''simple docstring'''
             _a    : Tuple     					=UMTaModelTester(self	)






      @unittest.skip("""Test has a segmentation fault on torch 1.8.0"""	)
      def __UpperCAmelCase       ( self			:Dict	)       ->					Tuple:




             '''simple docstring'''
             _a    : List[str]     					=self.model_tester.prepare_config_and_inputs()
             _a    : Union[str, Any]     					=UMTaModel(config_and_inputs[0]	).to(SCREAMING_SNAKE_CASE	)
             with tempfile.TemporaryDirectory() as tmpdirname:
                    torch.onnx.export(
                        SCREAMING_SNAKE_CASE     ,						(config_and_inputs[1], config_and_inputs[3], config_and_inputs[2])     ,						f"{tmpdirname}/t5_test.onnx"     ,						export_params=SCREAMING_SNAKE_CASE     ,						opset_version=9     ,						input_names=["""input_ids""", """decoder_input_ids"""]     ,						)






      @unittest.skipIf(torch_device == """cpu"""     ,						"""Cant do half precision"""	)
      def __UpperCAmelCase       ( self			:Optional[int]	)       ->					Optional[int]:




             '''simple docstring'''
             _a    : Optional[int]     					=self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_model_fpaa_forward(*SCREAMING_SNAKE_CASE	)






      def __UpperCAmelCase       ( self			:List[Any]	)       ->					List[str]:




             '''simple docstring'''
             _a    : Any     					=["""encoder_attentions""", """decoder_attentions""", """cross_attentions"""]
             _a    : Any     					=self.model_tester.prepare_config_and_inputs()
             _a    : int     					=config_and_inputs[0]
             _a    : Tuple     					=UMTaForConditionalGeneration(SCREAMING_SNAKE_CASE	).eval()
             model.to(SCREAMING_SNAKE_CASE	)

             _a    : List[Any]     					={
                 """head_mask""": torch.zeros(config.num_layers     ,						config.num_heads     ,						device=SCREAMING_SNAKE_CASE	),
                 """decoder_head_mask""": torch.zeros(config.num_decoder_layers     ,						config.num_heads     ,						device=SCREAMING_SNAKE_CASE	),
                 """cross_attn_head_mask""": torch.zeros(config.num_decoder_layers     ,						config.num_heads     ,						device=SCREAMING_SNAKE_CASE	),
             }

             for attn_name, (name, mask) in zip(SCREAMING_SNAKE_CASE     ,						head_masking.items()	):
                    _a    : str     					={name: mask}
                    # Explicitly pass decoder_head_mask as it is required from T5 model when head_mask specified
                    if name == "head_mask":
                           _a    : Optional[Any]     					=torch.ones(
                               config.num_decoder_layers     ,						config.num_heads     ,						device=SCREAMING_SNAKE_CASE	)

                    _a    : Union[str, Any]     					=model.generate(
                        config_and_inputs[1]["""input_ids"""]     ,						num_beams=1     ,						max_length=3     ,						output_attentions=SCREAMING_SNAKE_CASE     ,						return_dict_in_generate=SCREAMING_SNAKE_CASE     ,						**SCREAMING_SNAKE_CASE     ,						)
                    # We check the state of decoder_attentions and cross_attentions just from the last step
                    _a    : int     					=out[attn_name] if attn_name == attention_names[0] else out[attn_name][-1]
                    self.assertEqual(sum([w.sum().item() for w in attn_weights]	)     ,						0.0	)






      @unittest.skip("""Does not work on the tiny model as we keep hitting edge cases."""	)
      def __UpperCAmelCase       ( self			:List[Any]	)       ->					Optional[int]:




             '''simple docstring'''
             pass







@require_torch
@require_sentencepiece
@require_tokenizers
class A__       (						unittest.TestCase      ):






      @slow
      @unittest.skip(
          """Unless we stop stripping left and right by default for all special tokens, the expected ids obtained here will not match the original ones. Wait for https://github.com/huggingface/transformers/pull/23909 to be merged"""	)
      def __UpperCAmelCase       ( self			:Tuple	)       ->					Dict:




             '''simple docstring'''
             _a    : Tuple     					=UMTaForConditionalGeneration.from_pretrained("""google/umt5-small"""     ,						return_dict=SCREAMING_SNAKE_CASE	).to(SCREAMING_SNAKE_CASE	)
             _a    : Dict     					=AutoTokenizer.from_pretrained("""google/umt5-small"""     ,						use_fast=SCREAMING_SNAKE_CASE     ,						legacy=SCREAMING_SNAKE_CASE	)
             _a    : Tuple     					=[
                 """Bonjour monsieur <extra_id_0> bien <extra_id_1>.""",
                 """No se como puedo <extra_id_0>.""",
                 """This is the reason why we <extra_id_0> them.""",
                 """The <extra_id_0> walks in <extra_id_1>, seats""",
                 """A <extra_id_0> walks into a bar and orders a <extra_id_1> with <extra_id_2> pinch of <extra_id_3>.""",
             ]
             _a    : int     					=tokenizer(SCREAMING_SNAKE_CASE     ,						return_tensors="""pt"""     ,						padding=SCREAMING_SNAKE_CASE	).input_ids
             # fmt: off
             _a    : Optional[int]     					=torch.tensor(
                 [
                     [ 3_8_5_3_0, 2_1_0_7_0_3, 2_5_6_2_9_9, 1_4_1_0, 2_5_6_2_9_8, 2_7_4, 1, 0,0, 0, 0, 0, 0, 0, 0, 0,0, 0],
                     [   8_2_6, 3_2_1, 6_7_1, 2_5_9_2_2, 2_5_6_2_9_9, 2_7_4, 1, 0,0, 0, 0, 0, 0, 0, 0, 0,0, 0],
                     [  1_4_6_0, 3_3_9, 3_1_2, 1_9_0_1_4, 1_0_6_2_0, 7_5_8, 2_5_6_2_9_9, 2_3_5_5,2_7_4, 1, 0, 0, 0, 0, 0, 0,0, 0],
                     [   5_1_7, 2_5_6_2_9_9, 1_4_8_6_9, 2_8_1, 3_0_1, 2_5_6_2_9_8, 2_7_5, 1_1_9_9_8_3,1, 0, 0, 0, 0, 0, 0, 0,0, 0],
                     [   3_2_0, 2_5_6_2_9_9, 1_4_8_6_9, 2_8_1, 2_2_3_4, 2_8_9, 2_2_7_5, 3_3_3,6_1_3_9_1, 2_8_9, 2_5_6_2_9_8, 5_4_3, 2_5_6_2_9_7, 1_6_8_7_1_4, 3_2_9, 2_5_6_2_9_6,2_7_4, 1],
                 ]	)
             # fmt: on
             torch.testing.assert_allclose(SCREAMING_SNAKE_CASE     ,						SCREAMING_SNAKE_CASE	)

             _a    : Tuple     					=model.generate(input_ids.to(SCREAMING_SNAKE_CASE	)	)
             _a    : Union[str, Any]     					=[
                 """<pad><extra_id_0> et<extra_id_1> [eod] <extra_id_2><extra_id_55>.. [eod] 💐 💐 💐 💐 💐 💐 💐 💐 💐 💐 💐 <extra_id_56>ajšietosto<extra_id_56>lleux<extra_id_19><extra_id_6>ajšie</s>""",
                 """<pad><extra_id_0>.<extra_id_1>.,<0x0A>...spech <0x0A><extra_id_20> <extra_id_21></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>""",
                 """<pad><extra_id_0> are not going to be a part of the world. We are not going to be a part of<extra_id_1> and<extra_id_2><0x0A><extra_id_48>.<extra_id_48></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>""",
                 """<pad><extra_id_0> door<extra_id_1>, the door<extra_id_2> 피해[/</s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>""",
                 """<pad><extra_id_0>nyone who<extra_id_1> drink<extra_id_2> a<extra_id_3> alcohol<extra_id_4> A<extra_id_5> A. This<extra_id_6> I<extra_id_7><extra_id_52><extra_id_53></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>""",
             ]
             _a    : Tuple     					=tokenizer.batch_decode(SCREAMING_SNAKE_CASE	)
             self.assertEqual(SCREAMING_SNAKE_CASE     ,						SCREAMING_SNAKE_CASE	)






'''simple docstring'''







import argparse
import gc
import json
import os
import shutil
import warnings

import torch

from transformers import LlamaConfig, LlamaForCausalLM, LlamaTokenizer


try:
   from transformers import LlamaTokenizerFast
except ImportError as e:
   warnings.warn(e)
   warnings.warn(
       '''The converted tokenizer will be the `slow` tokenizer. To use the fast, update your `tokenizers` library and re-run the tokenizer conversion'''
   )
   A__:    Dict					    =       None
A__:    Tuple					    =       {
    '''7B''': 1_1008,
    '''13B''': 1_3824,
    '''30B''': 1_7920,
    '''65B''': 2_2016,
    '''70B''': 2_8672,
}
A__:    Any					    =       {
    '''7B''': 1,
    '''7Bf''': 1,
    '''13B''': 2,
    '''13Bf''': 2,
    '''30B''': 4,
    '''65B''': 8,
    '''70B''': 8,
    '''70Bf''': 8,
}


def 	SCREAMING_SNAKE_CASE_					(  _UpperCAmelCase	:	Optional[int]    ,_UpperCAmelCase	:	Optional[int]=1    ,_UpperCAmelCase	:	List[str]=256  )  ->			Dict:
       return multiple_of * ((int(ffn_dim_multiplier * int(8 * n / 3  )  ) + multiple_of - 1) // multiple_of)


def 	SCREAMING_SNAKE_CASE_					(  _UpperCAmelCase	:	List[Any]  )  ->			List[str]:
       with open(_UpperCAmelCase    ,"""r"""  ) as f:
              return json.load(_UpperCAmelCase  )


def 	SCREAMING_SNAKE_CASE_					(  _UpperCAmelCase	:	str    ,_UpperCAmelCase	:	Optional[Any]  )  ->			Tuple:
       with open(_UpperCAmelCase    ,"""w"""  ) as f:
              json.dump(_UpperCAmelCase    ,_UpperCAmelCase  )


def 	SCREAMING_SNAKE_CASE_					(  _UpperCAmelCase	:	str    ,_UpperCAmelCase	:	Optional[Any]    ,_UpperCAmelCase	:	int    ,_UpperCAmelCase	:	List[Any]=True  )  ->			Union[str, Any]:
       os.makedirs(_UpperCAmelCase    ,exist_ok=_UpperCAmelCase  )
       _a    : Union[str, Any]     					=os.path.join(_UpperCAmelCase    ,"""tmp"""  )
       os.makedirs(_UpperCAmelCase    ,exist_ok=_UpperCAmelCase  )

       _a    : int     					=read_json(os.path.join(_UpperCAmelCase    ,"""params.json"""  )  )
       _a    : int     					=NUM_SHARDS[model_size]
       _a    : Dict     					=params["""n_layers"""]
       _a    : Union[str, Any]     					=params["""n_heads"""]
       _a    : List[str]     					=n_heads // num_shards
       _a    : int     					=params["""dim"""]
       _a    : Union[str, Any]     					=dim // n_heads
       _a    : int     					=1_0_0_0_0.0
       _a    : str     					=1.0 / (base ** (torch.arange(0    ,_UpperCAmelCase    ,2  ).float() / dims_per_head))

       if "n_kv_heads" in params:
              _a    : str     					=params["""n_kv_heads"""]  # for GQA / MQA
              _a    : Optional[Any]     					=n_heads_per_shard // num_key_value_heads
              _a    : Optional[int]     					=dim // num_key_value_heads
       else:  # compatibility with other checkpoints
              _a    : str     					=n_heads
              _a    : Any     					=n_heads_per_shard
              _a    : str     					=dim

       # permute for sliced rotary
       def permute(_UpperCAmelCase	:	Tuple    ,_UpperCAmelCase	:	Optional[int]=n_heads    ,_UpperCAmelCase	:	Optional[int]=dim    ,_UpperCAmelCase	:	List[str]=dim  ):
              return w.view(_UpperCAmelCase    ,dima // n_heads // 2    ,2    ,_UpperCAmelCase  ).transpose(1    ,2  ).reshape(_UpperCAmelCase    ,_UpperCAmelCase  )

       print(F"Fetching all parameters from the checkpoint at {input_base_path}."  )
       # Load weights
       if model_size == "7B":
              # Not sharded
              # (The sharded implementation would also work, but this is simpler.)
              _a    : Any     					=torch.load(os.path.join(_UpperCAmelCase    ,"""consolidated.00.pth"""  )    ,map_location="""cpu"""  )
       else:
              # Sharded
              _a    : List[Any]     					=[
                  torch.load(os.path.join(_UpperCAmelCase    ,F"consolidated.{i:02d}.pth"  )    ,map_location="""cpu"""  )
                  for i in range(_UpperCAmelCase  )
              ]
       _a    : Any     					=0
       _a    : Optional[int]     					={"""weight_map""": {}}
       for layer_i in range(_UpperCAmelCase  ):
              _a    : List[str]     					=F"pytorch_model-{layer_i + 1}-of-{n_layers + 1}.bin"
              if model_size == "7B":
                     # Unsharded
                     _a    : List[str]     					={
                         F"model.layers.{layer_i}.self_attn.q_proj.weight": permute(
                             loaded[F"layers.{layer_i}.attention.wq.weight"]  ),
                         F"model.layers.{layer_i}.self_attn.k_proj.weight": permute(
                             loaded[F"layers.{layer_i}.attention.wk.weight"]  ),
                         F"model.layers.{layer_i}.self_attn.v_proj.weight": loaded[F"layers.{layer_i}.attention.wv.weight"],
                         F"model.layers.{layer_i}.self_attn.o_proj.weight": loaded[F"layers.{layer_i}.attention.wo.weight"],
                         F"model.layers.{layer_i}.mlp.gate_proj.weight": loaded[F"layers.{layer_i}.feed_forward.w1.weight"],
                         F"model.layers.{layer_i}.mlp.down_proj.weight": loaded[F"layers.{layer_i}.feed_forward.w2.weight"],
                         F"model.layers.{layer_i}.mlp.up_proj.weight": loaded[F"layers.{layer_i}.feed_forward.w3.weight"],
                         F"model.layers.{layer_i}.input_layernorm.weight": loaded[F"layers.{layer_i}.attention_norm.weight"],
                         F"model.layers.{layer_i}.post_attention_layernorm.weight": loaded[F"layers.{layer_i}.ffn_norm.weight"],
                     }
              else:
                     # Sharded
                     # Note that attention.w{q,k,v,o}, feed_fordward.w[1,2,3], attention_norm.weight and ffn_norm.weight share
                     # the same storage object, saving attention_norm and ffn_norm will save other weights too, which is
                     # redundant as other weights will be stitched from multiple shards. To avoid that, they are cloned.

                     _a    : Tuple     					={
                         F"model.layers.{layer_i}.input_layernorm.weight": loaded[0][
                             F"layers.{layer_i}.attention_norm.weight"
                         ].clone(),
                         F"model.layers.{layer_i}.post_attention_layernorm.weight": loaded[0][
                             F"layers.{layer_i}.ffn_norm.weight"
                         ].clone(),
                     }
                     _a    : str     					=permute(
                         torch.cat(
                             [
                                 loaded[i][F"layers.{layer_i}.attention.wq.weight"].view(_UpperCAmelCase    ,_UpperCAmelCase    ,_UpperCAmelCase  )
                                 for i in range(_UpperCAmelCase  )
                             ]    ,dim=0    ,).reshape(_UpperCAmelCase    ,_UpperCAmelCase  )  )
                     _a    : Tuple     					=permute(
                         torch.cat(
                             [
                                 loaded[i][F"layers.{layer_i}.attention.wk.weight"].view(
                                     _UpperCAmelCase    ,_UpperCAmelCase    ,_UpperCAmelCase  )
                                 for i in range(_UpperCAmelCase  )
                             ]    ,dim=0    ,).reshape(_UpperCAmelCase    ,_UpperCAmelCase  )    ,_UpperCAmelCase    ,_UpperCAmelCase    ,_UpperCAmelCase    ,)
                     _a    : Any     					=torch.cat(
                         [
                             loaded[i][F"layers.{layer_i}.attention.wv.weight"].view(
                                 _UpperCAmelCase    ,_UpperCAmelCase    ,_UpperCAmelCase  )
                             for i in range(_UpperCAmelCase  )
                         ]    ,dim=0    ,).reshape(_UpperCAmelCase    ,_UpperCAmelCase  )

                     _a    : List[str]     					=torch.cat(
                         [loaded[i][F"layers.{layer_i}.attention.wo.weight"] for i in range(_UpperCAmelCase  )]    ,dim=1  )
                     _a    : Union[str, Any]     					=torch.cat(
                         [loaded[i][F"layers.{layer_i}.feed_forward.w1.weight"] for i in range(_UpperCAmelCase  )]    ,dim=0  )
                     _a    : Tuple     					=torch.cat(
                         [loaded[i][F"layers.{layer_i}.feed_forward.w2.weight"] for i in range(_UpperCAmelCase  )]    ,dim=1  )
                     _a    : Union[str, Any]     					=torch.cat(
                         [loaded[i][F"layers.{layer_i}.feed_forward.w3.weight"] for i in range(_UpperCAmelCase  )]    ,dim=0  )

              _a    : str     					=inv_freq
              for k, v in state_dict.items():
                     _a    : Any     					=filename
                     param_count += v.numel()
              torch.save(_UpperCAmelCase    ,os.path.join(_UpperCAmelCase    ,_UpperCAmelCase  )  )

       _a    : Union[str, Any]     					=F"pytorch_model-{n_layers + 1}-of-{n_layers + 1}.bin"
       if model_size == "7B":
              # Unsharded
              _a    : List[str]     					={
                  """model.embed_tokens.weight""": loaded["""tok_embeddings.weight"""],
                  """model.norm.weight""": loaded["""norm.weight"""],
                  """lm_head.weight""": loaded["""output.weight"""],
              }
       else:
              _a    : int     					={
                  """model.norm.weight""": loaded[0]["""norm.weight"""],
                  """model.embed_tokens.weight""": torch.cat(
                      [loaded[i]["""tok_embeddings.weight"""] for i in range(_UpperCAmelCase  )]    ,dim=1  ),
                  """lm_head.weight""": torch.cat([loaded[i]["""output.weight"""] for i in range(_UpperCAmelCase  )]    ,dim=0  ),
              }

       for k, v in state_dict.items():
              _a    : Dict     					=filename
              param_count += v.numel()
       torch.save(_UpperCAmelCase    ,os.path.join(_UpperCAmelCase    ,_UpperCAmelCase  )  )

       # Write configs
       _a    : Tuple     					={"""total_size""": param_count * 2}
       write_json(_UpperCAmelCase    ,os.path.join(_UpperCAmelCase    ,"""pytorch_model.bin.index.json"""  )  )
       _a    : Optional[Any]     					=params["""ffn_dim_multiplier"""] if """ffn_dim_multiplier""" in params else 1
       _a    : int     					=params["""multiple_of"""] if """multiple_of""" in params else 256
       _a    : List[Any]     					=LlamaConfig(
           hidden_size=_UpperCAmelCase    ,intermediate_size=compute_intermediate_size(_UpperCAmelCase    ,_UpperCAmelCase    ,_UpperCAmelCase  )    ,num_attention_heads=params["""n_heads"""]    ,num_hidden_layers=params["""n_layers"""]    ,rms_norm_eps=params["""norm_eps"""]    ,num_key_value_heads=_UpperCAmelCase    ,)
       config.save_pretrained(_UpperCAmelCase  )

       # Make space so we can load the model properly now.
       del state_dict
       del loaded
       gc.collect()

       print("""Loading the checkpoint in a Llama model."""  )
       _a    : Any     					=LlamaForCausalLM.from_pretrained(_UpperCAmelCase    ,torch_dtype=torch.floataa    ,low_cpu_mem_usage=_UpperCAmelCase  )
       # Avoid saving this as part of the config.
       del model.config._name_or_path

       print("""Saving in the Transformers format."""  )
       model.save_pretrained(_UpperCAmelCase    ,safe_serialization=_UpperCAmelCase  )
       shutil.rmtree(_UpperCAmelCase  )


def 	SCREAMING_SNAKE_CASE_					(  _UpperCAmelCase	:	int    ,_UpperCAmelCase	:	int  )  ->			Optional[Any]:
       # Initialize the tokenizer based on the `spm` model
       _a    : List[str]     					=LlamaTokenizer if LlamaTokenizerFast is None else LlamaTokenizerFast
       print(F"Saving a {tokenizer_class.__name__} to {tokenizer_path}."  )
       _a    : List[Any]     					=tokenizer_class(_UpperCAmelCase  )
       tokenizer.save_pretrained(_UpperCAmelCase  )


def 	SCREAMING_SNAKE_CASE_					(  )  ->			Union[str, Any]:
       _a    : List[str]     					=argparse.ArgumentParser()
       parser.add_argument(
           """--input_dir"""    ,help="""Location of LLaMA weights, which contains tokenizer.model and model folders"""    ,)
       parser.add_argument(
           """--model_size"""    ,choices=["""7B""", """7Bf""", """13B""", """13Bf""", """30B""", """65B""", """70B""", """70Bf""", """tokenizer_only"""]    ,)
       parser.add_argument(
           """--output_dir"""    ,help="""Location to write HF model and tokenizer"""    ,)
       parser.add_argument("""--safe_serialization"""    ,type=_UpperCAmelCase    ,help="""Whether or not to save using `safetensors`."""  )
       _a    : Optional[Any]     					=parser.parse_args()
       if args.model_size != "tokenizer_only":
              write_model(
                  model_path=args.output_dir    ,input_base_path=os.path.join(args.input_dir    ,args.model_size  )    ,model_size=args.model_size    ,safe_serialization=args.safe_serialization    ,)
       _a    : List[Any]     					=os.path.join(args.input_dir    ,"""tokenizer.model"""  )
       write_tokenizer(args.output_dir    ,_UpperCAmelCase  )


if __name__ == "__main__":
   main()


