






import math
import time
from typing import Dict, List, Optional

from torch.utils.data import Dataset

from transformers import SeqaSeqTrainer, is_torch_tpu_available
from transformers.trainer_utils import PredictionOutput, speed_metrics


if is_torch_tpu_available(check_device=False):
							import torch_xla.core.xla_model as xm
							import torch_xla.debug.metrics as met


class 	__SCREAMING_SNAKE_CASE(						a_						):
							def __init__(  self:   Optional[int]							,						*UpperCamelCase:   Any							,						UpperCamelCase:   Any=None							,						UpperCamelCase:   Optional[Any]=None							,						**UpperCamelCase:   List[str]    )		->		Union[str, Any]:
											super().__init__(*lowerCAmelCase_							,						**lowerCAmelCase_    )
											snake_case__						=  eval_examples
											snake_case__						=  post_process_function
							def lowerCAmelCase_			(  self:   List[str]							,						UpperCamelCase:   Optional[Dataset] = None							,						UpperCamelCase:   Union[str, Any]=None							,						UpperCamelCase:   Optional[List[str]] = None							,						UpperCamelCase:   str = "eval"							,						**UpperCamelCase:   int							,						)		->		Dict[str, float]:
											snake_case__						=  gen_kwargs.copy()
											snake_case__						=  (
											    gen_kwargs['max_length'] if gen_kwargs.get('max_length'    ) is not None else self.args.generation_max_length
											)
											snake_case__						=  (
											    gen_kwargs['num_beams'] if gen_kwargs.get('num_beams'    ) is not None else self.args.generation_num_beams
											)
											snake_case__						=  gen_kwargs

											snake_case__						=  self.eval_dataset if eval_dataset is None else eval_dataset
											snake_case__						=  self.get_eval_dataloader(lowerCAmelCase_    )
											snake_case__						=  self.eval_examples if eval_examples is None else eval_examples

											# Temporarily disable metric computation, we will do it in the loop here.
											snake_case__						=  self.compute_metrics
											snake_case__						=  None
											snake_case__						=  time.time()
											snake_case__						=  self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
											try:
															snake_case__						=  eval_loop(
															    lowerCAmelCase_							,						description='Evaluation'							,						prediction_loss_only=True if compute_metrics is None else None							,						ignore_keys=lowerCAmelCase_							,						metric_key_prefix=lowerCAmelCase_							,						)
											finally:
															snake_case__						=  compute_metrics
											snake_case__						=  self.args.eval_batch_size * self.args.world_size
											if F'''{metric_key_prefix}_jit_compilation_time''' in output.metrics:
															start_time += output.metrics[F'''{metric_key_prefix}_jit_compilation_time''']
											output.metrics.update(
											    speed_metrics(
											        lowerCAmelCase_							,						lowerCAmelCase_							,						num_samples=output.num_samples							,						num_steps=math.ceil(output.num_samples / total_batch_size    )							,						)    )

											if self.post_process_function is not None and self.compute_metrics is not None and self.args.should_save:
															# Only the main node write the results by default
															snake_case__						=  self.post_process_function(lowerCAmelCase_							,						lowerCAmelCase_							,						lowerCAmelCase_    )
															snake_case__						=  self.compute_metrics(lowerCAmelCase_    )

															# Prefix all keys with metric_key_prefix + '_'
															for key in list(metrics.keys()    ):
																			if not key.startswith(F'''{metric_key_prefix}_'''    ):
																							snake_case__						=  metrics.pop(lowerCAmelCase_    )

															metrics.update(output.metrics    )
											else:
															snake_case__						=  output.metrics

											if self.args.should_log:
															# Only the main node log the results by default
															self.log(lowerCAmelCase_    )

											if self.args.tpu_metrics_debug or self.args.debug:
															# tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.)
															xm.master_print(met.metrics_report()    )

											snake_case__						=  self.callback_handler.on_evaluate(self.args							,						self.state							,						self.control							,						lowerCAmelCase_    )
											return metrics


							def lowerCAmelCase_			(  self:   Optional[Any]							,						UpperCamelCase:   Dict							,						UpperCamelCase:   str							,						UpperCamelCase:   Optional[Any]=None							,						UpperCamelCase:   str = "test"							,						**UpperCamelCase:   List[str]    )		->		Dict:
											snake_case__						=  gen_kwargs.copy()

											snake_case__						=  self.get_test_dataloader(lowerCAmelCase_    )

											# Temporarily disable metric computation, we will do it in the loop here.
											snake_case__						=  self.compute_metrics
											snake_case__						=  None
											snake_case__						=  time.time()
											snake_case__						=  self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
											try:
															snake_case__						=  eval_loop(
															    lowerCAmelCase_							,						description='Prediction'							,						prediction_loss_only=True if compute_metrics is None else None							,						ignore_keys=lowerCAmelCase_							,						metric_key_prefix=lowerCAmelCase_							,						)
											finally:
															snake_case__						=  compute_metrics

											snake_case__						=  self.args.eval_batch_size * self.args.world_size
											if F'''{metric_key_prefix}_jit_compilation_time''' in output.metrics:
															start_time += output.metrics[F'''{metric_key_prefix}_jit_compilation_time''']
											output.metrics.update(
											    speed_metrics(
											        lowerCAmelCase_							,						lowerCAmelCase_							,						num_samples=output.num_samples							,						num_steps=math.ceil(output.num_samples / total_batch_size    )							,						)    )
											if self.post_process_function is None or self.compute_metrics is None:
															return output

											snake_case__						=  self.post_process_function(lowerCAmelCase_							,						lowerCAmelCase_							,						lowerCAmelCase_							,						'predict'    )
											snake_case__						=  self.compute_metrics(lowerCAmelCase_    )

											# Prefix all keys with metric_key_prefix + '_'
											for key in list(metrics.keys()    ):
															if not key.startswith(F'''{metric_key_prefix}_'''    ):
																			snake_case__						=  metrics.pop(lowerCAmelCase_    )
											metrics.update(output.metrics    )
											return PredictionOutput(predictions=predictions.predictions							,						label_ids=predictions.label_ids							,						metrics=lowerCAmelCase_    )








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


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

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

UpperCAmelCase__  			=				{
    '''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 						a__					(					a_   ):





			'''simple docstring'''

			A						:				int					      =			VOCAB_FILES_NAMES
			A						:				Optional[int]					      =			PRETRAINED_VOCAB_FILES_MAP
			A						:				Tuple					      =			PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
			A						:				int					      =			['''input_ids''', '''attention_mask''']
			def __init__(  self							:			int			,    lowerCAmelCase_							:			List[str]			,    lowerCAmelCase_							:			Union[str, Any]=False			,    lowerCAmelCase_							:			List[str]=False			,    lowerCAmelCase_							:			List[Any]=False			,    lowerCAmelCase_							:			Union[str, Any]=None			,    lowerCAmelCase_							:			Union[str, Any]=None			,    lowerCAmelCase_							:			Union[str, Any]=None			,    lowerCAmelCase_							:			List[Any]=None			,    lowerCAmelCase_							:			Optional[Dict[str, Any]] = None			,    **lowerCAmelCase_							:			Optional[Any]			,    )      ->		None:
						__A=	{} if sp_model_kwargs is None else sp_model_kwargs

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

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

						__A=	do_lower_case
						__A=	remove_space
						__A=	keep_accents
						__A=	vocab_file

						__A=	spm.SentencePieceProcessor(**self.sp_model_kwargs	)
						self.sp_model.Load(lowerCAmelCase_	)

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

						# Regular expression to remove non-printing characters (e.g. some unicode control chars) in preprocessing
						__A=	re.compile(
						    F"""[{"".join(map(lowerCAmelCase_			,    list(range(0			,    9	)	) + list(range(11			,    32	)	) + list(range(127			,    160	)	) + [160, 173, 8_203]	)	)}]"""	)
			def __getstate__(  self							:			Optional[int]	)      ->		Tuple:
						__A=	self.__dict__.copy()
						__A=	None
						return state
			def __setstate__(  self							:			int			,    lowerCAmelCase_							:			int	)      ->		Tuple:
						__A=	d

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

						__A=	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 					lowerCAmelCase     (  self							:			Tuple	)      ->		int:
						return len(self.sp_model	)
			def 					lowerCAmelCase     (  self							:			int			,    lowerCAmelCase_							:			str	)      ->		str:
						__A=	self.non_printing_characters_re.sub(''			,    lowerCAmelCase_	)

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

						# NFC Unicode normalization
						__A=	unicodedata.normalize('NFC'			,    lowerCAmelCase_	)
						return text
			def 					lowerCAmelCase     (  self							:			Tuple			,    lowerCAmelCase_							:			str			,    **lowerCAmelCase_							:			Optional[Any]	)      ->		List[str]:
						__A=	self.preprocess_text(lowerCAmelCase_	)
						return self.sp_model.encode(lowerCAmelCase_			,    out_type=lowerCAmelCase_	)
			def 					lowerCAmelCase     (  self							:			Any			,    lowerCAmelCase_							:			str	)      ->		int:
						return self.sp_model.PieceToId(lowerCAmelCase_	)
			def 					lowerCAmelCase     (  self							:			Optional[Any]			,    lowerCAmelCase_							:			int	)      ->		str:
						return self.sp_model.IdToPiece(lowerCAmelCase_	)
			@staticmethod
			def 					lowerCAmelCase     (  lowerCAmelCase_							:			str	)      ->		str:
						return out_string
			def 					lowerCAmelCase     (  self							:			Union[str, Any]			,    lowerCAmelCase_							:			List[str]	)      ->		str:
						__A=	[]
						__A=	''
						__A=	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
												__A=	True
												__A=	[]
									else:
												current_sub_tokens.append(lowerCAmelCase_	)
												__A=	False
						out_string += self.sp_model.decode(lowerCAmelCase_	)

						return out_string
			def 					lowerCAmelCase     (  self							:			List[Any]	)      ->		Dict[str, int]:
						__A=	{self.convert_ids_to_tokens(lowerCAmelCase_	): i for i in range(self.vocab_size	)}
						vocab.update(self.added_tokens_encoder	)
						return vocab
			def 					lowerCAmelCase     (  self							:			Dict			,    lowerCAmelCase_							:			str			,    lowerCAmelCase_							:			Optional[str] = None	)      ->		Tuple[str]:
						if not os.path.isdir(lowerCAmelCase_	):
									logger.error(F"""Vocabulary path ({save_directory}) should be a directory"""	)
									return
						__A=	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=	self.sp_model.serialized_model_proto()
												fi.write(lowerCAmelCase_	)

						return (out_vocab_file,)
			def 					lowerCAmelCase     (  self							:			Optional[Any]			,    lowerCAmelCase_							:			Union[str, List[str]]			,    lowerCAmelCase_							:			Union[str, bool] = False	)      ->		Union[List[int], List[List[int]], "torch.Tensor"]:

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

						if return_tensors is True or return_tensors == "pt":
									__A=	torch.tensor(lowerCAmelCase_	)

						return token_ids
			def 					lowerCAmelCase     (  self							:			Tuple			,    lowerCAmelCase_							:			Union[int, List[int]]	)      ->		str:
						return self.sp_model.decode(lowerCAmelCase_	)

			def 					lowerCAmelCase     (  self							:			Optional[Any]			,    lowerCAmelCase_							:			"Conversation"	)      ->		List[int]:
						__A=	[F"""User: {text}""" if is_user else F"""Bot: {text}""" for is_user, text in conversation.iter_texts()]
						__A=	(
						    F"""{self.eos_token}{self.bos_token}""" + F"""{self.bos_token}""".join(lowerCAmelCase_	) + F"""{self.bos_token}Bot:"""
						)
						return self.encode(text=lowerCAmelCase_	)



