



'''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'''
       )
       __lowerCAmelCase						      =       None
__lowerCAmelCase						      =       {
    '''7B''': 11_008,
    '''13B''': 13_824,
    '''30B''': 17_920,
    '''65B''': 22_016,
    '''70B''': 28_672,
}
__lowerCAmelCase						      =       {
    '''7B''': 1,
    '''7Bf''': 1,
    '''13B''': 2,
    '''13Bf''': 2,
    '''30B''': 4,
    '''65B''': 8,
    '''70B''': 8,
    '''70Bf''': 8,
}



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



def 					__lowerCamelCase					(				lowerCAmelCase_  )      ->				Tuple:
  with open(lowerCAmelCase_						,      'r'  ) as f:
    return json.load(lowerCAmelCase_  )



def 					__lowerCamelCase					(				lowerCAmelCase_						,      lowerCAmelCase_  )      ->				List[str]:
  with open(lowerCAmelCase_						,      'w'  ) as f:
    json.dump(lowerCAmelCase_						,      lowerCAmelCase_  )



def 					__lowerCamelCase					(				lowerCAmelCase_						,      lowerCAmelCase_						,      lowerCAmelCase_						,      lowerCAmelCase_=True  )      ->				str:
  os.makedirs(lowerCAmelCase_						,      exist_ok=lowerCAmelCase_  )
  _a					:				Any				=							os.path.join(lowerCAmelCase_						,      'tmp'  )
  os.makedirs(lowerCAmelCase_						,      exist_ok=lowerCAmelCase_  )

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

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

  # permute for sliced rotary
  def permute(lowerCAmelCase_						,      lowerCAmelCase_=n_heads						,      lowerCAmelCase_=dim						,      lowerCAmelCase_=dim  ):
    return w.view(lowerCAmelCase_						,      dima // n_heads // 2						,      2						,      lowerCAmelCase_  ).transpose(1						,      2  ).reshape(lowerCAmelCase_						,      lowerCAmelCase_  )

  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					:				Dict				=							torch.load(os.path.join(lowerCAmelCase_						,      'consolidated.00.pth'  )						,      map_location='cpu'  )
  else:
    # Sharded
    _a					:				Optional[Any]				=							[
        torch.load(os.path.join(lowerCAmelCase_						,      f"""consolidated.{i:02d}.pth"""  )						,      map_location='cpu'  )
        for i in range(lowerCAmelCase_  )
    ]
  _a					:				Optional[int]				=							0
  _a					:				Any				=							{'weight_map': {}}
  for layer_i in range(lowerCAmelCase_  ):
    _a					:				Optional[Any]				=							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					:				Union[str, Any]				=							{
          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					:				Dict				=							permute(
          torch.cat(
              [
                  loaded[i][f"""layers.{layer_i}.attention.wq.weight"""].view(lowerCAmelCase_						,      lowerCAmelCase_						,      lowerCAmelCase_  )
                  for i in range(lowerCAmelCase_  )
              ]						,      dim=0						,      ).reshape(lowerCAmelCase_						,      lowerCAmelCase_  )  )
      _a					:				Tuple				=							permute(
          torch.cat(
              [
                  loaded[i][f"""layers.{layer_i}.attention.wk.weight"""].view(
                      lowerCAmelCase_						,      lowerCAmelCase_						,      lowerCAmelCase_  )
                  for i in range(lowerCAmelCase_  )
              ]						,      dim=0						,      ).reshape(lowerCAmelCase_						,      lowerCAmelCase_  )						,      lowerCAmelCase_						,      lowerCAmelCase_						,      lowerCAmelCase_						,      )
      _a					:				Tuple				=							torch.cat(
          [
              loaded[i][f"""layers.{layer_i}.attention.wv.weight"""].view(
                  lowerCAmelCase_						,      lowerCAmelCase_						,      lowerCAmelCase_  )
              for i in range(lowerCAmelCase_  )
          ]						,      dim=0						,      ).reshape(lowerCAmelCase_						,      lowerCAmelCase_  )

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

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

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

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

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

  # 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					:				List[str]				=							LlamaForCausalLM.from_pretrained(lowerCAmelCase_						,      torch_dtype=torch.floataa						,      low_cpu_mem_usage=lowerCAmelCase_  )
  # Avoid saving this as part of the config.
  del model.config._name_or_path

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



def 					__lowerCamelCase					(				lowerCAmelCase_						,      lowerCAmelCase_  )      ->				str:
  # Initialize the tokenizer based on the `spm` model
  _a					:				Dict				=							LlamaTokenizer if LlamaTokenizerFast is None else LlamaTokenizerFast
  print(f"""Saving a {tokenizer_class.__name__} to {tokenizer_path}."""  )
  _a					:				Dict				=							tokenizer_class(lowerCAmelCase_  )
  tokenizer.save_pretrained(lowerCAmelCase_  )



def 					__lowerCamelCase					(				)      ->				Optional[int]:
  _a					:				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=lowerCAmelCase_						,      help='Whether or not to save using `safetensors`.'  )
  _a					:				Tuple				=							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						,      lowerCAmelCase_  )


if __name__ == "__main__":
       main()









'''simple docstring'''

import doctest
import glob
import importlib
import inspect
import os
import re
from contextlib import contextmanager
from functools import wraps
from unittest.mock import patch

import numpy as np
import pytest
from absl.testing import parameterized

import datasets
from datasets import load_metric

from .utils import for_all_test_methods, local, slow


# mark all tests as integration
__lowerCAmelCase						      =       pytest.mark.integration


__lowerCAmelCase						      =       {'''comet'''}
__lowerCAmelCase						      =       importlib.util.find_spec('''fairseq''') is not None

__lowerCAmelCase						      =       {'''code_eval'''}
__lowerCAmelCase						      =       os.name == '''nt'''

__lowerCAmelCase						      =       {'''bertscore''', '''frugalscore''', '''perplexity'''}
__lowerCAmelCase						      =       importlib.util.find_spec('''transformers''') is not None



def 					__lowerCamelCase					(				lowerCAmelCase_  )      ->				Any:
		@wraps(lowerCAmelCase_  )
		def wrapper(self						,      lowerCAmelCase_  ):
				if not _has_fairseq and metric_name in REQUIRE_FAIRSEQ:
						self.skipTest('"test requires Fairseq"'  )
				else:
						test_case(self						,      lowerCAmelCase_  )

		return wrapper



def 					__lowerCamelCase					(				lowerCAmelCase_  )      ->				Union[str, Any]:
		@wraps(lowerCAmelCase_  )
		def wrapper(self						,      lowerCAmelCase_  ):
				if not _has_transformers and metric_name in REQUIRE_TRANSFORMERS:
						self.skipTest('"test requires transformers"'  )
				else:
						test_case(self						,      lowerCAmelCase_  )

		return wrapper



def 					__lowerCamelCase					(				lowerCAmelCase_  )      ->				int:
		@wraps(lowerCAmelCase_  )
		def wrapper(self						,      lowerCAmelCase_  ):
				if _on_windows and metric_name in UNSUPPORTED_ON_WINDOWS:
						self.skipTest('"test not supported on Windows"'  )
				else:
						test_case(self						,      lowerCAmelCase_  )

		return wrapper



def 					__lowerCamelCase					(				)      ->				Tuple:
		_a					:				Optional[int]				=							[metric_dir.split(os.sep  )[-2] for metric_dir in glob.glob('./metrics/*/'  )]
		return [{"testcase_name": x, "metric_name": x} for x in metrics if x != "gleu"]  # gleu is unfinished

@parameterized.named_parameters(get_local_metric_names()       )
@for_all_test_methods(
    _UpperCamelCase      ,						_UpperCamelCase      ,						_UpperCamelCase       )
@local
class      __magic_name__						(   parameterized.TestCase       ):
							lowerCAmelCase	:   List[str]           = {}
							lowerCAmelCase	:   Optional[int]           = None







							@pytest.mark.filterwarnings('ignore:metric_module_factory is deprecated:FutureWarning'		)
							@pytest.mark.filterwarnings('ignore:load_metric is deprecated:FutureWarning'		)
							def 							__lowercase      (							self :	Dict     ,_UpperCAmelCase :	Optional[Any]		):
									_a					:				Tuple				=							'[...]'
									_a					:				Dict				=							importlib.import_module(
									    datasets.load.metric_module_factory(os.path.join('metrics'     ,_UpperCAmelCase		)		).module_path		)
									_a					:				Optional[int]				=							datasets.load.import_main_class(metric_module.__name__     ,dataset=_UpperCAmelCase		)
									# check parameters
									_a					:				Optional[int]				=							inspect.signature(metric._compute		).parameters
									self.assertTrue(all(p.kind != p.VAR_KEYWORD for p in parameters.values()		)		)  # no **kwargs
									# run doctest
									with self.patch_intensive_calls(_UpperCAmelCase     ,metric_module.__name__		):
											with self.use_local_metrics():
													try:
															_a					:				Optional[int]				=							doctest.testmod(_UpperCAmelCase     ,verbose=_UpperCAmelCase     ,raise_on_error=_UpperCAmelCase		)
													except doctest.UnexpectedException as e:
															raise e.exc_info[1]  # raise the exception that doctest caught
									self.assertEqual(results.failed     ,0		)
									self.assertGreater(results.attempted     ,1		)







							@slow
							def 							__lowercase      (							self :	Tuple     ,_UpperCAmelCase :	Dict		):
									_a					:				Tuple				=							'[...]'
									_a					:				Optional[Any]				=							importlib.import_module(
									    datasets.load.metric_module_factory(os.path.join('metrics'     ,_UpperCAmelCase		)		).module_path		)
									# run doctest
									with self.use_local_metrics():
											_a					:				int				=							doctest.testmod(_UpperCAmelCase     ,verbose=_UpperCAmelCase     ,raise_on_error=_UpperCAmelCase		)
									self.assertEqual(results.failed     ,0		)
									self.assertGreater(results.attempted     ,1		)







							@contextmanager
							def 							__lowercase      (							self :	List[Any]     ,_UpperCAmelCase :	Dict     ,_UpperCAmelCase :	List[str]		):
									if metric_name in self.INTENSIVE_CALLS_PATCHER:
											with self.INTENSIVE_CALLS_PATCHER[metric_name](_UpperCAmelCase		):
													yield
									else:
											yield







							@contextmanager
							def 							__lowercase      (							self :	Optional[int]		):
									def load_local_metric(_UpperCAmelCase :	Tuple     ,*_UpperCAmelCase :	Dict     ,**_UpperCAmelCase :	Tuple		):
											return load_metric(os.path.join('metrics'     ,_UpperCAmelCase		)     ,*_UpperCAmelCase     ,**_UpperCAmelCase		)

									with patch('datasets.load_metric'		) as mock_load_metric:
											_a					:				Any				=							load_local_metric
											yield







							@classmethod
							def 							__lowercase      (							cls :	str     ,_UpperCAmelCase :	List[str]		):
									def wrapper(_UpperCAmelCase :	int		):
											_a					:				Optional[Any]				=							contextmanager(_UpperCAmelCase		)
											_a					:				Optional[int]				=							patcher
											return patcher

									return wrapper



@LocalMetricTest.register_intensive_calls_patcher('bleurt'  )
def 					__lowerCamelCase					(				lowerCAmelCase_  )      ->				List[str]:
		import tensorflow.compat.va as tf
		from bleurt.score import Predictor

		tf.flags.DEFINE_string('sv'						,      ''						,      ''  )  # handle pytest cli flags

		class      __magic_name__						(   _UpperCamelCase       ):







									def 							__lowercase      (							self :	int     ,_UpperCAmelCase :	Union[str, Any]		):
											assert len(input_dict['input_ids']		) == 2
											return np.array([1.03, 1.04]		)

    # mock predict_fn which is supposed to do a forward pass with a bleurt model
		with patch('bleurt.score._create_predictor'  ) as mock_create_predictor:
				_a					:				int				=							MockedPredictor()
				yield



@LocalMetricTest.register_intensive_calls_patcher('bertscore'  )
def 					__lowerCamelCase					(				lowerCAmelCase_  )      ->				Union[str, Any]:
		import torch

		def bert_cos_score_idf(lowerCAmelCase_						,      lowerCAmelCase_						,      *lowerCAmelCase_						,      **lowerCAmelCase_  ):
				return torch.tensor([[1.0, 1.0, 1.0]] * len(lowerCAmelCase_  )  )

		# mock get_model which is supposed to do download a bert model
		# mock bert_cos_score_idf which is supposed to do a forward pass with a bert model
		with patch('bert_score.scorer.get_model'  ), patch(
		    'bert_score.scorer.bert_cos_score_idf'  ) as mock_bert_cos_score_idf:
				_a					:				Any				=							bert_cos_score_idf
				yield



@LocalMetricTest.register_intensive_calls_patcher('comet'  )
def 					__lowerCamelCase					(				lowerCAmelCase_  )      ->				Dict:
		def load_from_checkpoint(lowerCAmelCase_  ):

				class      __magic_name__						:







											def 							__lowercase      (							self :	str     ,_UpperCAmelCase :	Dict     ,*_UpperCAmelCase :	int     ,**_UpperCAmelCase :	str		):
													assert len(_UpperCAmelCase		) == 2
													_a					:				Dict				=							[0.19, 0.92]
													return scores, sum(_UpperCAmelCase		) / len(_UpperCAmelCase		)
				return Model()

		# mock load_from_checkpoint which is supposed to do download a bert model
		# mock load_from_checkpoint which is supposed to do download a bert model
		with patch('comet.download_model'  ) as mock_download_model:
				_a					:				Any				=							None
				with patch('comet.load_from_checkpoint'  ) as mock_load_from_checkpoint:
						_a					:				Optional[Any]				=							load_from_checkpoint
						yield



def 					__lowerCamelCase					(				)      ->				Tuple:
		_a					:				Dict				=							load_metric(os.path.join('metrics'						,      'seqeval'  )  )
		_a					:				Optional[int]				=							'ERROR'
		_a					:				Optional[Any]				=							f"""Scheme should be one of [IOB1, IOB2, IOE1, IOE2, IOBES, BILOU], got {wrong_scheme}"""
		with pytest.raises(lowerCAmelCase_						,      match=re.escape(lowerCAmelCase_  )  ):
				metric.compute(predictions=[]						,      references=[]						,      scheme=lowerCAmelCase_  )




