



"""simple docstring"""






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


snake_case   					=				logging.get_logger(__name__)
snake_case   					=				{'''vocab_file''': '''spiece.model'''}

snake_case   					=				{
    '''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''',
    }
}

snake_case   					=				{
    '''AI-Sweden/gpt-sw3-126m''': 2_0_4_8,
    '''AI-Sweden/gpt-sw3-350m''': 2_0_4_8,
    '''AI-Sweden/gpt-sw3-1.6b''': 2_0_4_8,
    '''AI-Sweden/gpt-sw3-6.7b''': 2_0_4_8,
    '''AI-Sweden/gpt-sw3-20b''': 2_0_4_8,
}



class     UpperCAmelCase    (	__SCREAMING_SNAKE_CASE  ):
   A__		:	Dict           =  VOCAB_FILES_NAMES
   A__		:	Union[str, Any]           =  PRETRAINED_VOCAB_FILES_MAP
   A__		:	Any           =  PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
   A__		:	Tuple           =  ['''input_ids''', '''attention_mask''']



   def __init__(       self    :	int							,       __lowerCamelCase    :	Any							,       __lowerCamelCase    :	Dict=False							,       __lowerCamelCase    :	int=False							,       __lowerCamelCase    :	Dict=False							,       __lowerCamelCase    :	Union[str, Any]=None							,       __lowerCamelCase    :	Any=None							,       __lowerCamelCase    :	Union[str, Any]=None							,       __lowerCamelCase    :	int=None							,       __lowerCamelCase    :	Optional[Dict[str, Any]] = None							,       **__lowerCamelCase    :	List[str]							,       ):



     """simple docstring"""
     _snake_case   	=      {} if sp_model_kwargs is None else sp_model_kwargs

     _snake_case   	=      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'''				)
       _snake_case   	=      '''None'''

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

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

     _snake_case   	=      do_lower_case
     _snake_case   	=      remove_space
     _snake_case   	=      keep_accents
     _snake_case   	=      vocab_file

     _snake_case   	=      spm.SentencePieceProcessor(**self.sp_model_kwargs				)
     self.sp_model.Load(__lowerCamelCase				)

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

     # Regular expression to remove non-printing characters (e.g. some unicode control chars) in preprocessing
     _snake_case   	=      re.compile(
         f"""[{''.join(map(__lowerCamelCase							,       list(range(0							,       9				)				) + list(range(1_1							,       3_2				)				) + list(range(1_2_7							,       1_6_0				)				) + [1_6_0, 1_7_3, 8_2_0_3]				)				)}]"""				)



   def __getstate__(       self    :	Optional[Any]				):



     """simple docstring"""
     _snake_case   	=      self.__dict__.copy()
     _snake_case   	=      None
     return state



   def __setstate__(       self    :	List[Any]							,       __lowerCamelCase    :	List[str]				):



     """simple docstring"""
     _snake_case   	=      d

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

     _snake_case   	=      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    __UpperCAmelCase    (       self    :	Tuple				):



     """simple docstring"""
     return len(self.sp_model				)



   def    __UpperCAmelCase    (       self    :	Optional[int]							,       __lowerCamelCase    :	str				):



     """simple docstring"""
     _snake_case   	=      self.non_printing_characters_re.sub(''''''							,       __lowerCamelCase				)

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

     # NFC Unicode normalization
     _snake_case   	=      unicodedata.normalize('''NFC'''							,       __lowerCamelCase				)
     return text



   def    __UpperCAmelCase    (       self    :	Any							,       __lowerCamelCase    :	str							,       **__lowerCamelCase    :	List[Any]				):



     """simple docstring"""
     _snake_case   	=      self.preprocess_text(__lowerCamelCase				)
     return self.sp_model.encode(__lowerCamelCase							,       out_type=__lowerCamelCase				)



   def    __UpperCAmelCase    (       self    :	str							,       __lowerCamelCase    :	str				):



     """simple docstring"""
     return self.sp_model.PieceToId(__lowerCamelCase				)



   def    __UpperCAmelCase    (       self    :	List[Any]							,       __lowerCamelCase    :	int				):



     """simple docstring"""
     return self.sp_model.IdToPiece(__lowerCamelCase				)



   @staticmethod
   def    __UpperCAmelCase    (       __lowerCamelCase    :	str				):



     """simple docstring"""
     return out_string



   def    __UpperCAmelCase    (       self    :	Optional[int]							,       __lowerCamelCase    :	List[str]				):



     """simple docstring"""
     _snake_case   	=      []
     _snake_case   	=      ''''''
     _snake_case   	=      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(__lowerCamelCase				) + token
         _snake_case   	=      True
         _snake_case   	=      []
       else:
         current_sub_tokens.append(__lowerCamelCase				)
         _snake_case   	=      False
     out_string += self.sp_model.decode(__lowerCamelCase				)

     return out_string



   def    __UpperCAmelCase    (       self    :	str				):



     """simple docstring"""
     _snake_case   	=      {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    :	Any							,       __lowerCamelCase    :	str							,       __lowerCamelCase    :	Optional[str] = None				):



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

     return (out_vocab_file,)



   def    __UpperCAmelCase    (       self    :	Tuple							,       __lowerCamelCase    :	Union[str, List[str]]							,       __lowerCamelCase    :	Union[str, bool] = False				):



     """simple docstring"""

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

     if return_tensors is True or return_tensors == "pt":
       _snake_case   	=      torch.tensor(__lowerCamelCase				)

     return token_ids



   def    __UpperCAmelCase    (       self    :	Union[str, Any]							,       __lowerCamelCase    :	Union[int, List[int]]				):



     """simple docstring"""
     return self.sp_model.decode(__lowerCamelCase				)





   def    __UpperCAmelCase    (       self    :	Optional[Any]							,       __lowerCamelCase    :	"Conversation"				):



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











# Copyright 2023 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import torch

from accelerate import PartialState
from accelerate.utils.operations import broadcast, gather, gather_object, pad_across_processes, reduce

def lowercase    (  SCREAMING_SNAKE_CASE )			->							str:


			'''simple docstring'''







			return (torch.arange(state.num_processes ) + 1.0 + (state.num_processes * state.process_index)).to(state.device )

def lowercase    (  SCREAMING_SNAKE_CASE )			->							Dict:


			'''simple docstring'''







			SCREAMING_SNAKE_CASE_								=						create_tensor(SCREAMING_SNAKE_CASE )
			SCREAMING_SNAKE_CASE_								=						gather(SCREAMING_SNAKE_CASE )
			assert gathered_tensor.tolist() == list(range(1       ,    state.num_processes**2 + 1 ) )

def lowercase    (  SCREAMING_SNAKE_CASE )			->							List[str]:


			'''simple docstring'''







			SCREAMING_SNAKE_CASE_								=						[state.process_index]
			SCREAMING_SNAKE_CASE_								=						gather_object(SCREAMING_SNAKE_CASE )
			assert len(SCREAMING_SNAKE_CASE ) == state.num_processes, F'{gathered_obj}, {len(SCREAMING_SNAKE_CASE )} != {state.num_processes}'
			assert gathered_obj == list(range(state.num_processes ) ), F'{gathered_obj} != {list(range(state.num_processes ) )}'

def lowercase    (  SCREAMING_SNAKE_CASE )			->							int:


			'''simple docstring'''







			SCREAMING_SNAKE_CASE_								=						create_tensor(SCREAMING_SNAKE_CASE )
			SCREAMING_SNAKE_CASE_								=						broadcast(SCREAMING_SNAKE_CASE )
			assert broadcasted_tensor.shape == torch.Size([state.num_processes] )
			assert broadcasted_tensor.tolist() == list(range(1       ,    state.num_processes + 1 ) )

def lowercase    (  SCREAMING_SNAKE_CASE )			->							Union[str, Any]:


			'''simple docstring'''







			if state.is_main_process:
						SCREAMING_SNAKE_CASE_								=						torch.arange(state.num_processes + 1 ).to(state.device )
			else:
						SCREAMING_SNAKE_CASE_								=						torch.arange(state.num_processes ).to(state.device )
			SCREAMING_SNAKE_CASE_								=						pad_across_processes(SCREAMING_SNAKE_CASE )
			assert padded_tensor.shape == torch.Size([state.num_processes + 1] )
			if not state.is_main_process:
						assert padded_tensor.tolist() == list(range(0       ,    state.num_processes ) ) + [0]

def lowercase    (  SCREAMING_SNAKE_CASE )			->							str:


			'''simple docstring'''







			if state.num_processes != 2:
						return
			SCREAMING_SNAKE_CASE_								=						create_tensor(SCREAMING_SNAKE_CASE )
			SCREAMING_SNAKE_CASE_								=						reduce(SCREAMING_SNAKE_CASE       ,    'sum' )
			SCREAMING_SNAKE_CASE_								=						torch.tensor([4.0, 6] ).to(state.device )
			assert torch.allclose(SCREAMING_SNAKE_CASE       ,    SCREAMING_SNAKE_CASE ), F'{reduced_tensor} != {truth_tensor}'

def lowercase    (  SCREAMING_SNAKE_CASE )			->							Dict:


			'''simple docstring'''







			if state.num_processes != 2:
						return
			SCREAMING_SNAKE_CASE_								=						create_tensor(SCREAMING_SNAKE_CASE )
			SCREAMING_SNAKE_CASE_								=						reduce(SCREAMING_SNAKE_CASE       ,    'mean' )
			SCREAMING_SNAKE_CASE_								=						torch.tensor([2.0, 3] ).to(state.device )
			assert torch.allclose(SCREAMING_SNAKE_CASE       ,    SCREAMING_SNAKE_CASE ), F'{reduced_tensor} != {truth_tensor}'

def lowercase    (  SCREAMING_SNAKE_CASE )			->							List[str]:


			'''simple docstring'''







			main()

def lowercase    (  )			->							str:


			'''simple docstring'''







			SCREAMING_SNAKE_CASE_								=						PartialState()
			state.print(F'State: {state}' )
			state.print('testing gather' )
			test_gather(SCREAMING_SNAKE_CASE )
			state.print('testing gather_object' )
			test_gather_object(SCREAMING_SNAKE_CASE )
			state.print('testing broadcast' )
			test_broadcast(SCREAMING_SNAKE_CASE )
			state.print('testing pad_across_processes' )
			test_pad_across_processes(SCREAMING_SNAKE_CASE )
			state.print('testing reduce_sum' )
			test_reduce_sum(SCREAMING_SNAKE_CASE )
			state.print('testing reduce_mean' )
			test_reduce_mean(SCREAMING_SNAKE_CASE )


if __name__ == "__main__":
				main()
