


'''simple docstring'''







import json
import os
import subprocess
import unittest
from ast import literal_eval

import pytest
from parameterized import parameterized, parameterized_class

from . import is_sagemaker_available


if is_sagemaker_available():
       from sagemaker import Session, TrainingJobAnalytics
       from sagemaker.huggingface import HuggingFace
@pytest.mark.skipif(
    literal_eval(os.getenv("TEST_SAGEMAKER"    ,					"False"	)	) is not True    ,					reason="Skipping test because should only be run when releasing minor transformers version"    ,					)
@pytest.mark.usefixtures("sm_env"	)
@parameterized_class(
    [
        {
            "framework": "pytorch",
            "script": "run_glue.py",
            "model_name_or_path": "distilbert-base-cased",
            "instance_type": "ml.p3.16xlarge",
            "results": {"train_runtime": 6_5_0, "eval_accuracy": 0.7, "eval_loss": 0.6},
        },
        {
            "framework": "pytorch",
            "script": "run_ddp.py",
            "model_name_or_path": "distilbert-base-cased",
            "instance_type": "ml.p3.16xlarge",
            "results": {"train_runtime": 6_0_0, "eval_accuracy": 0.7, "eval_loss": 0.6},
        },
        {
            "framework": "tensorflow",
            "script": "run_tf_dist.py",
            "model_name_or_path": "distilbert-base-cased",
            "instance_type": "ml.p3.16xlarge",
            "results": {"train_runtime": 6_0_0, "eval_accuracy": 0.6, "eval_loss": 0.7},
        },
    ]	)
class 	UpperCamelCase__					( unittest.TestCase	):



     """simple docstring"""






     def a	( self   ):

            '''simple docstring'''

            if self.framework == "pytorch":
                   subprocess.run(
                       F'cp ./examples/pytorch/text-classification/run_glue.py {self.env.test_path}/run_glue.py'.split()      ,	encoding='utf-8'      ,	check=snake_case__      ,	)
            assert hasattr(self      ,	'env'   )







     def a	( self      ,	snake_case__   ):

            '''simple docstring'''

            _lowerCAmelCase    :							List[str]   			=       F'{self.env.base_job_name}-{instance_count}-{"ddp" if "ddp" in self.script else "smd"}'
            # distributed data settings
            _lowerCAmelCase    :							str   			=       {'smdistributed': {'dataparallel': {'enabled': True}}} if self.script != 'run_ddp.py' else None

            # creates estimator
            return HuggingFace(
                entry_point=self.script      ,	source_dir=self.env.test_path      ,	role=self.env.role      ,	image_uri=self.env.image_uri      ,	base_job_name=snake_case__      ,	instance_count=snake_case__      ,	instance_type=self.instance_type      ,	debugger_hook_config=snake_case__      ,	hyperparameters={**self.env.distributed_hyperparameters, 'model_name_or_path': self.model_name_or_path}      ,	metric_definitions=self.env.metric_definitions      ,	distribution=snake_case__      ,	py_version='py36'      ,	)







     def a	( self      ,	snake_case__   ):

            '''simple docstring'''

            TrainingJobAnalytics(snake_case__   ).export_csv(F'{self.env.test_path}/{job_name}_metrics.csv'   )







     @parameterized.expand([(2,)]   )
     def a	( self      ,	snake_case__   ):

            '''simple docstring'''

            _lowerCAmelCase    :							Dict   			=       self.create_estimator(snake_case__   )

            # run training
            estimator.fit()

            # result dataframe
            _lowerCAmelCase    :							Any   			=       TrainingJobAnalytics(estimator.latest_training_job.name   ).dataframe()

            # extract kpis
            _lowerCAmelCase    :							int   			=       list(result_metrics_df[result_metrics_df.metric_name == 'eval_accuracy']['value']   )
            _lowerCAmelCase    :							Any   			=       list(result_metrics_df[result_metrics_df.metric_name == 'eval_loss']['value']   )
            # get train time from SageMaker job, this includes starting, preprocessing, stopping
            _lowerCAmelCase    :							Dict   			=       (
                Session().describe_training_job(estimator.latest_training_job.name   ).get('TrainingTimeInSeconds'      ,	99_9999   )
            )

            # assert kpis
            assert train_runtime <= self.results["train_runtime"]
            assert all(t >= self.results['eval_accuracy'] for t in eval_accuracy   )
            assert all(t <= self.results['eval_loss'] for t in eval_loss   )

            # dump tests result into json file to share in PR
            with open(F'{estimator.latest_training_job.name}.json'      ,	'w'   ) as outfile:
                   json.dump({'train_time': train_runtime, 'eval_accuracy': eval_accuracy, 'eval_loss': eval_loss}      ,	snake_case__   )





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


lowerCAmelCase    :     int					=						logging.get_logger(__name__)
lowerCAmelCase    :     Union[str, Any]					=						{"""vocab_file""": """spiece.model"""}

lowerCAmelCase    :     Optional[int]					=						{
    """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""",
    }
}

lowerCAmelCase    :     Union[str, Any]					=						{
    """AI-Sweden/gpt-sw3-126m""": 20_48,
    """AI-Sweden/gpt-sw3-350m""": 20_48,
    """AI-Sweden/gpt-sw3-1.6b""": 20_48,
    """AI-Sweden/gpt-sw3-6.7b""": 20_48,
    """AI-Sweden/gpt-sw3-20b""": 20_48,
}
class 	UpperCamelCase__					( SCREAMING_SNAKE_CASE_	):



     """simple docstring"""






     __magic_name__    			=    VOCAB_FILES_NAMES
     __magic_name__    			=    PRETRAINED_VOCAB_FILES_MAP
     __magic_name__    			=    PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
     __magic_name__    			=    ["input_ids", "attention_mask"]







     def __init__( self      ,	snake_case__      ,	snake_case__=False      ,	snake_case__=False      ,	snake_case__=False      ,	snake_case__=None      ,	snake_case__=None      ,	snake_case__=None      ,	snake_case__=None      ,	snake_case__ = None      ,	**snake_case__      ,	):

            '''simple docstring'''

            _lowerCAmelCase    :							Tuple   			=       {} if sp_model_kwargs is None else sp_model_kwargs

            _lowerCAmelCase    :							List[Any]   			=       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'   )
                   _lowerCAmelCase    :							Any   			=       'None'

            # Default definitions for our 2 tokenizer versions, with None-checks to enable proper testing
            _lowerCAmelCase    :							str   			=       '<|endoftext|>' if eos_token is None else eos_token
            _lowerCAmelCase    :							Tuple   			=       '<unk>' if unk_token is None else unk_token
            if "gpt-sw3-7b" in name_or_path:
                   _lowerCAmelCase    :							List[str]   			=       unk_token if pad_token is None else pad_token
                   _lowerCAmelCase    :							Optional[int]   			=       eos_token if bos_token is None else bos_token
            else:
                   _lowerCAmelCase    :							Tuple   			=       '<pad>' if pad_token is None else pad_token
                   _lowerCAmelCase    :							Union[str, Any]   			=       '<s>' if bos_token is None else bos_token

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

            _lowerCAmelCase    :							Union[str, Any]   			=       do_lower_case
            _lowerCAmelCase    :							Optional[int]   			=       remove_space
            _lowerCAmelCase    :							Any   			=       keep_accents
            _lowerCAmelCase    :							Optional[int]   			=       vocab_file

            _lowerCAmelCase    :							Dict   			=       spm.SentencePieceProcessor(**self.sp_model_kwargs   )
            self.sp_model.Load(snake_case__   )

            # Used for whitespace normalization in input texts
            # fmt : off
            _lowerCAmelCase    :							Optional[Any]   			=       {' ', ' ', ' ', ' ', ' ', '　', ' ', ' ', ' ', ' ', '￼', ''}
            # fmt : on

            # Regular expression to remove non-printing characters (e.g. some unicode control chars) in preprocessing
            _lowerCAmelCase    :							Optional[Any]   			=       re.compile(
                F'[{"".join(map(snake_case__      ,	list(range(0      ,	9   )   ) + list(range(11      ,	32   )   ) + list(range(127      ,	160   )   ) + [160, 173, 8203]   )   )}]'   )







     def __getstate__( self   ):

            '''simple docstring'''

            _lowerCAmelCase    :							List[str]   			=       self.__dict__.copy()
            _lowerCAmelCase    :							int   			=       None
            return state







     def __setstate__( self      ,	snake_case__   ):

            '''simple docstring'''

            _lowerCAmelCase    :							Any   			=       d

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

            _lowerCAmelCase    :							List[str]   			=       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 a	( self   ):

            '''simple docstring'''

            return len(self.sp_model   )







     def a	( self      ,	snake_case__   ):

            '''simple docstring'''

            _lowerCAmelCase    :							Optional[int]   			=       self.non_printing_characters_re.sub(''      ,	snake_case__   )

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

            # NFC Unicode normalization
            _lowerCAmelCase    :							Union[str, Any]   			=       unicodedata.normalize('NFC'      ,	snake_case__   )
            return text







     def a	( self      ,	snake_case__      ,	**snake_case__   ):

            '''simple docstring'''

            _lowerCAmelCase    :							str   			=       self.preprocess_text(snake_case__   )
            return self.sp_model.encode(snake_case__      ,	out_type=snake_case__   )







     def a	( self      ,	snake_case__   ):

            '''simple docstring'''

            return self.sp_model.PieceToId(snake_case__   )







     def a	( self      ,	snake_case__   ):

            '''simple docstring'''

            return self.sp_model.IdToPiece(snake_case__   )







     @staticmethod
     def a	( snake_case__   ):

            '''simple docstring'''

            return out_string







     def a	( self      ,	snake_case__   ):

            '''simple docstring'''

            _lowerCAmelCase    :							int   			=       []
            _lowerCAmelCase    :							Optional[Any]   			=       ''
            _lowerCAmelCase    :							Tuple   			=       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(snake_case__   ) + token
                          _lowerCAmelCase    :							Union[str, Any]   			=       True
                          _lowerCAmelCase    :							List[Any]   			=       []
                   else:
                          current_sub_tokens.append(snake_case__   )
                          _lowerCAmelCase    :							List[Any]   			=       False
            out_string += self.sp_model.decode(snake_case__   )

            return out_string







     def a	( self   ):

            '''simple docstring'''

            _lowerCAmelCase    :							Union[str, Any]   			=       {self.convert_ids_to_tokens(snake_case__   ): i for i in range(self.vocab_size   )}
            vocab.update(self.added_tokens_encoder   )
            return vocab







     def a	( self      ,	snake_case__      ,	snake_case__ = None   ):

            '''simple docstring'''

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

            if os.path.abspath(self.vocab_file   ) != os.path.abspath(snake_case__   ) and os.path.isfile(self.vocab_file   ):
                   copyfile(self.vocab_file      ,	snake_case__   )
            elif not os.path.isfile(self.vocab_file   ):
                   with open(snake_case__      ,	'wb'   ) as fi:
                          _lowerCAmelCase    :							Any   			=       self.sp_model.serialized_model_proto()
                          fi.write(snake_case__   )

            return (out_vocab_file,)







     def a	( self      ,	snake_case__      ,	snake_case__ = False   ):

            '''simple docstring'''

            if isinstance(snake_case__      ,	snake_case__   ):
                   _lowerCAmelCase    :							Optional[Any]   			=       self.preprocess_text(snake_case__   )
                   _lowerCAmelCase    :							List[str]   			=       self.sp_model.encode(snake_case__   )
            else:
                   _lowerCAmelCase    :							Tuple   			=       [self.preprocess_text(snake_case__   ) for t in text]
                   _lowerCAmelCase    :							List[str]   			=       self.sp_model.encode(snake_case__   )

            if return_tensors is True or return_tensors == "pt":
                   _lowerCAmelCase    :							int   			=       torch.tensor(snake_case__   )

            return token_ids







     def a	( self      ,	snake_case__   ):

            '''simple docstring'''

            return self.sp_model.decode(snake_case__   )







     def a	( self      ,	snake_case__   ):

            '''simple docstring'''

            _lowerCAmelCase    :							Optional[int]   			=       [F'User: {text}' if is_user else F'Bot: {text}' for is_user, text in conversation.iter_texts()]
            _lowerCAmelCase    :							str   			=       (
                F'{self.eos_token}{self.bos_token}' + F'{self.bos_token}'.join(snake_case__   ) + F'{self.bos_token}Bot:'
            )
            return self.encode(text=snake_case__   )

