





import warnings
from typing import List, Optional, Union

import numpy as np
import PIL
import torch
from PIL import Image

from .configuration_utils import ConfigMixin, register_to_config
from .utils import CONFIG_NAME, PIL_INTERPOLATION, deprecate



class 				_UpperCamelCase       (						_a  ):
       _UpperCamelCase					:       List[str]       = CONFIG_NAME

       @register_to_config
       def __init__(		self:			str       , _SCREAMING_SNAKE_CASE:			List[str] = True       , _SCREAMING_SNAKE_CASE:			Optional[Any] = 8       , _SCREAMING_SNAKE_CASE:			Optional[Any] = "lanczos"       , _SCREAMING_SNAKE_CASE:			Dict = True       , _SCREAMING_SNAKE_CASE:			int = False       , )							->			List[Any]:




              """simple docstring"""


              super().__init__()

       @staticmethod
       def lowercase			(		_SCREAMING_SNAKE_CASE:			Tuple		)							->			Tuple:




              """simple docstring"""


              if images.ndim == 3:
                     UpperCamelCase_ 							=	images[None, ...]
              UpperCamelCase_ 							=	(images * 255).round().astype("uint8"		)
              if images.shape[-1] == 1:
                     # special case for grayscale (single channel) images
                     UpperCamelCase_ 							=	[Image.fromarray(image.squeeze()       , mode="L"		) for image in images]
              else:
                     UpperCamelCase_ 							=	[Image.fromarray(_UpperCAmelCase		) for image in images]

              return pil_images

       @staticmethod
       def lowercase			(		_SCREAMING_SNAKE_CASE:			int		)							->			Tuple:




              """simple docstring"""


              if not isinstance(_UpperCAmelCase       , _UpperCAmelCase		):
                     UpperCamelCase_ 							=	[images]
              UpperCamelCase_ 							=	[np.array(_UpperCAmelCase		).astype(np.floataa		) / 2_55.0 for image in images]
              UpperCamelCase_ 							=	np.stack(_UpperCAmelCase       , axis=0		)

              return images

       @staticmethod
       def lowercase			(		_SCREAMING_SNAKE_CASE:			int		)							->			List[str]:




              """simple docstring"""


              if images.ndim == 3:
                     UpperCamelCase_ 							=	images[..., None]

              UpperCamelCase_ 							=	torch.from_numpy(images.transpose(0       , 3       , 1       , 2		)		)
              return images

       @staticmethod
       def lowercase			(		_SCREAMING_SNAKE_CASE:			str		)							->			Tuple:




              """simple docstring"""


              UpperCamelCase_ 							=	images.cpu().permute(0       , 2       , 3       , 1		).float().numpy()
              return images

       @staticmethod
       def lowercase			(		_SCREAMING_SNAKE_CASE:			Dict		)							->			Optional[Any]:




              """simple docstring"""


              return 2.0 * images - 1.0

       @staticmethod
       def lowercase			(		_SCREAMING_SNAKE_CASE:			int		)							->			Optional[int]:




              """simple docstring"""


              return (images / 2 + 0.5).clamp(0       , 1		)

       @staticmethod
       def lowercase			(		_SCREAMING_SNAKE_CASE:			Dict		)							->			str:




              """simple docstring"""


              UpperCamelCase_ 							=	image.convert("RGB"		)
              return image

       def lowercase			(		self:			Union[str, Any]       , _SCREAMING_SNAKE_CASE:			int       , _SCREAMING_SNAKE_CASE:			Union[str, Any] = None       , _SCREAMING_SNAKE_CASE:			List[str] = None       , )							->			Optional[int]:




              """simple docstring"""


              if height is None:
                     UpperCamelCase_ 							=	image.height
              if width is None:
                     UpperCamelCase_ 							=	image.width

              UpperCamelCase_							,			UpperCamelCase_ 							=	(
                  x - x % self.config.vae_scale_factor for x in (width, height)
              )  # resize to integer multiple of vae_scale_factor
              UpperCamelCase_ 							=	image.resize((width, height)       , resample=PIL_INTERPOLATION[self.config.resample]		)
              return image

       def lowercase			(		self:			Dict       , _SCREAMING_SNAKE_CASE:			Optional[Any]       , _SCREAMING_SNAKE_CASE:			int = None       , _SCREAMING_SNAKE_CASE:			int = None       , )							->			str:




              """simple docstring"""


              UpperCamelCase_ 							=	(PIL.Image.Image, np.ndarray, torch.Tensor)
              if isinstance(_UpperCAmelCase       , _UpperCAmelCase		):
                     UpperCamelCase_ 							=	[image]
              elif not (isinstance(_UpperCAmelCase       , _UpperCAmelCase		) and all(isinstance(_UpperCAmelCase       , _UpperCAmelCase		) for i in image		)):
                     raise ValueError(
                         f'''Input is in incorrect format: {[type(_UpperCAmelCase		) for i in image]}. Currently, we only support {", ".join(_UpperCAmelCase		)}'''		)

              if isinstance(image[0]       , PIL.Image.Image		):
                     if self.config.do_convert_rgb:
                            UpperCamelCase_ 							=	[self.convert_to_rgb(_UpperCAmelCase		) for i in image]
                     if self.config.do_resize:
                            UpperCamelCase_ 							=	[self.resize(_UpperCAmelCase       , _UpperCAmelCase       , _UpperCAmelCase		) for i in image]
                     UpperCamelCase_ 							=	self.pil_to_numpy(_UpperCAmelCase		)  # to np
                     UpperCamelCase_ 							=	self.numpy_to_pt(_UpperCAmelCase		)  # to pt

              elif isinstance(image[0]       , np.ndarray		):
                     UpperCamelCase_ 							=	np.concatenate(_UpperCAmelCase       , axis=0		) if image[0].ndim == 4 else np.stack(_UpperCAmelCase       , axis=0		)
                     UpperCamelCase_ 							=	self.numpy_to_pt(_UpperCAmelCase		)
                     UpperCamelCase_							,			UpperCamelCase_							,			UpperCamelCase_							,			UpperCamelCase_ 							=	image.shape
                     if self.config.do_resize and (
                         height % self.config.vae_scale_factor != 0 or width % self.config.vae_scale_factor != 0
                     ):
                            raise ValueError(
                                f'''Currently we only support resizing for PIL image - please resize your numpy array to be divisible by {self.config.vae_scale_factor}'''
                                f'''currently the sizes are {height} and {width}. You can also pass a PIL image instead to use resize option in VAEImageProcessor'''		)

              elif isinstance(image[0]       , torch.Tensor		):
                     UpperCamelCase_ 							=	torch.cat(_UpperCAmelCase       , axis=0		) if image[0].ndim == 4 else torch.stack(_UpperCAmelCase       , axis=0		)
                     UpperCamelCase_							,			UpperCamelCase_							,			UpperCamelCase_							,			UpperCamelCase_ 							=	image.shape

                     # don't need any preprocess if the image is latents
                     if channel == 4:
                            return image

                     if self.config.do_resize and (
                         height % self.config.vae_scale_factor != 0 or width % self.config.vae_scale_factor != 0
                     ):
                            raise ValueError(
                                f'''Currently we only support resizing for PIL image - please resize your pytorch tensor to be divisible by {self.config.vae_scale_factor}'''
                                f'''currently the sizes are {height} and {width}. You can also pass a PIL image instead to use resize option in VAEImageProcessor'''		)

        # expected range [0,1], normalize to [-1,1]
              UpperCamelCase_ 							=	self.config.do_normalize
              if image.min() < 0:
                     warnings.warn(
                         "Passing `image` as torch tensor with value range in [-1,1] is deprecated. The expected value range for image tensor is [0,1] "
                         f'''when passing as pytorch tensor or numpy Array. You passed `image` with value range [{image.min()},{image.max()}]'''       , _UpperCAmelCase       , )
                     UpperCamelCase_ 							=	False

              if do_normalize:
                     UpperCamelCase_ 							=	self.normalize(_UpperCAmelCase		)

              return image



       def lowercase			(		self:			str       , _SCREAMING_SNAKE_CASE:			Optional[Any]       , _SCREAMING_SNAKE_CASE:			Tuple = "pil"       , _SCREAMING_SNAKE_CASE:			int = None       , )							->			Tuple:




              """simple docstring"""


              if not isinstance(_UpperCAmelCase       , torch.Tensor		):
                     raise ValueError(
                         f'''Input for postprocessing is in incorrect format: {type(_UpperCAmelCase		)}. We only support pytorch tensor'''		)
              if output_type not in ["latent", "pt", "np", "pil"]:
                     UpperCamelCase_ 							=	(
                         f'''the output_type {output_type} is outdated and has been set to `np`. Please make sure to set it to one of these instead: '''
                         "`pil`, `np`, `pt`, `latent`"
                     )
                     deprecate("Unsupported output_type"       , "1.0.0"       , _UpperCAmelCase       , standard_warn=_UpperCAmelCase		)
                     UpperCamelCase_ 							=	"np"

              if output_type == "latent":
                     return image

              if do_denormalize is None:
                     UpperCamelCase_ 							=	[self.config.do_normalize] * image.shape[0]

              UpperCamelCase_ 							=	torch.stack(
                  [self.denormalize(image[i]		) if do_denormalize[i] else image[i] for i in range(image.shape[0]		)]		)

              if output_type == "pt":
                     return image

              UpperCamelCase_ 							=	self.pt_to_numpy(_UpperCAmelCase		)

              if output_type == "np":
                     return image

              if output_type == "pil":
                     return self.numpy_to_pil(_UpperCAmelCase		)



class 				_UpperCamelCase       (						_a  ):
       _UpperCamelCase					:       Optional[int]       = CONFIG_NAME

       @register_to_config
       def __init__(		self:			int       , _SCREAMING_SNAKE_CASE:			Dict = True       , _SCREAMING_SNAKE_CASE:			Optional[int] = 8       , _SCREAMING_SNAKE_CASE:			Dict = "lanczos"       , _SCREAMING_SNAKE_CASE:			Tuple = True       , )							->			Tuple:




              """simple docstring"""


              super().__init__()

       @staticmethod
       def lowercase			(		_SCREAMING_SNAKE_CASE:			Union[str, Any]		)							->			Union[str, Any]:




              """simple docstring"""


              if images.ndim == 3:
                     UpperCamelCase_ 							=	images[None, ...]
              UpperCamelCase_ 							=	(images * 255).round().astype("uint8"		)
              if images.shape[-1] == 1:
                     # special case for grayscale (single channel) images
                     UpperCamelCase_ 							=	[Image.fromarray(image.squeeze()       , mode="L"		) for image in images]
              else:
                     UpperCamelCase_ 							=	[Image.fromarray(image[:, :, :3]		) for image in images]

              return pil_images

       @staticmethod
       def lowercase			(		_SCREAMING_SNAKE_CASE:			Any		)							->			int:




              """simple docstring"""


              return image[:, :, 1] * 2**8 + image[:, :, 2]

       def lowercase			(		self:			Union[str, Any]       , _SCREAMING_SNAKE_CASE:			Any		)							->			Optional[int]:




              """simple docstring"""


              if images.ndim == 3:
                     UpperCamelCase_ 							=	images[None, ...]
              UpperCamelCase_ 							=	images[:, :, :, 3:]
              if images.shape[-1] == 6:
                     UpperCamelCase_ 							=	(images_depth * 255).round().astype("uint8"		)
                     UpperCamelCase_ 							=	[
                         Image.fromarray(self.rgblike_to_depthmap(_UpperCAmelCase		)       , mode="I;16"		) for image_depth in images_depth
                     ]
              elif images.shape[-1] == 4:
                     UpperCamelCase_ 							=	(images_depth * 65535.0).astype(np.uintaa		)
                     UpperCamelCase_ 							=	[Image.fromarray(_UpperCAmelCase       , mode="I;16"		) for image_depth in images_depth]
              else:
                     raise Exception("Not supported"		)

              return pil_images



       def lowercase			(		self:			List[str]       , _SCREAMING_SNAKE_CASE:			Optional[Any]       , _SCREAMING_SNAKE_CASE:			Tuple = "pil"       , _SCREAMING_SNAKE_CASE:			Optional[int] = None       , )							->			List[str]:




              """simple docstring"""


              if not isinstance(_UpperCAmelCase       , torch.Tensor		):
                     raise ValueError(
                         f'''Input for postprocessing is in incorrect format: {type(_UpperCAmelCase		)}. We only support pytorch tensor'''		)
              if output_type not in ["latent", "pt", "np", "pil"]:
                     UpperCamelCase_ 							=	(
                         f'''the output_type {output_type} is outdated and has been set to `np`. Please make sure to set it to one of these instead: '''
                         "`pil`, `np`, `pt`, `latent`"
                     )
                     deprecate("Unsupported output_type"       , "1.0.0"       , _UpperCAmelCase       , standard_warn=_UpperCAmelCase		)
                     UpperCamelCase_ 							=	"np"

              if do_denormalize is None:
                     UpperCamelCase_ 							=	[self.config.do_normalize] * image.shape[0]

              UpperCamelCase_ 							=	torch.stack(
                  [self.denormalize(image[i]		) if do_denormalize[i] else image[i] for i in range(image.shape[0]		)]		)

              UpperCamelCase_ 							=	self.pt_to_numpy(_UpperCAmelCase		)

              if output_type == "np":
                     if image.shape[-1] == 6:
                            UpperCamelCase_ 							=	np.stack([self.rgblike_to_depthmap(im[:, :, 3:]		) for im in image]       , axis=0		)
                     else:
                            UpperCamelCase_ 							=	image[:, :, :, 3:]
                     return image[:, :, :, :3], image_depth

              if output_type == "pil":
                     return self.numpy_to_pil(_UpperCAmelCase		), self.numpy_to_depth(_UpperCAmelCase		)
              else:
                     raise Exception(f'''This type {output_type} is not supported'''		)


"""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

lowerCAmelCase_:       Optional[Any]			     =       logging.get_logger(__name__)

lowerCAmelCase_:       Optional[int]			     =       {"vocab_file": "tokenizer.model"}

lowerCAmelCase_:       Optional[int]			     =       {
    "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_:       Optional[int]			     =       {
    "hf-internal-testing/llama-tokenizer": 2_0_4_8,
}
lowerCAmelCase_:       str			     =       "▁"

lowerCAmelCase_     ,				lowerCAmelCase_:       str			     =       "[INST]", "[/INST]"
lowerCAmelCase_     ,				lowerCAmelCase_:       Dict			     =       "<<SYS>>\n", "\n<</SYS>>\n\n"

# fmt: off
lowerCAmelCase_:       List[Any]			     =       "You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your\\nanswers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure\\nthat your responses are socially unbiased and positive in nature.\n\nIf a question does not make any sense, or is not factually coherent, explain why instead of answering something not\\ncorrect. If you don't know the answer to a question, please don't share false information."






class  a__     ( _a						):
   snake_case_				=   VOCAB_FILES_NAMES
   snake_case_				=   PRETRAINED_VOCAB_FILES_MAP
   snake_case_				=   PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
   snake_case_				=   ["input_ids", "attention_mask"]


   def __init__(  self,					_UpperCAmelCase,					_UpperCAmelCase="<unk>",					_UpperCAmelCase="<s>",					_UpperCAmelCase="</s>",					_UpperCAmelCase=None,					_UpperCAmelCase = None,					_UpperCAmelCase=True,					_UpperCAmelCase=False,					_UpperCAmelCase=False,					_UpperCAmelCase=True,					**_UpperCAmelCase,					):
        '''simple docstring'''



        lowercase__								=				{} if sp_model_kwargs is None else sp_model_kwargs
        lowercase__								=				AddedToken(_UpperCAmelCase,					lstrip=_UpperCAmelCase,					rstrip=_UpperCAmelCase	) if isinstance(_UpperCAmelCase,					_UpperCAmelCase	) else bos_token
        lowercase__								=				AddedToken(_UpperCAmelCase,					lstrip=_UpperCAmelCase,					rstrip=_UpperCAmelCase	) if isinstance(_UpperCAmelCase,					_UpperCAmelCase	) else eos_token
        lowercase__								=				AddedToken(_UpperCAmelCase,					lstrip=_UpperCAmelCase,					rstrip=_UpperCAmelCase	) if isinstance(_UpperCAmelCase,					_UpperCAmelCase	) else unk_token
        lowercase__								=				AddedToken(_UpperCAmelCase,					lstrip=_UpperCAmelCase,					rstrip=_UpperCAmelCase	) if isinstance(_UpperCAmelCase,					_UpperCAmelCase	) else pad_token
        super().__init__(
            bos_token=_UpperCAmelCase,					eos_token=_UpperCAmelCase,					unk_token=_UpperCAmelCase,					pad_token=_UpperCAmelCase,					add_bos_token=_UpperCAmelCase,					add_eos_token=_UpperCAmelCase,					sp_model_kwargs=self.sp_model_kwargs,					clean_up_tokenization_spaces=_UpperCAmelCase,					legacy=_UpperCAmelCase,					**_UpperCAmelCase,					)
        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"	)
        lowercase__								=				legacy
        lowercase__								=				vocab_file
        lowercase__								=				add_bos_token
        lowercase__								=				add_eos_token
        lowercase__								=				spm.SentencePieceProcessor(**self.sp_model_kwargs	)
        self.sp_model.Load(_UpperCAmelCase	)


   def __getstate__(  self	):
        '''simple docstring'''



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


   def __setstate__(  self,					_UpperCAmelCase	):
        '''simple docstring'''



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


   @property
   def 						snake_case__						(  self	):
        '''simple docstring'''



        return self.sp_model.get_piece_size()


   def 						snake_case__						(  self	):
        '''simple docstring'''



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


   def 						snake_case__						(  self,					_UpperCAmelCase,					**_UpperCAmelCase	):
        '''simple docstring'''



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


   def 						snake_case__						(  self,					_UpperCAmelCase	):
        '''simple docstring'''



        if not self.legacy:
             lowercase__								=				text.startswith(_UpperCAmelCase	)
             if is_first:
                  lowercase__								=				text[1:]

        lowercase__								=				self.sp_model.encode(_UpperCAmelCase,					out_type=_UpperCAmelCase	)

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


   def 						snake_case__						(  self,					_UpperCAmelCase	):
        '''simple docstring'''



        return self.sp_model.piece_to_id(_UpperCAmelCase	)


   def 						snake_case__						(  self,					_UpperCAmelCase	):
        '''simple docstring'''



        lowercase__								=				self.sp_model.IdToPiece(_UpperCAmelCase	)
        return token


   def 						snake_case__						(  self,					_UpperCAmelCase	):
        '''simple docstring'''



        lowercase__								=				[]
        lowercase__								=				""
        lowercase__								=				False
        for i, token in enumerate(_UpperCAmelCase	):
             # 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(_UpperCAmelCase	) + token
                  lowercase__								=				True
                  lowercase__								=				[]
             else:
                  current_sub_tokens.append(_UpperCAmelCase	)
                  lowercase__								=				False
        out_string += self.sp_model.decode(_UpperCAmelCase	)
        return out_string


   def 						snake_case__						(  self,					_UpperCAmelCase,					_UpperCAmelCase = None	):
        '''simple docstring'''



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

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

        return (out_vocab_file,)


   def 						snake_case__						(  self,					_UpperCAmelCase,					_UpperCAmelCase=None	):
        '''simple docstring'''



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

        lowercase__								=				bos_token_id + token_ids_a + eos_token_id

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

        return output


   def 						snake_case__						(  self,					_UpperCAmelCase,					_UpperCAmelCase = None,					_UpperCAmelCase = False	):
        '''simple docstring'''



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

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

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


   def 						snake_case__						(  self,					_UpperCAmelCase,					_UpperCAmelCase = None	):
        '''simple docstring'''



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

        lowercase__								=				[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 						snake_case__						(  self,					_UpperCAmelCase	):
        '''simple docstring'''



        lowercase__								=				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...)"	)

        lowercase__								=				[]
        if len(conversation.past_user_inputs	) > 0:
             if not conversation.past_user_inputs[0].startswith(_UpperCAmelCase	) or E_SYS not in conversation.past_user_inputs[0]:
                  lowercase__								=				(
                      B_SYS + DEFAULT_SYSTEM_PROMPT + E_SYS + conversation.past_user_inputs[0]
                  )
        elif not dialogue[0][1].startswith(_UpperCAmelCase	) or E_SYS not in dialogue[0][1]:
             lowercase__								=				(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=_UpperCAmelCase	)
                + [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=_UpperCAmelCase	)
        return dialog_tokens




