






"""simple docstring"""



import io
import os
import unicodedata
from typing import Any, Dict, List, Optional, Tuple

import sentencepiece as spm

from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging


_lowerCAmelCase	:	Dict				=      logging.get_logger(__name__)

_lowerCAmelCase	:	List[Any]				=      """▁"""

_lowerCAmelCase	:	int				=      {"""vocab_file""": """vocab.txt""", """sentencepiece_model_ckpt""": """sentencepiece.bpe.model"""}

_lowerCAmelCase	:	Any				=      {
    """sentencepiece_model_file""": """sentencepiece.bpe.model""",
    """vocab_file""": """vocab.txt""",
}

_lowerCAmelCase	:	List[Any]				=      {
    """vocab_file""": {
        """ernie-m-base""": """https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/vocab.txt""",
        """ernie-m-large""": """https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/vocab.txt""",
    },
    """sentencepiece_model_file""": {
        """ernie-m-base""": """https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/sentencepiece.bpe.model""",
        """ernie-m-large""": """https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/sentencepiece.bpe.model""",
    },
}

_lowerCAmelCase	:	Any				=      {
    """ernie-m-base""": 514,
    """ernie-m-large""": 514,
}

_lowerCAmelCase	:	List[Any]				=      {
    """ernie-m-base""": {"""do_lower_case""": False},
    """ernie-m-large""": {"""do_lower_case""": False},
}




class 			lowerCAmelCase__			(    __magic_name__   ):
   SCREAMING_SNAKE_CASE_    =["input_ids"]

   SCREAMING_SNAKE_CASE_    =VOCAB_FILES_NAMES
   SCREAMING_SNAKE_CASE_    =PRETRAINED_INIT_CONFIGURATION
   SCREAMING_SNAKE_CASE_    =PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
   SCREAMING_SNAKE_CASE_    =PRETRAINED_VOCAB_FILES_MAP
   SCREAMING_SNAKE_CASE_    =RESOURCE_FILES_NAMES
   def __init__(		self      :	int							,			snake_case__      :	str							,			snake_case__      :	Tuple=None							,			snake_case__      :	Any=False							,			snake_case__      :	Union[str, Any]="utf8"							,			snake_case__      :	Dict="[UNK]"							,			snake_case__      :	Tuple="[SEP]"							,			snake_case__      :	List[str]="[PAD]"							,			snake_case__      :	List[str]="[CLS]"							,			snake_case__      :	Union[str, Any]="[MASK]"							,			snake_case__      :	Optional[Dict[str, Any]] = None							,			**snake_case__      :	List[Any]							,			):


        '''simple docstring'''
        # Mask token behave like a normal word, i.e. include the space before it and
        # is included in the raw text, there should be a match in a non-normalized sentence.

        UpperCAmelCase__						:    List[Any]							=							{} if sp_model_kwargs is None else sp_model_kwargs
        super().__init__(
            do_lower_case=snake_case__							,			unk_token=snake_case__							,			sep_token=snake_case__							,			pad_token=snake_case__							,			cls_token=snake_case__							,			mask_token=snake_case__							,			vocab_file=snake_case__							,			encoding=snake_case__							,			sp_model_kwargs=self.sp_model_kwargs							,			**snake_case__							,			)
        UpperCAmelCase__						:    Tuple							=							do_lower_case
        UpperCAmelCase__						:    List[str]							=							sentencepiece_model_ckpt
        UpperCAmelCase__						:    Tuple							=							spm.SentencePieceProcessor(**self.sp_model_kwargs							)
        self.sp_model.Load(snake_case__							)

        # to mimic paddlenlp.transformers.ernie_m.tokenizer.ErnieMTokenizer functioning
        if vocab_file is not None:
             UpperCAmelCase__						:    Optional[Any]							=							self.load_vocab(filepath=snake_case__							)
        else:
             UpperCAmelCase__						:    int							=							{self.sp_model.id_to_piece(snake_case__							): id for id in range(self.sp_model.get_piece_size()							)}
        UpperCAmelCase__						:    str							=							{v: k for k, v in self.vocab.items()}
   def       __a							(		self      :	List[Any]							,			snake_case__      :	Dict							):


        '''simple docstring'''
        if text is None:
             return None

        UpperCAmelCase__						:    Optional[Any]							=							self.tokenize(snake_case__							)
        UpperCAmelCase__							,				UpperCAmelCase__						:    Tuple							=							"", []

        for i, ch in enumerate(snake_case__							):
             if ch in self.SP_CHAR_MAPPING:
                  UpperCAmelCase__						:    Any							=							self.SP_CHAR_MAPPING.get(snake_case__							)
             else:
                  UpperCAmelCase__						:    str							=							unicodedata.normalize("NFKC"							,			snake_case__							)
             if self.is_whitespace(snake_case__							):
                  continue
             normalized_text += ch
             char_mapping.extend([i] * len(snake_case__							)							)

        UpperCAmelCase__							,				UpperCAmelCase__							,				UpperCAmelCase__						:    Optional[Any]							=							normalized_text, [], 0

        if self.do_lower_case:
             UpperCAmelCase__						:    Tuple							=							text.lower()

        for token in split_tokens:
             if token[:1] == "▁":
                  UpperCAmelCase__						:    str							=							token[1:]
             UpperCAmelCase__						:    Union[str, Any]							=							text[offset:].index(snake_case__							) + offset
             UpperCAmelCase__						:    int							=							start + len(snake_case__							)

             token_mapping.append((char_mapping[start], char_mapping[end - 1] + 1)							)
             UpperCAmelCase__						:    Union[str, Any]							=							end
        return token_mapping
   @property
   def       __a							(		self      :	Any							):


        '''simple docstring'''
        return len(self.vocab							)
   def       __a							(		self      :	Union[str, Any]							):


        '''simple docstring'''
        return dict(self.vocab							,			**self.added_tokens_encoder							)
   def __getstate__(		self      :	Optional[int]							):


        '''simple docstring'''
        UpperCAmelCase__						:    Optional[int]							=							self.__dict__.copy()
        UpperCAmelCase__						:    List[str]							=							None
        return state
   def __setstate__(		self      :	Union[str, Any]							,			snake_case__      :	List[Any]							):


        '''simple docstring'''
        UpperCAmelCase__						:    Optional[Any]							=							d

        # for backward compatibility
        if not hasattr(self							,			"sp_model_kwargs"							):
             UpperCAmelCase__						:    Dict							=							{}

        UpperCAmelCase__						:    Tuple							=							spm.SentencePieceProcessor(**self.sp_model_kwargs							)
        self.sp_model.Load(self.sentencepiece_model_ckpt							)
   def       __a							(		self      :	List[str]							,			snake_case__      :	Dict							):


        '''simple docstring'''
        return "".join((self.SP_CHAR_MAPPING.get(snake_case__							,			snake_case__							) for c in text)							)
   def       __a							(		self      :	Optional[Any]							,			snake_case__      :	Optional[int]							,			snake_case__      :	str=False							,			snake_case__      :	str=6_4							,			snake_case__      :	str=0.1							):


        '''simple docstring'''

        if self.sp_model_kwargs.get("enable_sampling"							) is True:
             UpperCAmelCase__						:    int							=							True
        if self.sp_model_kwargs.get("alpha"							) is not None:
             UpperCAmelCase__						:    Optional[int]							=							self.sp_model_kwargs.get("alpha"							)
        if self.sp_model_kwargs.get("nbest_size"							) is not None:
             UpperCAmelCase__						:    List[Any]							=							self.sp_model_kwargs.get("nbest_size"							)

        if not enable_sampling:
             UpperCAmelCase__						:    Union[str, Any]							=							self.sp_model.EncodeAsPieces(snake_case__							)
        else:
             UpperCAmelCase__						:    List[str]							=							self.sp_model.SampleEncodeAsPieces(snake_case__							,			snake_case__							,			snake_case__							)
        UpperCAmelCase__						:    Any							=							[]
        for pi, piece in enumerate(snake_case__							):
             if piece == SPIECE_UNDERLINE:
                  if not pieces[pi + 1].startswith(snake_case__							) and pi != 0:
                       new_pieces.append(snake_case__							)
                       continue
                  else:
                       continue
             UpperCAmelCase__						:    List[Any]							=							0
             for i, chunk in enumerate(snake_case__							):
                  if chunk == SPIECE_UNDERLINE:
                       continue
                  if self.is_ch_char(snake_case__							) or self.is_punct(snake_case__							):
                       if i > lst_i and piece[lst_i:i] != SPIECE_UNDERLINE:
                            new_pieces.append(piece[lst_i:i]							)
                       new_pieces.append(snake_case__							)
                       UpperCAmelCase__						:    str							=							i + 1
                  elif chunk.isdigit() and i > 0 and not piece[i - 1].isdigit():
                       if i > lst_i and piece[lst_i:i] != SPIECE_UNDERLINE:
                            new_pieces.append(piece[lst_i:i]							)
                       UpperCAmelCase__						:    int							=							i
                  elif not chunk.isdigit() and i > 0 and piece[i - 1].isdigit():
                       if i > lst_i and piece[lst_i:i] != SPIECE_UNDERLINE:
                            new_pieces.append(piece[lst_i:i]							)
                       UpperCAmelCase__						:    Optional[int]							=							i
             if len(snake_case__							) > lst_i:
                  new_pieces.append(piece[lst_i:]							)
        return new_pieces
   def       __a							(		self      :	List[str]							,			snake_case__      :	Optional[int]							):


        '''simple docstring'''
        UpperCAmelCase__						:    List[Any]							=							"".join(snake_case__							).replace(snake_case__							,			" "							).strip()
        return out_string
   def       __a							(		self      :	Tuple							,			snake_case__      :	Optional[int]							):


        '''simple docstring'''
        UpperCAmelCase__						:    List[str]							=							self.convert_ids_to_tokens(snake_case__							)
        UpperCAmelCase__						:    Any							=							"".join(snake_case__							).replace(snake_case__							,			" "							).strip()
        return out_string
   def       __a							(		self      :	Tuple							,			snake_case__      :	List[Any]							):


        '''simple docstring'''
        return self.vocab.get(snake_case__							,			self.vocab.get(self.unk_token							)							)
   def       __a							(		self      :	int							,			snake_case__      :	List[Any]							):


        '''simple docstring'''
        return self.reverse_vocab.get(snake_case__							,			self.unk_token							)
   def       __a							(		self      :	Optional[int]							,			snake_case__      :	Optional[Any]							,			snake_case__      :	Dict=None							):


        '''simple docstring'''
        if token_ids_a is None:
             return [self.cls_token_id] + token_ids_a + [self.sep_token_id]
        UpperCAmelCase__						:    Optional[Any]							=							[self.cls_token_id]
        UpperCAmelCase__						:    str							=							[self.sep_token_id]
        return _cls + token_ids_a + _sep + _sep + token_ids_a + _sep
   def       __a							(		self      :	int							,			snake_case__      :	List[str]							,			snake_case__      :	str=None							):


        '''simple docstring'''
        if offset_mapping_a is None:
             return [(0, 0)] + offset_mapping_a + [(0, 0)]

        return [(0, 0)] + offset_mapping_a + [(0, 0), (0, 0)] + offset_mapping_a + [(0, 0)]
   def       __a							(		self      :	Union[str, Any]							,			snake_case__      :	List[Any]							,			snake_case__      :	List[str]=None							,			snake_case__      :	Union[str, Any]=False							):


        '''simple docstring'''

        if already_has_special_tokens:
             if token_ids_a is not None:
                  raise ValueError(
                      "You should not supply a second sequence if the provided sequence of "
                      "ids is already formatted with special tokens for the model."							)
             return [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_a]

        if token_ids_a is not None:
             return [1] + ([0] * len(snake_case__							)) + [1, 1] + ([0] * len(snake_case__							)) + [1]
        return [1] + ([0] * len(snake_case__							)) + [1]
   def       __a							(		self      :	int							,			snake_case__      :	List[int]							,			snake_case__      :	Optional[List[int]] = None							):


        '''simple docstring'''
        # called when `add_special_tokens` is True, so align with `build_inputs_with_special_tokens` method
        if token_ids_a is None:
             # [CLS] X [SEP]
             return (len(snake_case__							) + 2) * [0]

        # [CLS] A [SEP] [SEP] B [SEP]
        return [0] * (len(snake_case__							) + 1) + [1] * (len(snake_case__							) + 3)
   def       __a							(		self      :	Optional[Any]							,			snake_case__      :	Union[str, Any]							):


        '''simple docstring'''
        if "\u4e00" <= char <= "\u9fff":
             return True
        return False
   def       __a							(		self      :	Dict							,			snake_case__      :	Optional[int]							):


        '''simple docstring'''
        if ("a" <= char <= "z") or ("A" <= char <= "Z"):
             return True
        return False
   def       __a							(		self      :	str							,			snake_case__      :	Union[str, Any]							):


        '''simple docstring'''
        if char in ",;:.?!~，；：。？！《》【】":
             return True
        return False
   def       __a							(		self      :	Dict							,			snake_case__      :	Any							):


        '''simple docstring'''
        if char == " " or char == "\t" or char == "\n" or char == "\r":
             return True
        if len(snake_case__							) == 1:
             UpperCAmelCase__						:    str							=							unicodedata.category(snake_case__							)
             if cat == "Zs":
                  return True
        return False
   def       __a							(		self      :	Union[str, Any]							,			snake_case__      :	int							):


        '''simple docstring'''
        UpperCAmelCase__						:    Union[str, Any]							=							{}
        with io.open(snake_case__							,			"r"							,			encoding="utf-8"							) as f:
             for index, line in enumerate(snake_case__							):
                  UpperCAmelCase__						:    str							=							line.rstrip("\n"							)
                  UpperCAmelCase__						:    Dict							=							int(snake_case__							)

        return token_to_idx




   def       __a							(		self      :	Union[str, Any]							,			snake_case__      :	str							,			snake_case__      :	Optional[str] = None							):


        '''simple docstring'''
        UpperCAmelCase__						:    List[str]							=							0
        if os.path.isdir(snake_case__							):
             UpperCAmelCase__						:    str							=							os.path.join(
                 snake_case__							,			(filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]							)
        else:
             UpperCAmelCase__						:    Any							=							(filename_prefix + "-" if filename_prefix else "") + save_directory
        with open(snake_case__							,			"w"							,			encoding="utf-8"							) as writer:
             for token, token_index in sorted(self.vocab.items()							,			key=lambda snake_case__							: kv[1]							):
                  if index != token_index:
                       logger.warning(
                           f'Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive.'
                           " Please check that the vocabulary is not corrupted!"							)
                       UpperCAmelCase__						:    str							=							token_index
                  writer.write(token + "\n"							)
                  index += 1

        UpperCAmelCase__						:    Union[str, Any]							=							os.path.join(snake_case__							,			"sentencepiece.bpe.model"							)
        with open(snake_case__							,			"wb"							) as fi:
             UpperCAmelCase__						:    str							=							self.sp_model.serialized_model_proto()
             fi.write(snake_case__							)

        return (vocab_file,)










"""simple docstring"""



import argparse
import gc
import json
import os
import re

import torch
from huggingface_hub import hf_hub_download

from transformers import AutoModelForCausalLM, AutoTokenizer, PreTrainedTokenizerFast, RwkvConfig
from transformers.modeling_utils import WEIGHTS_INDEX_NAME, shard_checkpoint


_lowerCAmelCase	:	Optional[int]				=      {
    """169M""": 12,
    """430M""": 24,
    """1B5""": 24,
    """3B""": 32,
    """7B""": 32,
    """14B""": 40,
}

_lowerCAmelCase	:	Optional[Any]				=      {
    """169M""": 768,
    """430M""": 1_024,
    """1B5""": 2_048,
    """3B""": 2_560,
    """7B""": 4_096,
    """14B""": 5_120,
}


def 	SCREAMING_SNAKE_CASE__       (  snake_case       : Any				)->		Tuple:






     '''simple docstring'''



     UpperCAmelCase__						:    str							=							list(state_dict.keys()				)
     for name in state_dict_keys:
          UpperCAmelCase__						:    Dict							=							state_dict.pop(snake_case				)
          # emb -> embedding
          if name.startswith("emb."				):
               UpperCAmelCase__						:    str							=							name.replace("emb."			,					"embeddings."				)
          # ln_0 -> pre_ln (only present at block 0)
          if name.startswith("blocks.0.ln0"				):
               UpperCAmelCase__						:    List[str]							=							name.replace("blocks.0.ln0"			,					"blocks.0.pre_ln"				)
          # att -> attention
          UpperCAmelCase__						:    Optional[int]							=							re.sub(r"blocks\.(\d+)\.att"			,					r"blocks.\1.attention"			,					snake_case				)
          # ffn -> feed_forward
          UpperCAmelCase__						:    Any							=							re.sub(r"blocks\.(\d+)\.ffn"			,					r"blocks.\1.feed_forward"			,					snake_case				)
          # time_mix_k -> time_mix_key and reshape
          if name.endswith(".time_mix_k"				):
               UpperCAmelCase__						:    List[Any]							=							name.replace(".time_mix_k"			,					".time_mix_key"				)
          # time_mix_v -> time_mix_value and reshape
          if name.endswith(".time_mix_v"				):
               UpperCAmelCase__						:    int							=							name.replace(".time_mix_v"			,					".time_mix_value"				)
          # time_mix_r -> time_mix_key and reshape
          if name.endswith(".time_mix_r"				):
               UpperCAmelCase__						:    Optional[Any]							=							name.replace(".time_mix_r"			,					".time_mix_receptance"				)

          if name != "head.weight":
               UpperCAmelCase__						:    int							=							"rwkv." + name

          UpperCAmelCase__						:    Dict							=							weight
     return state_dict


def 	SCREAMING_SNAKE_CASE__       (  snake_case       : Optional[Any]			,					snake_case       : Optional[int]			,					snake_case       : Optional[Any]			,					snake_case       : Dict=None			,					snake_case       : List[Any]=None			,					snake_case       : List[str]=False			,					snake_case       : str=None				)->		int:






     '''simple docstring'''



     if tokenizer_file is None:
          print("No `--tokenizer_file` provided, we will use the default tokenizer."				)
          UpperCAmelCase__						:    str							=							5_0277
          UpperCAmelCase__						:    List[Any]							=							AutoTokenizer.from_pretrained("EleutherAI/gpt-neox-20b"				)
     else:
          UpperCAmelCase__						:    Union[str, Any]							=							PreTrainedTokenizerFast(tokenizer_file=snake_case				)
          UpperCAmelCase__						:    Tuple							=							len(snake_case				)
     tokenizer.save_pretrained(snake_case				)

     # 2. Build the config
     UpperCAmelCase__						:    Dict							=							list(NUM_HIDDEN_LAYERS_MAPPING.keys()				)
     if size is None:
          # Try to infer size from the checkpoint name
          for candidate in possible_sizes:
               if candidate in checkpoint_file:
                    UpperCAmelCase__						:    List[Any]							=							candidate
                    break
          if size is None:
               raise ValueError("Could not infer the size, please provide it with the `--size` argument."				)
     if size not in possible_sizes:
          raise ValueError(f'`size` should be one of {possible_sizes}, got {size}.'				)

     UpperCAmelCase__						:    int							=							RwkvConfig(
         vocab_size=snake_case			,					num_hidden_layers=NUM_HIDDEN_LAYERS_MAPPING[size]			,					hidden_size=HIDEN_SIZE_MAPPING[size]			,					)
     config.save_pretrained(snake_case				)

     # 3. Download model file then convert state_dict
     UpperCAmelCase__						:    Optional[int]							=							hf_hub_download(snake_case			,					snake_case				)
     UpperCAmelCase__						:    Optional[Any]							=							torch.load(snake_case			,					map_location="cpu"				)
     UpperCAmelCase__						:    Tuple							=							convert_state_dict(snake_case				)

     # 4. Split in shards and save
     UpperCAmelCase__							,				UpperCAmelCase__						:    List[Any]							=							shard_checkpoint(snake_case				)
     for shard_file, shard in shards.items():
          torch.save(snake_case			,					os.path.join(snake_case			,					snake_case				)				)

     if index is not None:
          UpperCAmelCase__						:    Tuple							=							os.path.join(snake_case			,					snake_case				)
          # Save the index as well
          with open(snake_case			,					"w"			,					encoding="utf-8"				) as f:
               UpperCAmelCase__						:    Any							=							json.dumps(snake_case			,					indent=2			,					sort_keys=snake_case				) + "\n"
               f.write(snake_case				)

          # 5. Clean up shards (for some reason the file PyTorch saves take the same space as the whole state_dict
          print(
              "Cleaning up shards. This may error with an OOM error, it this is the case don't worry you still have converted the model."				)
          UpperCAmelCase__						:    List[str]							=							list(shards.keys()				)

          del state_dict
          del shards
          gc.collect()

          for shard_file in shard_files:
               UpperCAmelCase__						:    Any							=							torch.load(os.path.join(snake_case			,					snake_case				)				)
               torch.save({k: v.cpu().clone() for k, v in state_dict.items()}			,					os.path.join(snake_case			,					snake_case				)				)

     del state_dict
     gc.collect()

     if push_to_hub:
          if model_name is None:
               raise ValueError("Please provide a `model_name` to push the model to the Hub."				)
          UpperCAmelCase__						:    Optional[Any]							=							AutoModelForCausalLM.from_pretrained(snake_case				)
          model.push_to_hub(snake_case			,					max_shard_size="2GB"				)
          tokenizer.push_to_hub(snake_case				)


if __name__ == "__main__":
 _lowerCAmelCase	:	Optional[Any]				=      argparse.ArgumentParser()
 # Required parameters
 parser.add_argument(
     """--repo_id""", default=None, type=str, required=True, help="""Repo ID from which to pull the checkpoint."""
 )
 parser.add_argument(
     """--checkpoint_file""", default=None, type=str, required=True, help="""Name of the checkpoint file in the repo."""
 )
 parser.add_argument(
     """--output_dir""", default=None, type=str, required=True, help="""Where to save the converted model."""
 )
 parser.add_argument(
     """--tokenizer_file""",
     default=None,
     type=str,
     help="""Path to the tokenizer file to use (if not provided, only the model is converted).""",
 )
 parser.add_argument(
     """--size""",
     default=None,
     type=str,
     help="""Size of the model. Will be inferred from the `checkpoint_file` if not passed.""",
 )
 parser.add_argument(
     """--push_to_hub""",
     action="""store_true""",
     help="""Push to the Hub the converted model.""",
 )
 parser.add_argument(
     """--model_name""",
     default=None,
     type=str,
     help="""Name of the pushed model on the Hub, including the username / organization.""",
 )

 _lowerCAmelCase	:	Dict				=      parser.parse_args()
 convert_rmkv_checkpoint_to_hf_format(
     args.repo_id,
     args.checkpoint_file,
     args.output_dir,
     size=args.size,
     tokenizer_file=args.tokenizer_file,
     push_to_hub=args.push_to_hub,
     model_name=args.model_name,
 )


