


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

__lowerCamelCase   	=  logging.get_logger(__name__)

__lowerCamelCase   	=  {'''vocab_file''': '''tokenizer.model'''}

__lowerCamelCase   	=  {
    '''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''',
    },
}
__lowerCamelCase   	=  {
    '''hf-internal-testing/llama-tokenizer''': 2048,
}
__lowerCamelCase   	=  '''▁'''

__lowerCamelCase	,							__lowerCamelCase   	=  '''[INST]''', '''[/INST]'''
__lowerCamelCase	,							__lowerCamelCase   	=  '''<<SYS>>\n''', '''\n<</SYS>>\n\n'''

# fmt: off
__lowerCamelCase   	=  '''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 	a__						(    lowerCAmelCase_     ):
       lowerCamelCase__:  List[str]				     =  VOCAB_FILES_NAMES
       lowerCamelCase__:  List[str]				     =  PRETRAINED_VOCAB_FILES_MAP
       lowerCamelCase__:  int				     =  PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
       lowerCamelCase__:  str				     =  ["""input_ids""", """attention_mask"""]

       def __init__( self   :  Union[str, Any]   ,				lowerCamelCase_   :  Tuple   ,				lowerCamelCase_   :  List[str]="<unk>"   ,				lowerCamelCase_   :  Optional[int]="<s>"   ,				lowerCamelCase_   :  Any="</s>"   ,				lowerCamelCase_   :  Any=None   ,				lowerCamelCase_   :  Optional[Dict[str, Any]] = None   ,				lowerCamelCase_   :  Any=True   ,				lowerCamelCase_   :  List[str]=False   ,				lowerCamelCase_   :  List[str]=False   ,				lowerCamelCase_   :  List[str]=True   ,				**lowerCamelCase_   :  Union[str, Any]   ,				):
            a_     :  str				      =     {} if sp_model_kwargs is None else sp_model_kwargs
            a_     :  Dict				      =     AddedToken(lowerCamelCase_   ,				lstrip=lowerCamelCase_   ,				rstrip=lowerCamelCase_     ) if isinstance(lowerCamelCase_   ,				lowerCamelCase_     ) else bos_token
            a_     :  List[Any]				      =     AddedToken(lowerCamelCase_   ,				lstrip=lowerCamelCase_   ,				rstrip=lowerCamelCase_     ) if isinstance(lowerCamelCase_   ,				lowerCamelCase_     ) else eos_token
            a_     :  Dict				      =     AddedToken(lowerCamelCase_   ,				lstrip=lowerCamelCase_   ,				rstrip=lowerCamelCase_     ) if isinstance(lowerCamelCase_   ,				lowerCamelCase_     ) else unk_token
            a_     :  Any				      =     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"""     )
            a_     :  Union[str, Any]				      =     legacy
            a_     :  Optional[Any]				      =     vocab_file
            a_     :  Dict				      =     add_bos_token
            a_     :  Tuple				      =     add_eos_token
            a_     :  Dict				      =     spm.SentencePieceProcessor(**self.sp_model_kwargs     )
            self.sp_model.Load(lowerCamelCase_     )

       def __getstate__( self   :  Union[str, Any]     ):
            a_     :  int				      =     self.__dict__.copy()
            a_     :  Optional[Any]				      =     None
            a_     :  List[str]				      =     self.sp_model.serialized_model_proto()
            return state

       def __setstate__( self   :  Any   ,				lowerCamelCase_   :  str     ):
            a_     :  Tuple				      =     d
            a_     :  int				      =     spm.SentencePieceProcessor(**self.sp_model_kwargs     )
            self.sp_model.LoadFromSerializedProto(self.sp_model_proto     )

       @property
       def     UpperCAmelCase( self   :  Dict     ):
            return self.sp_model.get_piece_size()

       def     UpperCAmelCase( self   :  Optional[Any]     ):
            a_     :  Union[str, Any]				      =     {self.convert_ids_to_tokens(lowerCamelCase_     ): i for i in range(self.vocab_size     )}
            vocab.update(self.added_tokens_encoder     )
            return vocab

       def     UpperCAmelCase( self   :  int   ,				lowerCamelCase_   :  Any   ,				**lowerCamelCase_   :  Dict     ):
            # Replace the SPIECE_UNDERLINE with a space to make sure SPIECE_UNDERLINE is only used at
            # the beginning of the text
            if not self.legacy:
                 a_     :  Union[str, Any]				      =     SPIECE_UNDERLINE + text.replace(lowerCamelCase_   ,				""" """     )
            return super().tokenize(lowerCamelCase_   ,				**lowerCamelCase_     )

       def     UpperCAmelCase( self   :  int   ,				lowerCamelCase_   :  List[Any]     ):
            if not self.legacy:
                 a_     :  List[Any]				      =     text.startswith(lowerCamelCase_     )
                 if is_first:
                      a_     :  Optional[int]				      =     text[1:]

            a_     :  Tuple				      =     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_     ):
                 a_     :  Tuple				      =     ([tokens[0][1:]] if len(tokens[0]     ) > 1 else []) + tokens[1:]
            return tokens

       def     UpperCAmelCase( self   :  int   ,				lowerCamelCase_   :  List[str]     ):
            return self.sp_model.piece_to_id(lowerCamelCase_     )

       def     UpperCAmelCase( self   :  Dict   ,				lowerCamelCase_   :  Tuple     ):
            a_     :  int				      =     self.sp_model.IdToPiece(lowerCamelCase_     )
            return token

       def     UpperCAmelCase( self   :  Dict   ,				lowerCamelCase_   :  List[str]     ):
            a_     :  Optional[int]				      =     []
            a_     :  str				      =     """"""
            a_     :  Dict				      =     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
                      a_     :  int				      =     True
                      a_     :  str				      =     []
                 else:
                      current_sub_tokens.append(lowerCamelCase_     )
                      a_     :  Tuple				      =     False
            out_string += self.sp_model.decode(lowerCamelCase_     )
            return out_string

       def     UpperCAmelCase( self   :  List[Any]   ,				lowerCamelCase_   :  str   ,				lowerCamelCase_   :  Optional[str] = None     ):
            if not os.path.isdir(lowerCamelCase_     ):
                 logger.error(F'''Vocabulary path ({save_directory}) should be a directory'''     )
                 return
            a_     :  List[Any]				      =     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:
                      a_     :  Optional[Any]				      =     self.sp_model.serialized_model_proto()
                      fi.write(lowerCamelCase_     )

            return (out_vocab_file,)

       def     UpperCAmelCase( self   :  Tuple   ,				lowerCamelCase_   :  List[str]   ,				lowerCamelCase_   :  Optional[Any]=None     ):
            a_     :  Dict				      =     [self.bos_token_id] if self.add_bos_token else []
            a_     :  Any				      =     [self.eos_token_id] if self.add_eos_token else []

            a_     :  List[Any]				      =     bos_token_id + token_ids_a + eos_token_id

            if token_ids_a is not None:
                 a_     :  List[str]				      =     output + bos_token_id + token_ids_a + eos_token_id

            return output

       def     UpperCAmelCase( self   :  Optional[int]   ,				lowerCamelCase_   :  List[int]   ,				lowerCamelCase_   :  Optional[List[int]] = None   ,				lowerCamelCase_   :  bool = False     ):
            if already_has_special_tokens:
                 return super().get_special_tokens_mask(
                     token_ids_a=lowerCamelCase_   ,				token_ids_a=lowerCamelCase_   ,				already_has_special_tokens=lowerCamelCase_     )

            a_     :  Any				      =     [1] if self.add_bos_token else []
            a_     :  Any				      =     [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     UpperCAmelCase( self   :  Optional[int]   ,				lowerCamelCase_   :  List[int]   ,				lowerCamelCase_   :  Optional[List[int]] = None     ):
            a_     :  str				      =     [self.bos_token_id] if self.add_bos_token else []
            a_     :  Dict				      =     [self.eos_token_id] if self.add_eos_token else []

            a_     :  List[Any]				      =     [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     UpperCAmelCase( self   :  int   ,				lowerCamelCase_   :  "Conversation"     ):
            a_     :  int				      =     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...)"""     )

            a_     :  List[int]				      =     []
            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]:
                      a_     :  Optional[int]				      =     (
                          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]:
                 a_     :  Optional[Any]				      =     (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







import unittest

from transformers import SpeechaTextaConfig
from transformers.testing_utils import is_torch_available, require_torch, torch_device

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


if is_torch_available():
       import torch

       from transformers.models.speech_to_text_a.modeling_speech_to_text_a import (
           SpeechaTextaDecoder,
           SpeechaTextaForCausalLM,
       )


@require_torch
class 	a__						:

       def __init__( self   :  Dict   ,				lowerCamelCase_   :  Any   ,				lowerCamelCase_   :  Dict=9_9   ,				lowerCamelCase_   :  List[Any]=1_3   ,				lowerCamelCase_   :  Dict=1_6   ,				lowerCamelCase_   :  Any=7   ,				lowerCamelCase_   :  Dict=True   ,				lowerCamelCase_   :  List[str]=True   ,				lowerCamelCase_   :  Tuple=True   ,				lowerCamelCase_   :  Any=False   ,				lowerCamelCase_   :  Union[str, Any]=True   ,				lowerCamelCase_   :  int=2   ,				lowerCamelCase_   :  Tuple=3_2   ,				lowerCamelCase_   :  int=4   ,				lowerCamelCase_   :  Dict=4   ,				lowerCamelCase_   :  str=3_0   ,				lowerCamelCase_   :  Optional[int]=0   ,				lowerCamelCase_   :  Optional[Any]=1   ,				lowerCamelCase_   :  Any=2   ,				lowerCamelCase_   :  Optional[int]=None   ,				):
            a_     :  Optional[Any]				      =     parent
            a_     :  Union[str, Any]				      =     batch_size
            a_     :  Tuple				      =     decoder_seq_length
            # For common tests
            a_     :  Union[str, Any]				      =     self.decoder_seq_length
            a_     :  List[str]				      =     is_training
            a_     :  int				      =     use_attention_mask
            a_     :  Dict				      =     use_labels

            a_     :  List[str]				      =     vocab_size
            a_     :  Optional[int]				      =     d_model
            a_     :  str				      =     d_model
            a_     :  Any				      =     decoder_layers
            a_     :  Tuple				      =     decoder_layers
            a_     :  Dict				      =     decoder_ffn_dim
            a_     :  List[str]				      =     decoder_attention_heads
            a_     :  List[Any]				      =     decoder_attention_heads
            a_     :  List[str]				      =     eos_token_id
            a_     :  Any				      =     bos_token_id
            a_     :  List[Any]				      =     pad_token_id
            a_     :  Dict				      =     decoder_start_token_id
            a_     :  Tuple				      =     use_cache
            a_     :  List[Any]				      =     max_position_embeddings

            a_     :  List[str]				      =     None
            a_     :  Any				      =     decoder_seq_length
            a_     :  List[Any]				      =     2
            a_     :  Optional[Any]				      =     1

       def     UpperCAmelCase( self   :  str     ):
            a_     :  Any				      =     ids_tensor([self.batch_size, self.decoder_seq_length]   ,				self.vocab_size     )

            a_     :  Any				      =     None
            if self.use_attention_mask:
                 a_     :  Optional[Any]				      =     ids_tensor([self.batch_size, self.decoder_seq_length]   ,				vocab_size=2     )

            a_     :  Tuple				      =     None
            if self.use_labels:
                 a_     :  int				      =     ids_tensor([self.batch_size, self.decoder_seq_length]   ,				self.vocab_size     )

            a_     :  int				      =     SpeechaTextaConfig(
                vocab_size=self.vocab_size   ,				d_model=self.d_model   ,				decoder_layers=self.decoder_layers   ,				decoder_ffn_dim=self.decoder_ffn_dim   ,				decoder_attention_heads=self.decoder_attention_heads   ,				eos_token_id=self.eos_token_id   ,				bos_token_id=self.bos_token_id   ,				use_cache=self.use_cache   ,				pad_token_id=self.pad_token_id   ,				decoder_start_token_id=self.decoder_start_token_id   ,				max_position_embeddings=self.max_position_embeddings   ,				)

            return (
                config,
                input_ids,
                attention_mask,
                lm_labels,
            )

       def     UpperCAmelCase( self   :  Tuple   ,				lowerCamelCase_   :  List[str]   ,				lowerCamelCase_   :  str   ,				lowerCamelCase_   :  Optional[int]   ,				lowerCamelCase_   :  List[str]   ,				):
            a_     :  List[Any]				      =     True
            a_     :  Optional[int]				      =     SpeechaTextaDecoder(config=lowerCamelCase_     ).to(lowerCamelCase_     ).eval()
            a_     :  Optional[int]				      =     input_ids[:2]

            input_ids[input_ids == 0] += 1
            # first forward pass
            a_     :  Union[str, Any]				      =     model(lowerCamelCase_   ,				use_cache=lowerCamelCase_     )
            a_     :  Tuple				      =     model(lowerCamelCase_     )
            a_     :  str				      =     model(lowerCamelCase_   ,				use_cache=lowerCamelCase_     )

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

            a_     :  Tuple				      =     outputs["""past_key_values"""]

            # create hypothetical next token and extent to next_input_ids
            a_     :  Any				      =     ids_tensor((2, 1)   ,				config.vocab_size - 1     ) + 1

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

            print(lowerCamelCase_     )

            a_     :  Any				      =     model(lowerCamelCase_     )["""last_hidden_state"""]
            a_     :  int				      =     model(lowerCamelCase_   ,				past_key_values=lowerCamelCase_     )["""last_hidden_state"""]

            # select random slice
            a_     :  Tuple				      =     ids_tensor((1,)   ,				output_from_past.shape[-1]     ).item()
            a_     :  List[str]				      =     output_from_no_past[:, next_input_ids.shape[-1] - 1, random_slice_idx].detach()
            a_     :  List[Any]				      =     output_from_past[:, 0, random_slice_idx].detach()

            # test that outputs are equal for slice
            assert torch.allclose(lowerCamelCase_   ,				lowerCamelCase_   ,				atol=1E-3     )

       def     UpperCAmelCase( self   :  Any     ):
            a_     :  List[Any]				      =     self.prepare_config_and_inputs()
            (
                (
                a_
            )      ,      (
                a_
            )      ,      (
                a_
            )      ,      (
                a_
            )      ,      
            )     :  Optional[int]				      =     config_and_inputs

            a_     :  Tuple				      =     {
                """input_ids""": input_ids,
                """attention_mask""": attention_mask,
            }
            return config, inputs_dict


@require_torch
class 	a__						(    lowerCAmelCase_    ,							lowerCAmelCase_    ,							lowerCAmelCase_    ,							unittest.TestCase     ):
       lowerCamelCase__:  int				     =  (SpeechaTextaDecoder, SpeechaTextaForCausalLM) if is_torch_available() else ()
       lowerCamelCase__:  int				     =  (SpeechaTextaForCausalLM,) if is_torch_available() else ()
       lowerCamelCase__:  int				     =  {"""text-generation""": SpeechaTextaForCausalLM} if is_torch_available() else {}
       lowerCamelCase__:  Dict				     =  True
       lowerCamelCase__:  List[Any]				     =  False

       def     UpperCAmelCase( self   :  List[str]   ,				):
            a_     :  Optional[int]				      =     SpeechaTextaStandaloneDecoderModelTester(self   ,				is_training=lowerCamelCase_     )
            a_     :  str				      =     ConfigTester(self   ,				config_class=lowerCamelCase_     )

       def     UpperCAmelCase( self   :  Optional[Any]     ):
            pass

       def     UpperCAmelCase( self   :  Optional[Any]     ):
            pass

       def     UpperCAmelCase( self   :  Optional[Any]     ):
            pass

       def     UpperCAmelCase( self   :  str     ):
            self.config_tester.run_common_tests()

       def     UpperCAmelCase( self   :  Dict     ):
            a_     :  int				      =     self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_decoder_model_past(*lowerCamelCase_     )

       def     UpperCAmelCase( self   :  int     ):
            return



