


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

_snake_case   = logging.get_logger(__name__)

_snake_case   = {"vocab_file": "tokenizer.model"}

_snake_case   = {
    "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",
    },
}
_snake_case   = {
    "hf-internal-testing/llama-tokenizer": 2_0_4_8,
}
_snake_case   = "▁"

_snake_case ,						_snake_case   = "[INST]", "[/INST]"
_snake_case ,						_snake_case   = "<<SYS>>\n", "\n<</SYS>>\n\n"

# fmt: off
_snake_case   = "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_     ):







	"""simple docstring"""





	_UpperCamelCase				: Optional[Any]      =					VOCAB_FILES_NAMES
	_UpperCamelCase				: Any      =					PRETRAINED_VOCAB_FILES_MAP
	_UpperCamelCase				: Any      =					PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
	_UpperCamelCase				: Any      =					['''input_ids''', '''attention_mask''']
	def __init__(			self					: int       ,    _a					: Any       ,    _a					: Optional[Any]="<unk>"       ,    _a					: List[Any]="<s>"       ,    _a					: Optional[int]="</s>"       ,    _a					: Any=None       ,    _a					: Optional[Dict[str, Any]] = None       ,    _a					: Tuple=True       ,    _a					: Tuple=False       ,    _a					: Tuple=False       ,    _a					: Dict=True       ,    **_a					: List[str]       ,    )    ->			Union[str, Any]:
						UpperCAmelCase						:				Union[str, Any]		  =			{} if sp_model_kwargs is None else sp_model_kwargs
						UpperCAmelCase						:				Tuple		  =			AddedToken(_a       ,    lstrip=_a       ,    rstrip=_a				) if isinstance(_a       ,    _a				) else bos_token
						UpperCAmelCase						:				Tuple		  =			AddedToken(_a       ,    lstrip=_a       ,    rstrip=_a				) if isinstance(_a       ,    _a				) else eos_token
						UpperCAmelCase						:				List[str]		  =			AddedToken(_a       ,    lstrip=_a       ,    rstrip=_a				) if isinstance(_a       ,    _a				) else unk_token
						UpperCAmelCase						:				Dict		  =			AddedToken(_a       ,    lstrip=_a       ,    rstrip=_a				) if isinstance(_a       ,    _a				) else pad_token
						super().__init__(
						    bos_token=_a       ,    eos_token=_a       ,    unk_token=_a       ,    pad_token=_a       ,    add_bos_token=_a       ,    add_eos_token=_a       ,    sp_model_kwargs=self.sp_model_kwargs       ,    clean_up_tokenization_spaces=_a       ,    legacy=_a       ,    **_a       ,    )
						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"				)
						UpperCAmelCase						:				Optional[int]		  =			legacy
						UpperCAmelCase						:				List[str]		  =			vocab_file
						UpperCAmelCase						:				List[str]		  =			add_bos_token
						UpperCAmelCase						:				List[str]		  =			add_eos_token
						UpperCAmelCase						:				List[Any]		  =			spm.SentencePieceProcessor(**self.sp_model_kwargs				)
						self.sp_model.Load(_a				)
	def __getstate__(			self					: int				)    ->			Tuple:
						UpperCAmelCase						:				List[Any]		  =			self.__dict__.copy()
						UpperCAmelCase						:				Dict		  =			None
						UpperCAmelCase						:				List[str]		  =			self.sp_model.serialized_model_proto()
						return state
	def __setstate__(			self					: int       ,    _a					: Union[str, Any]				)    ->			Optional[int]:
						UpperCAmelCase						:				Optional[int]		  =			d
						UpperCAmelCase						:				Any		  =			spm.SentencePieceProcessor(**self.sp_model_kwargs				)
						self.sp_model.LoadFromSerializedProto(self.sp_model_proto				)
	@property
	def   _UpperCamelCase    (			self					: Any				)    ->			Tuple:
						return self.sp_model.get_piece_size()
	def   _UpperCamelCase    (			self					: List[str]				)    ->			Tuple:
						UpperCAmelCase						:				Tuple		  =			{self.convert_ids_to_tokens(_a				): i for i in range(self.vocab_size				)}
						vocab.update(self.added_tokens_encoder				)
						return vocab
	def   _UpperCamelCase    (			self					: Optional[int]       ,    _a					: Optional[Any]       ,    **_a					: List[str]				)    ->			List[str]:
						# 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:
											UpperCAmelCase						:				Tuple		  =			SPIECE_UNDERLINE + text.replace(_a       ,    " "				)
						return super().tokenize(_a       ,    **_a				)
	def   _UpperCamelCase    (			self					: Optional[int]       ,    _a					: Union[str, Any]				)    ->			Any:
						if not self.legacy:
											UpperCAmelCase						:				Union[str, Any]		  =			text.startswith(_a				)
											if is_first:
																UpperCAmelCase						:				Dict		  =			text[1:]

						UpperCAmelCase						:				Optional[int]		  =			self.sp_model.encode(_a       ,    out_type=_a				)

						if not self.legacy and not is_first and not text.startswith(" "				) and tokens[0].startswith(_a				):
											UpperCAmelCase						:				List[str]		  =			([tokens[0][1:]] if len(tokens[0]				) > 1 else []) + tokens[1:]
						return tokens
	def   _UpperCamelCase    (			self					: Optional[int]       ,    _a					: Any				)    ->			Any:
						return self.sp_model.piece_to_id(_a				)
	def   _UpperCamelCase    (			self					: Optional[Any]       ,    _a					: Dict				)    ->			Optional[int]:
						UpperCAmelCase						:				Tuple		  =			self.sp_model.IdToPiece(_a				)
						return token
	def   _UpperCamelCase    (			self					: List[Any]       ,    _a					: Any				)    ->			Dict:
						UpperCAmelCase						:				List[Any]		  =			[]
						UpperCAmelCase						:				Tuple		  =			""
						UpperCAmelCase						:				Optional[Any]		  =			False
						for i, token in enumerate(_a				):
											# 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(_a				) + token
																UpperCAmelCase						:				int		  =			True
																UpperCAmelCase						:				Optional[int]		  =			[]
											else:
																current_sub_tokens.append(_a				)
																UpperCAmelCase						:				Tuple		  =			False
						out_string += self.sp_model.decode(_a				)
						return out_string
	def   _UpperCamelCase    (			self					: Union[str, Any]       ,    _a					: List[Any]       ,    _a					: Optional[str] = None				)    ->			Tuple[str]:
						if not os.path.isdir(_a				):
											logger.error(f'Vocabulary path ({save_directory}) should be a directory'				)
											return
						UpperCAmelCase						:				List[str]		  =			os.path.join(
						    _a       ,    (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]				)

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

						return (out_vocab_file,)
	def   _UpperCamelCase    (			self					: Optional[Any]       ,    _a					: List[str]       ,    _a					: List[Any]=None				)    ->			str:
						UpperCAmelCase						:				Optional[Any]		  =			[self.bos_token_id] if self.add_bos_token else []
						UpperCAmelCase						:				Optional[Any]		  =			[self.eos_token_id] if self.add_eos_token else []

						UpperCAmelCase						:				Dict		  =			bos_token_id + token_ids_a + eos_token_id

						if token_ids_a is not None:
											UpperCAmelCase						:				Any		  =			output + bos_token_id + token_ids_a + eos_token_id

						return output
	def   _UpperCamelCase    (			self					: List[str]       ,    _a					: List[int]       ,    _a					: Optional[List[int]] = None       ,    _a					: bool = False				)    ->			List[int]:
						if already_has_special_tokens:
											return super().get_special_tokens_mask(
											    token_ids_a=_a       ,    token_ids_a=_a       ,    already_has_special_tokens=_a				)

						UpperCAmelCase						:				List[str]		  =			[1] if self.add_bos_token else []
						UpperCAmelCase						:				Any		  =			[1] if self.add_eos_token else []

						if token_ids_a is None:
											return bos_token_id + ([0] * len(_a				)) + eos_token_id
						return (
						    bos_token_id
						    + ([0] * len(_a				))
						    + eos_token_id
						    + bos_token_id
						    + ([0] * len(_a				))
						    + eos_token_id
						)
	def   _UpperCamelCase    (			self					: Dict       ,    _a					: List[int]       ,    _a					: Optional[List[int]] = None				)    ->			List[int]:
						UpperCAmelCase						:				Optional[int]		  =			[self.bos_token_id] if self.add_bos_token else []
						UpperCAmelCase						:				Dict		  =			[self.eos_token_id] if self.add_eos_token else []

						UpperCAmelCase						:				Union[str, 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					: Optional[Any]       ,    _a					: "Conversation"				)    ->			List[int]:
						UpperCAmelCase						:				Union[str, Any]		  =			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...)"				)

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







# DISCLAIMER: This file is strongly influenced by https://github.com/yang-song/score_sde_pytorch

from dataclasses import dataclass
from typing import Optional, Tuple, Union

import flax
import jax.numpy as jnp
from jax import random

from ..configuration_utils import ConfigMixin, register_to_config
from .scheduling_utils_flax import FlaxSchedulerMixin, FlaxSchedulerOutput, broadcast_to_shape_from_left




@flax.struct.dataclass
class    A_   :







 """simple docstring"""





 _UpperCamelCase				: Optional[jnp.ndarray]      =					None
 _UpperCamelCase				: Optional[jnp.ndarray]      =					None
 _UpperCamelCase				: Optional[jnp.ndarray]      =					None
 @classmethod
 def   _UpperCamelCase    (			cls					: Union[str, Any]				)    ->			int:
      return cls()




@dataclass
class    A_   ( a_     ):







 """simple docstring"""





 _UpperCamelCase				: ScoreSdeVeSchedulerState
 _UpperCamelCase				: jnp.ndarray
 _UpperCamelCase				: Optional[jnp.ndarray]      =					None




class    A_   ( a_      ,						a_     ):







 """simple docstring"""





 @property
 def   _UpperCamelCase    (			self					: Optional[int]				)    ->			List[str]:
      return True
 @register_to_config
 def __init__(			self					: List[str]       ,    _a					: int = 2_0_0_0       ,    _a					: float = 0.1_5       ,    _a					: float = 0.0_1       ,    _a					: float = 1_3_4_8.0       ,    _a					: float = 1E-5       ,    _a					: int = 1       ,    )    ->			List[Any]:
      pass
 def   _UpperCamelCase    (			self					: int				)    ->			List[Any]:
      UpperCAmelCase						:				str		  =			ScoreSdeVeSchedulerState.create()
      return self.set_sigmas(
          _a       ,    self.config.num_train_timesteps       ,    self.config.sigma_min       ,    self.config.sigma_max       ,    self.config.sampling_eps       ,    )
 def   _UpperCamelCase    (			self					: Optional[int]       ,    _a					: ScoreSdeVeSchedulerState       ,    _a					: int       ,    _a					: Tuple = ()       ,    _a					: float = None				)    ->			ScoreSdeVeSchedulerState:
      UpperCAmelCase						:				Tuple		  =			sampling_eps if sampling_eps is not None else self.config.sampling_eps

      UpperCAmelCase						:				Dict		  =			jnp.linspace(1       ,    _a       ,    _a				)
      return state.replace(timesteps=_a				)
 def   _UpperCamelCase    (			self					: Union[str, Any]       ,    _a					: ScoreSdeVeSchedulerState       ,    _a					: int       ,    _a					: float = None       ,    _a					: float = None       ,    _a					: float = None       ,    )    ->			ScoreSdeVeSchedulerState:
      UpperCAmelCase						:				str		  =			sigma_min if sigma_min is not None else self.config.sigma_min
      UpperCAmelCase						:				Any		  =			sigma_max if sigma_max is not None else self.config.sigma_max
      UpperCAmelCase						:				Any		  =			sampling_eps if sampling_eps is not None else self.config.sampling_eps
      if state.timesteps is None:
           UpperCAmelCase						:				List[Any]		  =			self.set_timesteps(_a       ,    _a       ,    _a				)

      UpperCAmelCase						:				List[Any]		  =			jnp.exp(jnp.linspace(jnp.log(_a				)       ,    jnp.log(_a				)       ,    _a				)				)
      UpperCAmelCase						:				List[str]		  =			jnp.array([sigma_min * (sigma_max / sigma_min) ** t for t in state.timesteps]				)

      return state.replace(discrete_sigmas=_a       ,    sigmas=_a				)
 def   _UpperCamelCase    (			self					: List[Any]       ,    _a					: Optional[int]       ,    _a					: Optional[int]       ,    _a					: Union[str, Any]				)    ->			List[str]:
      return jnp.where(timesteps == 0       ,    jnp.zeros_like(_a				)       ,    state.discrete_sigmas[timesteps - 1]				)
 def   _UpperCamelCase    (			self					: Dict       ,    _a					: ScoreSdeVeSchedulerState       ,    _a					: jnp.ndarray       ,    _a					: int       ,    _a					: jnp.ndarray       ,    _a					: random.KeyArray       ,    _a					: bool = True       ,    )    ->			Union[FlaxSdeVeOutput, Tuple]:
      if state.timesteps is None:
           raise ValueError(
               "`state.timesteps` is not set, you need to run 'set_timesteps' after creating the scheduler"				)

      UpperCAmelCase						:				Union[str, Any]		  =			timestep * jnp.ones(
          sample.shape[0]       ,    )
      UpperCAmelCase						:				int		  =			(timestep * (len(state.timesteps				) - 1)).long()

      UpperCAmelCase						:				List[str]		  =			state.discrete_sigmas[timesteps]
      UpperCAmelCase						:				Optional[int]		  =			self.get_adjacent_sigma(_a       ,    _a       ,    _a				)
      UpperCAmelCase						:				Tuple		  =			jnp.zeros_like(_a				)
      UpperCAmelCase						:				List[Any]		  =			(sigma**2 - adjacent_sigma**2) ** 0.5

      # equation 6 in the paper: the model_output modeled by the network is grad_x log pt(x)
      # also equation 47 shows the analog from SDE models to ancestral sampling methods
      UpperCAmelCase						:				Union[str, Any]		  =			diffusion.flatten()
      UpperCAmelCase						:				Union[str, Any]		  =			broadcast_to_shape_from_left(_a       ,    sample.shape				)
      UpperCAmelCase						:				Tuple		  =			drift - diffusion**2 * model_output

      #  equation 6: sample noise for the diffusion term of
      UpperCAmelCase						:				List[str]		  =			random.split(_a       ,    num=1				)
      UpperCAmelCase						:				str		  =			random.normal(key=_a       ,    shape=sample.shape				)
      UpperCAmelCase						:				Any		  =			sample - drift  # subtract because `dt` is a small negative timestep
      # TODO is the variable diffusion the correct scaling term for the noise?
      UpperCAmelCase						:				str		  =			prev_sample_mean + diffusion * noise  # add impact of diffusion field g

      if not return_dict:
           return (prev_sample, prev_sample_mean, state)

      return FlaxSdeVeOutput(prev_sample=_a       ,    prev_sample_mean=_a       ,    state=_a				)
 def   _UpperCamelCase    (			self					: Any       ,    _a					: ScoreSdeVeSchedulerState       ,    _a					: jnp.ndarray       ,    _a					: jnp.ndarray       ,    _a					: random.KeyArray       ,    _a					: bool = True       ,    )    ->			Union[FlaxSdeVeOutput, Tuple]:
      if state.timesteps is None:
           raise ValueError(
               "`state.timesteps` is not set, you need to run 'set_timesteps' after creating the scheduler"				)

      # For small batch sizes, the paper "suggest replacing norm(z) with sqrt(d), where d is the dim. of z"
      # sample noise for correction
      UpperCAmelCase						:				Optional[int]		  =			random.split(_a       ,    num=1				)
      UpperCAmelCase						:				str		  =			random.normal(key=_a       ,    shape=sample.shape				)

      # compute step size from the model_output, the noise, and the snr
      UpperCAmelCase						:				str		  =			jnp.linalg.norm(_a				)
      UpperCAmelCase						:				Optional[int]		  =			jnp.linalg.norm(_a				)
      UpperCAmelCase						:				int		  =			(self.config.snr * noise_norm / grad_norm) ** 2 * 2
      UpperCAmelCase						:				List[Any]		  =			step_size * jnp.ones(sample.shape[0]				)

      # compute corrected sample: model_output term and noise term
      UpperCAmelCase						:				Optional[Any]		  =			step_size.flatten()
      UpperCAmelCase						:				Union[str, Any]		  =			broadcast_to_shape_from_left(_a       ,    sample.shape				)
      UpperCAmelCase						:				int		  =			sample + step_size * model_output
      UpperCAmelCase						:				int		  =			prev_sample_mean + ((step_size * 2) ** 0.5) * noise

      if not return_dict:
           return (prev_sample, state)

      return FlaxSdeVeOutput(prev_sample=_a       ,    state=_a				)

 def __len__(			self					: Any				)    ->			Optional[int]:
      return self.config.num_train_timesteps



