



"""simple docstring"""





import json
import os
import tempfile

import datasets
from datasets.arrow_writer import ArrowWriter
from datasets.features import ArrayaD
from utils import generate_examples, get_duration


SCREAMING_SNAKE_CASE				:     List[str]          =	(3_0, 4_8_7)
SCREAMING_SNAKE_CASE				:     List[str]          =	(3_6, 1_0_2_4)
SCREAMING_SNAKE_CASE				:     Tuple          =	(1_0_0, 1_0_0)
SCREAMING_SNAKE_CASE				:     Union[str, Any]          =	1_0_0

SCREAMING_SNAKE_CASE				:     Tuple          =	datasets.Features(
    {'''text''': ArrayaD(SHAPE_TEST_1, dtype='''float32'''), '''image''': ArrayaD(SHAPE_TEST_2, dtype='''float32''')}
)

SCREAMING_SNAKE_CASE    ,					SCREAMING_SNAKE_CASE				:     Union[str, Any]          =	os.path.split(__file__)
SCREAMING_SNAKE_CASE				:     Dict          =	os.path.join(RESULTS_BASEPATH, '''results''', RESULTS_FILENAME.replace('''.py''', '''.json'''))






@get_duration
def 	__UpperCAmelCase					(       snake_case_  :  Any   ,	snake_case_  :  Tuple   ,	snake_case_  :  Any   )							->	Optional[int]:






   """simple docstring"""


   with ArrowWriter(features=snake_case_   ,	path=os.path.join(snake_case_   ,	"""beta.arrow"""   )   ) as writer:
      for key, record in dummy_data:
         _lowerCAmelCase					     =		my_features.encode_example(snake_case_   )
         writer.write(snake_case_   )
      _lowerCAmelCase     ,						_lowerCAmelCase					     =		writer.finalize()






@get_duration
def 	__UpperCAmelCase					(       snake_case_  :  Dict   ,	snake_case_  :  List[str]   )							->	List[str]:






   """simple docstring"""


   _lowerCAmelCase					     =		datasets.Dataset.from_file(
       filename=os.path.join(snake_case_   ,	"""beta.arrow"""   )   ,	info=datasets.DatasetInfo(features=snake_case_   )   )
   for _ in dataset:
      pass






@get_duration
def 	__UpperCAmelCase					(       snake_case_  :  List[str]   ,	snake_case_  :  Tuple   )							->	Optional[Any]:






   """simple docstring"""


   _lowerCAmelCase					     =		datasets.Dataset.from_file(
       filename=os.path.join(snake_case_   ,	"""beta.arrow"""   )   ,	info=datasets.DatasetInfo(features=snake_case_   )   )
   dataset.set_format("""numpy"""   )
   for _ in dataset:
      pass






@get_duration
def 	__UpperCAmelCase					(       snake_case_  :  Optional[int]   ,	snake_case_  :  Union[str, Any]   )							->	str:






   """simple docstring"""


   _lowerCAmelCase					     =		10
   _lowerCAmelCase					     =		datasets.Dataset.from_file(
       filename=os.path.join(snake_case_   ,	"""beta.arrow"""   )   ,	info=datasets.DatasetInfo(features=snake_case_   )   )
   for i in range(0   ,	len(snake_case_   )   ,	snake_case_   ):
      _lowerCAmelCase					     =		dataset[i : i + batch_size]






@get_duration
def 	__UpperCAmelCase					(       snake_case_  :  List[str]   ,	snake_case_  :  Union[str, Any]   )							->	int:






   """simple docstring"""


   _lowerCAmelCase					     =		10
   _lowerCAmelCase					     =		datasets.Dataset.from_file(
       filename=os.path.join(snake_case_   ,	"""beta.arrow"""   )   ,	info=datasets.DatasetInfo(features=snake_case_   )   )
   dataset.set_format("""numpy"""   )
   for i in range(0   ,	len(snake_case_   )   ,	snake_case_   ):
      _lowerCAmelCase					     =		dataset[i : i + batch_size]






@get_duration
def 	__UpperCAmelCase					(       snake_case_  :  str   ,	snake_case_  :  Any   )							->	List[str]:






   """simple docstring"""


   _lowerCAmelCase					     =		datasets.Dataset.from_file(
       filename=os.path.join(snake_case_   ,	"""beta.arrow"""   )   ,	info=datasets.DatasetInfo(features=snake_case_   )   )
   for col in feats:
      _lowerCAmelCase					     =		dataset[col]






@get_duration
def 	__UpperCAmelCase					(       snake_case_  :  Dict   ,	snake_case_  :  int   )							->	Tuple:






   """simple docstring"""


   _lowerCAmelCase					     =		datasets.Dataset.from_file(
       filename=os.path.join(snake_case_   ,	"""beta.arrow"""   )   ,	info=datasets.DatasetInfo(features=snake_case_   )   )
   dataset.set_format("""numpy"""   )
   for col in feats:
      _lowerCAmelCase					     =		dataset[col]






def 	__UpperCAmelCase					(       )							->	Tuple:






   """simple docstring"""


   _lowerCAmelCase					     =		{}
   _lowerCAmelCase					     =		(
       read_unformated,
       read_formatted_as_numpy,
       read_batch_unformated,
       read_batch_formatted_as_numpy,
       read_col_unformated,
       read_col_formatted_as_numpy,
   )
   with tempfile.TemporaryDirectory() as tmp_dir:
      _lowerCAmelCase					     =		datasets.Features({"""image""": ArrayaD(snake_case_   ,	dtype="""float32"""   )}   )
      _lowerCAmelCase					     =		generate_examples(features=snake_case_   ,	num_examples=snake_case_   )
      _lowerCAmelCase					     =		write(snake_case_   ,	snake_case_   ,	snake_case_   )
      for read_func in read_functions:
         _lowerCAmelCase					     =		read_func(snake_case_   ,	snake_case_   )

   with tempfile.TemporaryDirectory() as tmp_dir:
      # don't use fixed length for fair comparison
      # feats = datasets.Features(
      #     {"image": datasets.Sequence(datasets.Sequence(datasets.Value("float32"), SPEED_TEST_SHAPE[1]), SPEED_TEST_SHAPE[0])}
      # )
      _lowerCAmelCase					     =		datasets.Features({"""image""": datasets.Sequence(datasets.Sequence(datasets.Value("""float32"""   )   )   )}   )
      _lowerCAmelCase					     =		generate_examples(
          features=snake_case_   ,	num_examples=snake_case_   ,	seq_shapes={"""image""": SPEED_TEST_SHAPE}   )
      _lowerCAmelCase					     =		write(snake_case_   ,	snake_case_   ,	snake_case_   )
      for read_func in read_functions:
         _lowerCAmelCase					     =		read_func(snake_case_   ,	snake_case_   )

   with tempfile.TemporaryDirectory() as tmp_dir:
      # don't use fixed length for fair comparison
      # feats = datasets.Features(
      #     {"image": datasets.Sequence(datasets.Value("float32"), SPEED_TEST_SHAPE[0] * SPEED_TEST_SHAPE[1])}
      # )
      _lowerCAmelCase					     =		datasets.Features({"""image""": datasets.Sequence(datasets.Value("""float32"""   )   )}   )
      _lowerCAmelCase					     =		generate_examples(
          features=snake_case_   ,	num_examples=snake_case_   ,	seq_shapes={"""image""": [SPEED_TEST_SHAPE[0] * SPEED_TEST_SHAPE[1]]}   ,	)
      _lowerCAmelCase					     =		write(snake_case_   ,	snake_case_   ,	snake_case_   )
      for read_func in read_functions:
         _lowerCAmelCase					     =		read_func(snake_case_   ,	snake_case_   )

   with open(snake_case_   ,	"""wb"""   ) as f:
      f.write(json.dumps(snake_case_   ).encode("""utf-8"""   )   )


if __name__ == "__main__":  # useful to run the profiler
  benchmark_array_xd()




"""simple docstring"""





import os
from shutil import copyfile
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple

import sentencepiece as spm

from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...utils import logging


if TYPE_CHECKING:
  from transformers.pipelines.conversational import Conversation

SCREAMING_SNAKE_CASE				:     Optional[int]          =	logging.get_logger(__name__)

SCREAMING_SNAKE_CASE				:     List[str]          =	{'''vocab_file''': '''tokenizer.model'''}

SCREAMING_SNAKE_CASE				:     str          =	{
    '''vocab_file''': {
        '''hf-internal-testing/llama-tokenizer''': '''https://huggingface.co/hf-internal-testing/llama-tokenizer/resolve/main/tokenizer.model''',
    },
    '''tokenizer_file''': {
        '''hf-internal-testing/llama-tokenizer''': '''https://huggingface.co/hf-internal-testing/llama-tokenizer/resolve/main/tokenizer_config.json''',
    },
}
SCREAMING_SNAKE_CASE				:     Tuple          =	{
    '''hf-internal-testing/llama-tokenizer''': 2_0_4_8,
}
SCREAMING_SNAKE_CASE				:     Tuple          =	'''▁'''

SCREAMING_SNAKE_CASE    ,					SCREAMING_SNAKE_CASE				:     Optional[int]          =	'''[INST]''', '''[/INST]'''
SCREAMING_SNAKE_CASE    ,					SCREAMING_SNAKE_CASE				:     Union[str, Any]          =	'''<<SYS>>\n''', '''\n<</SYS>>\n\n'''

# fmt: off
SCREAMING_SNAKE_CASE				:     Optional[Any]          =	'''You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your\
answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure\
that your responses are socially unbiased and positive in nature.

If a question does not make any sense, or is not factually coherent, explain why instead of answering something not\
correct. If you don\'t know the answer to a question, please don\'t share false information.'''


class       __lowerCamelCase	(   __lowercase    ):
   __UpperCamelCase									=   VOCAB_FILES_NAMES
   __UpperCamelCase									=   PRETRAINED_VOCAB_FILES_MAP
   __UpperCamelCase									=   PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
   __UpperCamelCase									=   ['input_ids', 'attention_mask']







   def __init__(self       ,	lowerCamelCase       ,	lowerCamelCase="<unk>"       ,	lowerCamelCase="<s>"       ,	lowerCamelCase="</s>"       ,	lowerCamelCase=None       ,	lowerCamelCase = None       ,	lowerCamelCase=True       ,	lowerCamelCase=False       ,	lowerCamelCase=False       ,	lowerCamelCase=True       ,	**lowerCamelCase       ,	):




      '''simple docstring'''




      _lowerCAmelCase					     =		{} if sp_model_kwargs is None else sp_model_kwargs
      _lowerCAmelCase					     =		AddedToken(lowerCamelCase       ,	lstrip=lowerCamelCase       ,	rstrip=lowerCamelCase				) if isinstance(lowerCamelCase       ,	lowerCamelCase				) else bos_token
      _lowerCAmelCase					     =		AddedToken(lowerCamelCase       ,	lstrip=lowerCamelCase       ,	rstrip=lowerCamelCase				) if isinstance(lowerCamelCase       ,	lowerCamelCase				) else eos_token
      _lowerCAmelCase					     =		AddedToken(lowerCamelCase       ,	lstrip=lowerCamelCase       ,	rstrip=lowerCamelCase				) if isinstance(lowerCamelCase       ,	lowerCamelCase				) else unk_token
      _lowerCAmelCase					     =		AddedToken(lowerCamelCase       ,	lstrip=lowerCamelCase       ,	rstrip=lowerCamelCase				) if isinstance(lowerCamelCase       ,	lowerCamelCase				) else pad_token
      super().__init__(
          bos_token=lowerCamelCase       ,	eos_token=lowerCamelCase       ,	unk_token=lowerCamelCase       ,	pad_token=lowerCamelCase       ,	add_bos_token=lowerCamelCase       ,	add_eos_token=lowerCamelCase       ,	sp_model_kwargs=self.sp_model_kwargs       ,	clean_up_tokenization_spaces=lowerCamelCase       ,	legacy=lowerCamelCase       ,	**lowerCamelCase       ,	)
      if legacy:
         logger.warning_once(
             f"""You are using the legacy behaviour of the {self.__class__}. This means that tokens that come after special tokens will not be properly handled. We recommend you to"""
             """ read the related pull request available at https://github.com/huggingface/transformers/pull/24565"""				)
      _lowerCAmelCase					     =		legacy
      _lowerCAmelCase					     =		vocab_file
      _lowerCAmelCase					     =		add_bos_token
      _lowerCAmelCase					     =		add_eos_token
      _lowerCAmelCase					     =		spm.SentencePieceProcessor(**self.sp_model_kwargs				)
      self.sp_model.Load(lowerCamelCase				)







   def __getstate__(self				):




      '''simple docstring'''




      _lowerCAmelCase					     =		self.__dict__.copy()
      _lowerCAmelCase					     =		None
      _lowerCAmelCase					     =		self.sp_model.serialized_model_proto()
      return state







   def __setstate__(self       ,	lowerCamelCase				):




      '''simple docstring'''




      _lowerCAmelCase					     =		d
      _lowerCAmelCase					     =		spm.SentencePieceProcessor(**self.sp_model_kwargs				)
      self.sp_model.LoadFromSerializedProto(self.sp_model_proto				)







   @property
   def 							A__						(self				):




      '''simple docstring'''




      return self.sp_model.get_piece_size()







   def 							A__						(self				):




      '''simple docstring'''




      _lowerCAmelCase					     =		{self.convert_ids_to_tokens(lowerCamelCase				): i for i in range(self.vocab_size				)}
      vocab.update(self.added_tokens_encoder				)
      return vocab







   def 							A__						(self       ,	lowerCamelCase       ,	**lowerCamelCase				):




      '''simple docstring'''




      if not self.legacy:
         _lowerCAmelCase					     =		SPIECE_UNDERLINE + text.replace(lowerCamelCase       ,	""" """				)
      return super().tokenize(lowerCamelCase       ,	**lowerCamelCase				)







   def 							A__						(self       ,	lowerCamelCase				):




      '''simple docstring'''




      if not self.legacy:
         _lowerCAmelCase					     =		text.startswith(lowerCamelCase				)
         if is_first:
            _lowerCAmelCase					     =		text[1:]

      _lowerCAmelCase					     =		self.sp_model.encode(lowerCamelCase       ,	out_type=lowerCamelCase				)

      if not self.legacy and not is_first and not text.startswith(""" """				) and tokens[0].startswith(lowerCamelCase				):
         _lowerCAmelCase					     =		([tokens[0][1:]] if len(tokens[0]				) > 1 else []) + tokens[1:]
      return tokens







   def 							A__						(self       ,	lowerCamelCase				):




      '''simple docstring'''




      return self.sp_model.piece_to_id(lowerCamelCase				)







   def 							A__						(self       ,	lowerCamelCase				):




      '''simple docstring'''




      _lowerCAmelCase					     =		self.sp_model.IdToPiece(lowerCamelCase				)
      return token







   def 							A__						(self       ,	lowerCamelCase				):




      '''simple docstring'''




      _lowerCAmelCase					     =		[]
      _lowerCAmelCase					     =		""""""
      _lowerCAmelCase					     =		False
      for i, token in enumerate(lowerCamelCase				):
         # make sure that special tokens are not decoded using sentencepiece model
         if token in self.all_special_tokens:
            if not prev_is_special and i != 0:
               out_string += " "
            out_string += self.sp_model.decode(lowerCamelCase				) + token
            _lowerCAmelCase					     =		True
            _lowerCAmelCase					     =		[]
         else:
            current_sub_tokens.append(lowerCamelCase				)
            _lowerCAmelCase					     =		False
      out_string += self.sp_model.decode(lowerCamelCase				)
      return out_string







   def 							A__						(self       ,	lowerCamelCase       ,	lowerCamelCase = None				):




      '''simple docstring'''




      if not os.path.isdir(lowerCamelCase				):
         logger.error(f"""Vocabulary path ({save_directory}) should be a directory"""				)
         return
      _lowerCAmelCase					     =		os.path.join(
          lowerCamelCase       ,	(filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""]				)

      if os.path.abspath(self.vocab_file				) != os.path.abspath(lowerCamelCase				) and os.path.isfile(self.vocab_file				):
         copyfile(self.vocab_file       ,	lowerCamelCase				)
      elif not os.path.isfile(self.vocab_file				):
         with open(lowerCamelCase       ,	"""wb"""				) as fi:
            _lowerCAmelCase					     =		self.sp_model.serialized_model_proto()
            fi.write(lowerCamelCase				)

      return (out_vocab_file,)







   def 							A__						(self       ,	lowerCamelCase       ,	lowerCamelCase=None				):




      '''simple docstring'''




      _lowerCAmelCase					     =		[self.bos_token_id] if self.add_bos_token else []
      _lowerCAmelCase					     =		[self.eos_token_id] if self.add_eos_token else []

      _lowerCAmelCase					     =		bos_token_id + token_ids_a + eos_token_id

      if token_ids_a is not None:
         _lowerCAmelCase					     =		output + bos_token_id + token_ids_a + eos_token_id

      return output







   def 							A__						(self       ,	lowerCamelCase       ,	lowerCamelCase = None       ,	lowerCamelCase = False				):




      '''simple docstring'''




      if already_has_special_tokens:
         return super().get_special_tokens_mask(
             token_ids_a=lowerCamelCase       ,	token_ids_a=lowerCamelCase       ,	already_has_special_tokens=lowerCamelCase				)

      _lowerCAmelCase					     =		[1] if self.add_bos_token else []
      _lowerCAmelCase					     =		[1] if self.add_eos_token else []

      if token_ids_a is None:
         return bos_token_id + ([0] * len(lowerCamelCase				)) + eos_token_id
      return (
          bos_token_id
          + ([0] * len(lowerCamelCase				))
          + eos_token_id
          + bos_token_id
          + ([0] * len(lowerCamelCase				))
          + eos_token_id
      )







   def 							A__						(self       ,	lowerCamelCase       ,	lowerCamelCase = None				):




      '''simple docstring'''




      _lowerCAmelCase					     =		[self.bos_token_id] if self.add_bos_token else []
      _lowerCAmelCase					     =		[self.eos_token_id] if self.add_eos_token else []

      _lowerCAmelCase					     =		[0] * len(bos_token_id + token_ids_a + eos_token_id				)

      if token_ids_a is not None:
         output += [1] * len(bos_token_id + token_ids_a + eos_token_id				)

      return output







   def 							A__						(self       ,	lowerCamelCase				):




      '''simple docstring'''




      _lowerCAmelCase					     =		list(conversation.iter_texts()				)
      if not all([is_user for is_user, msg in dialogue[::2]]				) or not all(
          [not is_user for is_user, msg in dialogue[1::2]]				):
         raise ValueError(
             """The model only supports 'user' and 'assistant' roles, starting with user and alternating (u/a/u/a/u...)"""				)

      _lowerCAmelCase					     =		[]
      if len(conversation.past_user_inputs				) > 0:
         if not conversation.past_user_inputs[0].startswith(lowerCamelCase				) or E_SYS not in conversation.past_user_inputs[0]:
            _lowerCAmelCase					     =		(
                B_SYS + DEFAULT_SYSTEM_PROMPT + E_SYS + conversation.past_user_inputs[0]
            )
      elif not dialogue[0][1].startswith(lowerCamelCase				) or E_SYS not in dialogue[0][1]:
         _lowerCAmelCase					     =		(dialogue[0][0], B_SYS + DEFAULT_SYSTEM_PROMPT + E_SYS + dialogue[0][1])

      dialog_tokens += sum(
          [
              [self.bos_token_id]
              + self.encode(
                  f"""{B_INST} {(prompt[1]).strip()} {E_INST} {(answer[1]).strip()} """       ,	add_special_tokens=lowerCamelCase				)
              + [self.eos_token_id]
              for prompt, answer in zip(dialogue[::2]       ,	dialogue[1::2]				)
          ]       ,	[]       ,	)
      if not (dialogue[-1][0]):
         raise ValueError(f"""Last message must be from user, got {dialogue[-1]["role"]}"""				)
      dialog_tokens += [self.bos_token_id] + self.encode(
          f"""{B_INST} {(dialogue[-1][1]).strip()} {E_INST}"""       ,	add_special_tokens=lowerCamelCase				)
      return dialog_tokens