



'''simple docstring'''





# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import copy
import importlib.metadata
import json
import os
from dataclasses import dataclass
from typing import Any, Dict, Union

from packaging import version

from ..utils import is_torch_available, logging


if is_torch_available():
   import torch


__lowerCamelCase         =			logging.get_logger(__name__)


@dataclass
class   snake_case_ :




       """simple docstring"""






       def __init__(     self     ,lowercase=False     ,lowercase=False     ,lowercase=6.0     ,lowercase=None     ,lowercase=False     ,lowercase=False     ,lowercase=None     ,lowercase="fp4"     ,lowercase=False     ,**lowercase     ,):

             """simple docstring"""





             UpperCAmelCase_  :	int				      =		load_in_abit
             UpperCAmelCase_  :	Tuple				      =		load_in_abit
             UpperCAmelCase_  :	Union[str, Any]				      =		llm_inta_threshold
             UpperCAmelCase_  :	Tuple				      =		llm_inta_skip_modules
             UpperCAmelCase_  :	List[str]				      =		llm_inta_enable_fpaa_cpu_offload
             UpperCAmelCase_  :	Dict				      =		llm_inta_has_fpaa_weight
             UpperCAmelCase_  :	Optional[Any]				      =		bnb_abit_quant_type
             UpperCAmelCase_  :	Tuple				      =		bnb_abit_use_double_quant

             if bnb_abit_compute_dtype is None:
                   UpperCAmelCase_  :	Any				      =		torch.floataa
             elif isinstance(lowercase     ,lowercase):
                   UpperCAmelCase_  :	int				      =		getattr(lowercase     ,lowercase)
             elif isinstance(lowercase     ,torch.dtype):
                   UpperCAmelCase_  :	Optional[Any]				      =		bnb_abit_compute_dtype
             else:
                   raise ValueError("bnb_4bit_compute_dtype must be a string or a torch.dtype")

             self.post_init()



       def  A_   (     self):

             """simple docstring"""





             if not isinstance(self.llm_inta_threshold     ,lowercase):
                   raise ValueError("llm_int8_threshold must be a float")

             if self.llm_inta_skip_modules is not None and not isinstance(self.llm_inta_skip_modules     ,lowercase):
                   raise ValueError("llm_int8_skip_modules must be a list of strings")
             if not isinstance(self.llm_inta_enable_fpaa_cpu_offload     ,lowercase):
                   raise ValueError("llm_int8_enable_fp32_cpu_offload must be a boolean")

             if not isinstance(self.llm_inta_has_fpaa_weight     ,lowercase):
                   raise ValueError("llm_int8_has_fp16_weight must be a boolean")

             if self.bnb_abit_compute_dtype is not None and not isinstance(self.bnb_abit_compute_dtype     ,torch.dtype):
                   raise ValueError("bnb_4bit_compute_dtype must be torch.dtype")

             if not isinstance(self.bnb_abit_quant_type     ,lowercase):
                   raise ValueError("bnb_4bit_quant_type must be a string")

             if not isinstance(self.bnb_abit_use_double_quant     ,lowercase):
                   raise ValueError("bnb_4bit_use_double_quant must be a boolean")

             if self.load_in_abit and not version.parse(importlib.metadata.version("bitsandbytes")) >= version.parse(
                 "0.39.0"):
                   raise ValueError(
                       "4 bit quantization requires bitsandbytes>=0.39.0 - please upgrade your bitsandbytes version")



       def  A_   (     self):

             """simple docstring"""





             return self.load_in_abit or self.load_in_abit



       def  A_   (     self):

             """simple docstring"""





             if self.load_in_abit:
                   return "llm_int8"
             elif self.load_in_abit and self.bnb_abit_quant_type == "fp4":
                   return "fp4"
             elif self.load_in_abit and self.bnb_abit_quant_type == "nf4":
                   return "nf4"
             else:
                   return None



       @classmethod
       def  A_   (     cls     ,lowercase     ,lowercase     ,**lowercase):

             """simple docstring"""





             UpperCAmelCase_  :	Optional[int]				      =		cls(**lowercase)

             UpperCAmelCase_  :	Union[str, Any]				      =		[]
             for key, value in kwargs.items():
                   if hasattr(lowercase     ,lowercase):
                         setattr(lowercase     ,lowercase     ,lowercase)
                         to_remove.append(lowercase)
             for key in to_remove:
                   kwargs.pop(lowercase     ,lowercase)

             if return_unused_kwargs:
                   return config, kwargs
             else:
                   return config



       def  A_   (     self     ,lowercase):

             """simple docstring"""





             with open(lowercase     ,"w"     ,encoding="utf-8") as writer:
                   UpperCAmelCase_  :	Any				      =		self.to_dict()
                   UpperCAmelCase_  :	Tuple				      =		json.dumps(lowercase     ,indent=2     ,sort_keys=lowercase) + "\n"

                   writer.write(lowercase)



       def  A_   (     self):

             """simple docstring"""





             UpperCAmelCase_  :	int				      =		copy.deepcopy(self.__dict__)
             UpperCAmelCase_  :	List[str]				      =		str(output["bnb_4bit_compute_dtype"]).split(".")[1]

             return output



       def __repr__(     self):

             """simple docstring"""





             return F"""{self.__class__.__name__} {self.to_json_string()}"""



       def  A_   (     self     ,lowercase = True):

             """simple docstring"""





             if use_diff is True:
                   UpperCAmelCase_  :	Any				      =		self.to_diff_dict()
             else:
                   UpperCAmelCase_  :	Dict				      =		self.to_dict()
             return json.dumps(lowercase     ,indent=2     ,sort_keys=lowercase) + "\n"



       def  A_   (     self):

             """simple docstring"""





             UpperCAmelCase_  :	Union[str, Any]				      =		self.to_dict()

             # get the default config dict
             UpperCAmelCase_  :	Tuple				      =		BitsAndBytesConfig().to_dict()

             UpperCAmelCase_  :	Union[str, Any]				      =		{}

             # only serialize values that differ from the default config
             for key, value in config_dict.items():
                   if value != default_config_dict[key]:
                         UpperCAmelCase_  :	List[str]				      =		value

             return serializable_config_dict





import argparse
import logging
import pickle
import random
import time

import numpy as np

from transformers import BertTokenizer, GPTaTokenizer, RobertaTokenizer


logging.basicConfig(
    format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''', datefmt='''%m/%d/%Y %H:%M:%S''', level=logging.INFO
)
__lowerCamelCase         =			logging.getLogger(__name__)







def    _snake_case (       )     ->     Dict:






      '''simple docstring'''







      UpperCAmelCase_  :	Any				      =		argparse.ArgumentParser(
          description="Preprocess the data to avoid re-doing it several times by (tokenization + token_to_ids)."    )
      parser.add_argument("--file_path"					,  type=__snake_case					,  default="data/dump.txt"					,  help="The path to the data."    )
      parser.add_argument("--tokenizer_type"					,  type=__snake_case					,  default="bert"					,  choices=["bert", "roberta", "gpt2"]    )
      parser.add_argument("--tokenizer_name"					,  type=__snake_case					,  default="bert-base-uncased"					,  help="The tokenizer to use."    )
      parser.add_argument("--dump_file"					,  type=__snake_case					,  default="data/dump"					,  help="The dump file prefix."    )
      UpperCAmelCase_  :	str				      =		parser.parse_args()

      logger.info(F"""Loading Tokenizer ({args.tokenizer_name})"""    )
      if args.tokenizer_type == "bert":
            UpperCAmelCase_  :	int				      =		BertTokenizer.from_pretrained(args.tokenizer_name    )
            UpperCAmelCase_  :	Optional[Any]				      =		tokenizer.special_tokens_map["cls_token"]  # `[CLS]`
            UpperCAmelCase_  :	Dict				      =		tokenizer.special_tokens_map["sep_token"]  # `[SEP]`
      elif args.tokenizer_type == "roberta":
            UpperCAmelCase_  :	str				      =		RobertaTokenizer.from_pretrained(args.tokenizer_name    )
            UpperCAmelCase_  :	int				      =		tokenizer.special_tokens_map["cls_token"]  # `<s>`
            UpperCAmelCase_  :	Optional[Any]				      =		tokenizer.special_tokens_map["sep_token"]  # `</s>`
      elif args.tokenizer_type == "gpt2":
            UpperCAmelCase_  :	Tuple				      =		GPTaTokenizer.from_pretrained(args.tokenizer_name    )
            UpperCAmelCase_  :	List[Any]				      =		tokenizer.special_tokens_map["bos_token"]  # `<|endoftext|>`
            UpperCAmelCase_  :	List[str]				      =		tokenizer.special_tokens_map["eos_token"]  # `<|endoftext|>`

      logger.info(F"""Loading text from {args.file_path}"""    )
      with open(args.file_path					,  "r"					,  encoding="utf8"    ) as fp:
            UpperCAmelCase_  :	Union[str, Any]				      =		fp.readlines()

      logger.info("Start encoding"    )
      logger.info(F"""{len(__snake_case    )} examples to process."""    )

      UpperCAmelCase_  :	List[str]				      =		[]
      UpperCAmelCase_  :	str				      =		0
      UpperCAmelCase_  :	Union[str, Any]				      =		1_0_0_0_0
      UpperCAmelCase_  :	int				      =		time.time()
      for text in data:
            UpperCAmelCase_  :	str				      =		F"""{bos} {text.strip()} {sep}"""
            UpperCAmelCase_  :	Any				      =		tokenizer.encode(__snake_case					,  add_special_tokens=__snake_case    )
            rslt.append(__snake_case    )

            iter += 1
            if iter % interval == 0:
                  UpperCAmelCase_  :	List[str]				      =		time.time()
                  logger.info(F"""{iter} examples processed. - {(end-start):.2f}s/{interval}expl"""    )
                  UpperCAmelCase_  :	Optional[Any]				      =		time.time()
      logger.info("Finished binarization"    )
      logger.info(F"""{len(__snake_case    )} examples processed."""    )

      UpperCAmelCase_  :	List[Any]				      =		F"""{args.dump_file}.{args.tokenizer_name}.pickle"""
      UpperCAmelCase_  :	Optional[int]				      =		tokenizer.vocab_size
      if vocab_size < (1 << 1_6):
            UpperCAmelCase_  :	List[Any]				      =		[np.uintaa(__snake_case    ) for d in rslt]
      else:
            UpperCAmelCase_  :	str				      =		[np.intaa(__snake_case    ) for d in rslt]
      random.shuffle(rslt_    )
      logger.info(F"""Dump to {dp_file}"""    )
      with open(__snake_case					,  "wb"    ) as handle:
            pickle.dump(rslt_					,  __snake_case					,  protocol=pickle.HIGHEST_PROTOCOL    )


if __name__ == "__main__":
   main()
