





from typing import Optional

import torch
import torch.utils.checkpoint
from torch import Tensor, nn
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss

from ...activations import ACTaFN
from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward
from ...modeling_outputs import (
    BaseModelOutputWithNoAttention,
    BaseModelOutputWithPoolingAndNoAttention,
    ImageClassifierOutputWithNoAttention,
)
from ...modeling_utils import PreTrainedModel
from ...utils import logging
from .configuration_regnet import RegNetConfig


lowercase_          =		logging.get_logger(__name__)

# General docstring
lowercase_          =		"""RegNetConfig"""

# Base docstring
lowercase_          =		"""facebook/regnet-y-040"""
lowercase_          =		[1, 1_088, 7, 7]

# Image classification docstring
lowercase_          =		"""facebook/regnet-y-040"""
lowercase_          =		"""tabby, tabby cat"""

lowercase_          =		[
    """facebook/regnet-y-040""",
    # See all regnet models at https://huggingface.co/models?filter=regnet
]
class     SCREAMING_SNAKE_CASE       (nn.Module				):


   def __init__(   self      :    int      ,					a      :    int      ,					a      :    int      ,					a      :    int = 3      ,					a      :    int = 1      ,					a      :    int = 1      ,					a      :    Optional[str] = "relu"      ,					)->       Optional[Any]:





     """simple docstring"""







     super().__init__()
     lowercase__           =  nn.Convad(
         a      ,					a      ,					kernel_size=a      ,					stride=a      ,					padding=kernel_size // 2      ,					groups=a      ,					bias=a      ,					)
     lowercase__           =  nn.BatchNormad(a	)
     lowercase__           =  ACTaFN[activation] if activation is not None else nn.Identity()


   def 	SCREAMING_SNAKE_CASE_							(   self      :    Optional[Any]      ,					a      :    Optional[Any]	)->       Any:





     """simple docstring"""







     lowercase__           =  self.convolution(a	)
     lowercase__           =  self.normalization(a	)
     lowercase__           =  self.activation(a	)
     return hidden_state






class     SCREAMING_SNAKE_CASE       (nn.Module				):


   def __init__(   self      :    List[Any]      ,					a      :    RegNetConfig	)->       Dict:





     """simple docstring"""







     super().__init__()
     lowercase__           =  RegNetConvLayer(
         config.num_channels      ,					config.embedding_size      ,					kernel_size=3      ,					stride=2      ,					activation=config.hidden_act	)
     lowercase__           =  config.num_channels


   def 	SCREAMING_SNAKE_CASE_							(   self      :    Tuple      ,					a      :    Tuple	)->       int:





     """simple docstring"""







     lowercase__           =  pixel_values.shape[1]
     if num_channels != self.num_channels:
       raise ValueError(
           'Make sure that the channel dimension of the pixel values match with the one set in the configuration.'	)
     lowercase__           =  self.embedder(a	)
     return hidden_state






class     SCREAMING_SNAKE_CASE       (nn.Module				):


   def __init__(   self      :    Dict      ,					a      :    int      ,					a      :    int      ,					a      :    int = 2	)->       Dict:





     """simple docstring"""







     super().__init__()
     lowercase__           =  nn.Convad(a      ,					a      ,					kernel_size=1      ,					stride=a      ,					bias=a	)
     lowercase__           =  nn.BatchNormad(a	)


   def 	SCREAMING_SNAKE_CASE_							(   self      :    List[str]      ,					a      :    Tensor	)->       Tensor:





     """simple docstring"""







     lowercase__           =  self.convolution(a	)
     lowercase__           =  self.normalization(a	)
     return hidden_state






class     SCREAMING_SNAKE_CASE       (nn.Module				):


   def __init__(   self      :    Optional[int]      ,					a      :    int      ,					a      :    int	)->       int:





     """simple docstring"""







     super().__init__()

     lowercase__           =  nn.AdaptiveAvgPoolad((1, 1)	)
     lowercase__           =  nn.Sequential(
         nn.Convad(a      ,					a      ,					kernel_size=1	)      ,					nn.ReLU()      ,					nn.Convad(a      ,					a      ,					kernel_size=1	)      ,					nn.Sigmoid()      ,					)


   def 	SCREAMING_SNAKE_CASE_							(   self      :    List[str]      ,					a      :    Tuple	)->       str:





     """simple docstring"""







     lowercase__           =  self.pooler(a	)
     lowercase__           =  self.attention(a	)
     lowercase__           =  hidden_state * attention
     return hidden_state






class     SCREAMING_SNAKE_CASE       (nn.Module				):


   def __init__(   self      :    Dict      ,					a      :    RegNetConfig      ,					a      :    int      ,					a      :    int      ,					a      :    int = 1	)->       Optional[int]:





     """simple docstring"""







     super().__init__()
     lowercase__           =  in_channels != out_channels or stride != 1
     lowercase__           =  max(1      ,					out_channels // config.groups_width	)
     lowercase__           =  (
         RegNetShortCut(a      ,					a      ,					stride=a	) if should_apply_shortcut else nn.Identity()
     )
     lowercase__           =  nn.Sequential(
         RegNetConvLayer(a      ,					a      ,					kernel_size=1      ,					activation=config.hidden_act	)      ,					RegNetConvLayer(a      ,					a      ,					stride=a      ,					groups=a      ,					activation=config.hidden_act	)      ,					RegNetConvLayer(a      ,					a      ,					kernel_size=1      ,					activation=a	)      ,					)
     lowercase__           =  ACTaFN[config.hidden_act]


   def 	SCREAMING_SNAKE_CASE_							(   self      :    Optional[Any]      ,					a      :    List[str]	)->       Optional[int]:





     """simple docstring"""







     lowercase__           =  hidden_state
     lowercase__           =  self.layer(a	)
     lowercase__           =  self.shortcut(a	)
     hidden_state += residual
     lowercase__           =  self.activation(a	)
     return hidden_state






class     SCREAMING_SNAKE_CASE       (nn.Module				):


   def __init__(   self      :    Optional[int]      ,					a      :    RegNetConfig      ,					a      :    int      ,					a      :    int      ,					a      :    int = 1	)->       str:





     """simple docstring"""







     super().__init__()
     lowercase__           =  in_channels != out_channels or stride != 1
     lowercase__           =  max(1      ,					out_channels // config.groups_width	)
     lowercase__           =  (
         RegNetShortCut(a      ,					a      ,					stride=a	) if should_apply_shortcut else nn.Identity()
     )
     lowercase__           =  nn.Sequential(
         RegNetConvLayer(a      ,					a      ,					kernel_size=1      ,					activation=config.hidden_act	)      ,					RegNetConvLayer(a      ,					a      ,					stride=a      ,					groups=a      ,					activation=config.hidden_act	)      ,					RegNetSELayer(a      ,					reduced_channels=int(round(in_channels / 4	)	)	)      ,					RegNetConvLayer(a      ,					a      ,					kernel_size=1      ,					activation=a	)      ,					)
     lowercase__           =  ACTaFN[config.hidden_act]


   def 	SCREAMING_SNAKE_CASE_							(   self      :    str      ,					a      :    Optional[Any]	)->       Tuple:





     """simple docstring"""







     lowercase__           =  hidden_state
     lowercase__           =  self.layer(a	)
     lowercase__           =  self.shortcut(a	)
     hidden_state += residual
     lowercase__           =  self.activation(a	)
     return hidden_state






class     SCREAMING_SNAKE_CASE       (nn.Module				):


   def __init__(   self      :    Any      ,					a      :    RegNetConfig      ,					a      :    int      ,					a      :    int      ,					a      :    int = 2      ,					a      :    int = 2      ,					)->       Optional[int]:





     """simple docstring"""







     super().__init__()

     lowercase__           =  RegNetXLayer if config.layer_type == 'x' else RegNetYLayer

     lowercase__           =  nn.Sequential(
         # downsampling is done in the first layer with stride of 2
         layer(
             a      ,					a      ,					a      ,					stride=a      ,					)      ,					*[layer(a      ,					a      ,					a	) for _ in range(depth - 1	)]      ,					)


   def 	SCREAMING_SNAKE_CASE_							(   self      :    Dict      ,					a      :    Union[str, Any]	)->       Union[str, Any]:





     """simple docstring"""







     lowercase__           =  self.layers(a	)
     return hidden_state






class     SCREAMING_SNAKE_CASE       (nn.Module				):


   def __init__(   self      :    List[Any]      ,					a      :    RegNetConfig	)->       Dict:





     """simple docstring"""







     super().__init__()
     lowercase__           =  nn.ModuleList([]	)
     # based on `downsample_in_first_stage`, the first layer of the first stage may or may not downsample the input
     self.stages.append(
         RegNetStage(
             a      ,					config.embedding_size      ,					config.hidden_sizes[0]      ,					stride=2 if config.downsample_in_first_stage else 1      ,					depth=config.depths[0]      ,					)	)
     lowercase__           =  zip(config.hidden_sizes      ,					config.hidden_sizes[1:]	)
     for (in_channels, out_channels), depth in zip(a      ,					config.depths[1:]	):
       self.stages.append(RegNetStage(a      ,					a      ,					a      ,					depth=a	)	)


   def 	SCREAMING_SNAKE_CASE_							(   self      :    Optional[Any]      ,					a      :    Tensor      ,					a      :    bool = False      ,					a      :    bool = True	)->       BaseModelOutputWithNoAttention:





     """simple docstring"""







     lowercase__           =  () if output_hidden_states else None

     for stage_module in self.stages:
       if output_hidden_states:
         lowercase__           =  hidden_states + (hidden_state,)

       lowercase__           =  stage_module(a	)

     if output_hidden_states:
       lowercase__           =  hidden_states + (hidden_state,)

     if not return_dict:
       return tuple(v for v in [hidden_state, hidden_states] if v is not None	)

     return BaseModelOutputWithNoAttention(last_hidden_state=a      ,					hidden_states=a	)






class     SCREAMING_SNAKE_CASE       (UpperCAmelCase				):
   _UpperCamelCase   :		Dict			 =	RegNetConfig
   _UpperCamelCase   :		int			 =	'regnet'
   _UpperCamelCase   :		Optional[int]			 =	'pixel_values'
   _UpperCamelCase   :		str			 =	True


   def 	SCREAMING_SNAKE_CASE_							(   self      :    Optional[int]      ,					a      :    Any	)->       List[str]:





     """simple docstring"""







     if isinstance(a      ,					nn.Convad	):
       nn.init.kaiming_normal_(module.weight      ,					mode='fan_out'      ,					nonlinearity='relu'	)
     elif isinstance(a      ,					(nn.BatchNormad, nn.GroupNorm)	):
       nn.init.constant_(module.weight      ,					1	)
       nn.init.constant_(module.bias      ,					0	)


   def 	SCREAMING_SNAKE_CASE_							(   self      :    Any      ,					a      :    Any      ,					a      :    Optional[int]=False	)->       Any:





     """simple docstring"""







     if isinstance(a      ,					a	):
       lowercase__           =  value






lowercase_          =		R"""
    This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it
    as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
    behavior.

    Parameters:
        config ([`RegNetConfig`]): Model configuration class with all the parameters of the model.
            Initializing with a config file does not load the weights associated with the model, only the
            configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
"""

lowercase_          =		R"""
    Args:
        pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
            Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See
            [`ConvNextImageProcessor.__call__`] for details.

        output_hidden_states (`bool`, *optional*):
            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
            more detail.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~file_utils.ModelOutput`] instead of a plain tuple.
"""
@add_start_docstrings(
    'The bare RegNet model outputting raw features without any specific head on top.'      ,     UpperCAmelCase      ,     )
# Copied from transformers.models.resnet.modeling_resnet.ResNetModel with RESNET->REGNET,ResNet->RegNet
class     SCREAMING_SNAKE_CASE       (UpperCAmelCase				):


   def __init__(   self      :    Optional[Any]      ,					a      :    Tuple	)->       Tuple:





     """simple docstring"""







     super().__init__(a	)
     lowercase__           =  config
     lowercase__           =  RegNetEmbeddings(a	)
     lowercase__           =  RegNetEncoder(a	)
     lowercase__           =  nn.AdaptiveAvgPoolad((1, 1)	)
     # Initialize weights and apply final processing
     self.post_init()


   @add_start_docstrings_to_model_forward(a	)
   @add_code_sample_docstrings(
       checkpoint=_CHECKPOINT_FOR_DOC      ,					output_type=a      ,					config_class=_CONFIG_FOR_DOC      ,					modality='vision'      ,					expected_output=_EXPECTED_OUTPUT_SHAPE      ,					)
   def 	SCREAMING_SNAKE_CASE_							(   self      :    Optional[Any]      ,					a      :    Tensor      ,					a      :    Optional[bool] = None      ,					a      :    Optional[bool] = None	)->       BaseModelOutputWithPoolingAndNoAttention:





     """simple docstring"""







     lowercase__           =  (
         output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
     )
     lowercase__           =  return_dict if return_dict is not None else self.config.use_return_dict

     lowercase__           =  self.embedder(a	)

     lowercase__           =  self.encoder(
         a      ,					output_hidden_states=a      ,					return_dict=a	)

     lowercase__           =  encoder_outputs[0]

     lowercase__           =  self.pooler(a	)

     if not return_dict:
       return (last_hidden_state, pooled_output) + encoder_outputs[1:]

     return BaseModelOutputWithPoolingAndNoAttention(
         last_hidden_state=a      ,					pooler_output=a      ,					hidden_states=encoder_outputs.hidden_states      ,					)






@add_start_docstrings(
    '\n    RegNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n    ImageNet.\n    '      ,     UpperCAmelCase      ,     )
# Copied from transformers.models.resnet.modeling_resnet.ResNetForImageClassification with RESNET->REGNET,ResNet->RegNet,resnet->regnet
class     SCREAMING_SNAKE_CASE       (UpperCAmelCase				):


   def __init__(   self      :    Optional[Any]      ,					a      :    int	)->       Dict:





     """simple docstring"""







     super().__init__(a	)
     lowercase__           =  config.num_labels
     lowercase__           =  RegNetModel(a	)
     # classification head
     lowercase__           =  nn.Sequential(
         nn.Flatten()      ,					nn.Linear(config.hidden_sizes[-1]      ,					config.num_labels	) if config.num_labels > 0 else nn.Identity()      ,					)
     # initialize weights and apply final processing
     self.post_init()


   @add_start_docstrings_to_model_forward(a	)
   @add_code_sample_docstrings(
       checkpoint=_IMAGE_CLASS_CHECKPOINT      ,					output_type=a      ,					config_class=_CONFIG_FOR_DOC      ,					expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT      ,					)
   def 	SCREAMING_SNAKE_CASE_							(   self      :    int      ,					a      :    Optional[torch.FloatTensor] = None      ,					a      :    Optional[torch.LongTensor] = None      ,					a      :    Optional[bool] = None      ,					a      :    Optional[bool] = None      ,					)->       ImageClassifierOutputWithNoAttention:





     """simple docstring"""







     lowercase__           =  return_dict if return_dict is not None else self.config.use_return_dict

     lowercase__           =  self.regnet(a      ,					output_hidden_states=a      ,					return_dict=a	)

     lowercase__           =  outputs.pooler_output if return_dict else outputs[1]

     lowercase__           =  self.classifier(a	)

     lowercase__           =  None

     if labels is not None:
       if self.config.problem_type is None:
         if self.num_labels == 1:
           lowercase__           =  'regression'
         elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
           lowercase__           =  'single_label_classification'
         else:
           lowercase__           =  'multi_label_classification'
       if self.config.problem_type == "regression":
         lowercase__           =  MSELoss()
         if self.num_labels == 1:
           lowercase__           =  loss_fct(logits.squeeze()      ,					labels.squeeze()	)
         else:
           lowercase__           =  loss_fct(a      ,					a	)
       elif self.config.problem_type == "single_label_classification":
         lowercase__           =  CrossEntropyLoss()
         lowercase__           =  loss_fct(logits.view(-1      ,					self.num_labels	)      ,					labels.view(-1	)	)
       elif self.config.problem_type == "multi_label_classification":
         lowercase__           =  BCEWithLogitsLoss()
         lowercase__           =  loss_fct(a      ,					a	)

     if not return_dict:
       lowercase__           =  (logits,) + outputs[2:]
       return (loss,) + output if loss is not None else output

     return ImageClassifierOutputWithNoAttention(loss=a      ,					logits=a      ,					hidden_states=outputs.hidden_states	)









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

import sentencepiece as spm

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


if is_torch_available():
      import torch


if TYPE_CHECKING:
      from transformers.pipelines.conversational import Conversation


lowercase_          =		logging.get_logger(__name__)
lowercase_          =		{"""vocab_file""": """spiece.model"""}

lowercase_          =		{
    """vocab_file""": {
        """AI-Sweden/gpt-sw3-126m""": """https://huggingface.co/AI-Sweden/gpt-sw3-126m/resolve/main/spiece.model""",
        """AI-Sweden/gpt-sw3-350m""": """https://huggingface.co/AI-Sweden/gpt-sw3-350m/resolve/main/spiece.model""",
        """AI-Sweden/gpt-sw3-1.6b""": """https://huggingface.co/AI-Sweden/gpt-sw3-1.6b/resolve/main/spiece.model""",
        """AI-Sweden/gpt-sw3-6.7b""": """https://huggingface.co/AI-Sweden/gpt-sw3-6.7b/resolve/main/spiece.model""",
        """AI-Sweden/gpt-sw3-20b""": """https://huggingface.co/AI-Sweden/gpt-sw3-20b/resolve/main/spiece.model""",
    }
}

lowercase_          =		{
    """AI-Sweden/gpt-sw3-126m""": 2_048,
    """AI-Sweden/gpt-sw3-350m""": 2_048,
    """AI-Sweden/gpt-sw3-1.6b""": 2_048,
    """AI-Sweden/gpt-sw3-6.7b""": 2_048,
    """AI-Sweden/gpt-sw3-20b""": 2_048,
}
class     SCREAMING_SNAKE_CASE       (UpperCAmelCase				):
   _UpperCamelCase   :		List[str]			 =	VOCAB_FILES_NAMES
   _UpperCamelCase   :		List[Any]			 =	PRETRAINED_VOCAB_FILES_MAP
   _UpperCamelCase   :		Union[str, Any]			 =	PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
   _UpperCamelCase   :		Any			 =	['input_ids', 'attention_mask']


   def __init__(   self      :    Optional[Any]      ,					a      :    Tuple      ,					a      :    Optional[int]=False      ,					a      :    str=False      ,					a      :    str=False      ,					a      :    Tuple=None      ,					a      :    Any=None      ,					a      :    Union[str, Any]=None      ,					a      :    Union[str, Any]=None      ,					a      :    Optional[Dict[str, Any]] = None      ,					**a      :    Optional[int]      ,					)->       None:





     """simple docstring"""







     lowercase__           =  {} if sp_model_kwargs is None else sp_model_kwargs

     lowercase__           =  kwargs.get('name_or_path'	)
     if name_or_path is None:
       logger.warning(
           'name_or_path not provided, will work for all GPTSw3 models except gpt-sw3-7b,'
           ' you are testing the model, this can safely be ignored'	)
       lowercase__           =  'None'

     # Default definitions for our 2 tokenizer versions, with None-checks to enable proper testing
     lowercase__           =  '<|endoftext|>' if eos_token is None else eos_token
     lowercase__           =  '<unk>' if unk_token is None else unk_token
     if "gpt-sw3-7b" in name_or_path:
       lowercase__           =  unk_token if pad_token is None else pad_token
       lowercase__           =  eos_token if bos_token is None else bos_token
     else:
       lowercase__           =  '<pad>' if pad_token is None else pad_token
       lowercase__           =  '<s>' if bos_token is None else bos_token

     super().__init__(
         do_lower_case=a      ,					remove_space=a      ,					keep_accents=a      ,					bos_token=a      ,					eos_token=a      ,					unk_token=a      ,					pad_token=a      ,					sp_model_kwargs=self.sp_model_kwargs      ,					**a      ,					)

     lowercase__           =  do_lower_case
     lowercase__           =  remove_space
     lowercase__           =  keep_accents
     lowercase__           =  vocab_file

     lowercase__           =  spm.SentencePieceProcessor(**self.sp_model_kwargs	)
     self.sp_model.Load(a	)

     # Used for whitespace normalization in input texts
     # fmt : off
     lowercase__           =  {' ', ' ', ' ', ' ', ' ', '　', ' ', ' ', ' ', ' ', '￼', ''}
     # fmt : on

     # Regular expression to remove non-printing characters (e.g. some unicode control chars) in preprocessing
     lowercase__           =  re.compile(
         f"""[{"".join(map(a      ,					list(range(0      ,					9	)	) + list(range(11      ,					32	)	) + list(range(127      ,					160	)	) + [160, 173, 8_203]	)	)}]"""	)


   def __getstate__(   self      :    Any	)->       str:





     """simple docstring"""







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


   def __setstate__(   self      :    int      ,					a      :    Optional[Any]	)->       int:





     """simple docstring"""







     lowercase__           =  d

     # for backward compatibility
     if not hasattr(self      ,					'sp_model_kwargs'	):
       lowercase__           =  {}

     lowercase__           =  spm.SentencePieceProcessor(**self.sp_model_kwargs	)
     self.sp_model.Load(self.vocab_file	)


   @property
   # Copied from transformers.models.albert.tokenization_albert.AlbertTokenizer.vocab_size
   def 	SCREAMING_SNAKE_CASE_							(   self      :    Union[str, Any]	)->       int:





     """simple docstring"""







     return len(self.sp_model	)


   def 	SCREAMING_SNAKE_CASE_							(   self      :    Tuple      ,					a      :    str	)->       str:





     """simple docstring"""







     lowercase__           =  self.non_printing_characters_re.sub(''      ,					a	)

     # Normalize whitespaces
     lowercase__           =  ''.join([char if char not in self.whitespaces else ' ' for char in text]	)

     # NFC Unicode normalization
     lowercase__           =  unicodedata.normalize('NFC'      ,					a	)
     return text


   def 	SCREAMING_SNAKE_CASE_							(   self      :    Any      ,					a      :    str      ,					**a      :    Tuple	)->       List[str]:





     """simple docstring"""







     lowercase__           =  self.preprocess_text(a	)
     return self.sp_model.encode(a      ,					out_type=a	)


   def 	SCREAMING_SNAKE_CASE_							(   self      :    Optional[int]      ,					a      :    str	)->       int:





     """simple docstring"""







     return self.sp_model.PieceToId(a	)


   def 	SCREAMING_SNAKE_CASE_							(   self      :    Optional[Any]      ,					a      :    int	)->       str:





     """simple docstring"""







     return self.sp_model.IdToPiece(a	)


   @staticmethod
   def 	SCREAMING_SNAKE_CASE_							(   a      :    str	)->       str:





     """simple docstring"""







     return out_string


   def 	SCREAMING_SNAKE_CASE_							(   self      :    Union[str, Any]      ,					a      :    List[str]	)->       str:





     """simple docstring"""







     lowercase__           =  []
     lowercase__           =  ''
     lowercase__           =  False
     for token in tokens:
       # make sure that special tokens are not decoded using sentencepiece model
       if token in self.all_special_tokens:
         # TODO: Check if this is needed, as it ensures that decode(encode(doc)) != doc by adding extra whitespace in the decoded document
         if not prev_is_special:
           out_string += " "

         out_string += self.sp_model.decode(a	) + token
         lowercase__           =  True
         lowercase__           =  []
       else:
         current_sub_tokens.append(a	)
         lowercase__           =  False
     out_string += self.sp_model.decode(a	)

     return out_string


   def 	SCREAMING_SNAKE_CASE_							(   self      :    List[str]	)->       Dict[str, int]:





     """simple docstring"""







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


   def 	SCREAMING_SNAKE_CASE_							(   self      :    Any      ,					a      :    str      ,					a      :    Optional[str] = None	)->       Tuple[str]:





     """simple docstring"""







     if not os.path.isdir(a	):
       logger.error(f"""Vocabulary path ({save_directory}) should be a directory"""	)
       return
     lowercase__           =  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:
         lowercase__           =  self.sp_model.serialized_model_proto()
         fi.write(a	)

     return (out_vocab_file,)


   def 	SCREAMING_SNAKE_CASE_							(   self      :    Union[str, Any]      ,					a      :    Union[str, List[str]]      ,					a      :    Union[str, bool] = False	)->       Union[List[int], List[List[int]], "torch.Tensor"]:





     """simple docstring"""







     if isinstance(a      ,					a	):
       lowercase__           =  self.preprocess_text(a	)
       lowercase__           =  self.sp_model.encode(a	)
     else:
       lowercase__           =  [self.preprocess_text(a	) for t in text]
       lowercase__           =  self.sp_model.encode(a	)

     if return_tensors is True or return_tensors == "pt":
       lowercase__           =  torch.tensor(a	)

     return token_ids


   def 	SCREAMING_SNAKE_CASE_							(   self      :    Optional[Any]      ,					a      :    Union[int, List[int]]	)->       str:





     """simple docstring"""







     return self.sp_model.decode(a	)


   def 	SCREAMING_SNAKE_CASE_							(   self      :    Any      ,					a      :    "Conversation"	)->       List[int]:





     """simple docstring"""







     lowercase__           =  [f"""User: {text}""" if is_user else f"""Bot: {text}""" for is_user, text in conversation.iter_texts()]
     lowercase__           =  (
         f"""{self.eos_token}{self.bos_token}""" + f"""{self.bos_token}""".join(a	) + f"""{self.bos_token}Bot:"""
     )
     return self.encode(text=a	)


