






'''simple docstring'''



from __future__ import annotations

import unittest

from transformers import XGLMConfig, XGLMTokenizer, is_tf_available
from transformers.testing_utils import require_tf, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
		import tensorflow as tf

		from transformers.models.xglm.modeling_tf_xglm import (
		    TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST,
		    TFXGLMForCausalLM,
		    TFXGLMModel,
		)


@require_tf
class 						_snake_case   :
					lowerCAmelCase :Any						=   XGLMConfig
					lowerCAmelCase :Optional[Any]						=   {}
					lowerCAmelCase :Optional[int]						=   '''gelu'''




					def __init__( self							,							_lowerCamelCase							,							_lowerCamelCase=14							,							_lowerCamelCase=7							,							_lowerCamelCase=True							,							_lowerCamelCase=True							,							_lowerCamelCase=True							,							_lowerCamelCase=99							,							_lowerCamelCase=32							,							_lowerCamelCase=2							,							_lowerCamelCase=4							,							_lowerCamelCase=37							,							_lowerCamelCase="gelu"							,							_lowerCamelCase=0.1							,							_lowerCamelCase=0.1							,							_lowerCamelCase=512							,							_lowerCamelCase=0.02							,							):
								UpperCAmelCase__					:   List[str]       				=       parent
								UpperCAmelCase__					:   Optional[int]       				=       batch_size
								UpperCAmelCase__					:   Optional[int]       				=       seq_length
								UpperCAmelCase__					:   Optional[int]       				=       is_training
								UpperCAmelCase__					:   Tuple       				=       use_input_mask
								UpperCAmelCase__					:   Optional[Any]       				=       use_labels
								UpperCAmelCase__					:   Optional[Any]       				=       vocab_size
								UpperCAmelCase__					:   List[str]       				=       d_model
								UpperCAmelCase__					:   int       				=       num_hidden_layers
								UpperCAmelCase__					:   Dict       				=       num_attention_heads
								UpperCAmelCase__					:   Optional[Any]       				=       ffn_dim
								UpperCAmelCase__					:   Tuple       				=       activation_function
								UpperCAmelCase__					:   Dict       				=       activation_dropout
								UpperCAmelCase__					:   str       				=       attention_dropout
								UpperCAmelCase__					:   Optional[int]       				=       max_position_embeddings
								UpperCAmelCase__					:   Optional[int]       				=       initializer_range
								UpperCAmelCase__					:   Optional[Any]       				=       None
								UpperCAmelCase__					:   List[Any]       				=       0
								UpperCAmelCase__					:   Optional[Any]       				=       2
								UpperCAmelCase__					:   int       				=       1




					def 			snake_case__  ( self):
								return XGLMConfig.from_pretrained("""facebook/xglm-564M""")




					def 			snake_case__  ( self):
								UpperCAmelCase__					:   List[Any]       				=       tf.clip_by_value(
								    ids_tensor([self.batch_size, self.seq_length]							,							self.vocab_size)							,							clip_value_min=0							,							clip_value_max=3)

								UpperCAmelCase__					:   Dict       				=       None
								if self.use_input_mask:
											UpperCAmelCase__					:   Dict       				=       random_attention_mask([self.batch_size, self.seq_length])

								UpperCAmelCase__					:   Union[str, Any]       				=       self.get_config()

								UpperCAmelCase__					:   int       				=       floats_tensor([self.num_hidden_layers, self.num_attention_heads]							,							2)

								return (
								    config,
								    input_ids,
								    input_mask,
								    head_mask,
								)




					def 			snake_case__  ( self):
								return XGLMConfig(
								    vocab_size=self.vocab_size							,							d_model=self.hidden_size							,							num_layers=self.num_hidden_layers							,							attention_heads=self.num_attention_heads							,							ffn_dim=self.ffn_dim							,							activation_function=self.activation_function							,							activation_dropout=self.activation_dropout							,							attention_dropout=self.attention_dropout							,							max_position_embeddings=self.max_position_embeddings							,							initializer_range=self.initializer_range							,							use_cache=__lowerCamelCase							,							bos_token_id=self.bos_token_id							,							eos_token_id=self.eos_token_id							,							pad_token_id=self.pad_token_id							,							return_dict=__lowerCamelCase							,							)




					def 			snake_case__  ( self):
								UpperCAmelCase__					:   Union[str, Any]       				=       self.prepare_config_and_inputs()

								(
								    (
								    UpperCAmelCase__     
								)				,    (
								    UpperCAmelCase__     
								)				,    (
								    UpperCAmelCase__     
								)				,    (
								    UpperCAmelCase__     
								)				,         
								)					:   Dict       				=       config_and_inputs

								UpperCAmelCase__					:   Any       				=       {
								    """input_ids""": input_ids,
								    """head_mask""": head_mask,
								}

								return config, inputs_dict


@require_tf
class 						_snake_case   (       UpperCamelCase__    ,				UpperCamelCase__    ,				unittest.TestCase		):
					lowerCAmelCase :str						=   (TFXGLMModel, TFXGLMForCausalLM) if is_tf_available() else ()
					lowerCAmelCase :List[str]						=   (TFXGLMForCausalLM,) if is_tf_available() else ()
					lowerCAmelCase :Optional[int]						=   (
					    {'''feature-extraction''': TFXGLMModel, '''text-generation''': TFXGLMForCausalLM} if is_tf_available() else {}
					)
					lowerCAmelCase :Any						=   False
					lowerCAmelCase :Any						=   False
					lowerCAmelCase :Dict						=   False




					def 			snake_case__  ( self):
								UpperCAmelCase__					:   Optional[Any]       				=       TFXGLMModelTester(self)
								UpperCAmelCase__					:   Optional[int]       				=       ConfigTester(self							,							config_class=__lowerCamelCase							,							n_embd=37)




					def 			snake_case__  ( self):
								self.config_tester.run_common_tests()




					@slow
					def 			snake_case__  ( self):
								for model_name in TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
											UpperCAmelCase__					:   int       				=       TFXGLMModel.from_pretrained(__lowerCamelCase)
											self.assertIsNotNone(__lowerCamelCase)




					@unittest.skip(reason="""Currently, model embeddings are going to undergo a major refactor.""")
					def 			snake_case__  ( self):
								super().test_resize_token_embeddings()


@require_tf
class 						_snake_case   (       unittest.TestCase		):




					@slow
					def 			snake_case__  ( self							,							_lowerCamelCase=True):
								UpperCAmelCase__					:   Any       				=       TFXGLMForCausalLM.from_pretrained("""facebook/xglm-564M""")
								UpperCAmelCase__					:   List[Any]       				=       tf.convert_to_tensor([[2, 268, 9865]]							,							dtype=tf.intaa)  # The dog
								# </s> The dog is a very friendly dog. He is very affectionate and loves to play with other
								# fmt: off
								UpperCAmelCase__					:   List[str]       				=       [2, 268, 9865, 67, 11, 1988, 5_7252, 9865, 5, 984, 67, 1988, 21_3838, 1658, 53, 7_0446, 33, 6657, 278, 1581]
								# fmt: on
								UpperCAmelCase__					:   int       				=       model.generate(__lowerCamelCase							,							do_sample=__lowerCamelCase							,							num_beams=1)
								if verify_outputs:
											self.assertListEqual(output_ids[0].numpy().tolist()							,							__lowerCamelCase)




					@slow
					def 			snake_case__  ( self):
								UpperCAmelCase__					:   str       				=       XGLMTokenizer.from_pretrained("""facebook/xglm-564M""")
								UpperCAmelCase__					:   List[str]       				=       TFXGLMForCausalLM.from_pretrained("""facebook/xglm-564M""")

								tf.random.set_seed(0)
								UpperCAmelCase__					:   Any       				=       tokenizer("""Today is a nice day and"""							,							return_tensors="""tf""")
								UpperCAmelCase__					:   Optional[Any]       				=       tokenized.input_ids
								# forces the generation to happen on CPU, to avoid GPU-related quirks (and assure same output regardless of the available devices)
								with tf.device(""":/CPU:0"""):
											UpperCAmelCase__					:   List[Any]       				=       model.generate(__lowerCamelCase							,							do_sample=__lowerCamelCase							,							seed=[7, 0])
								UpperCAmelCase__					:   Union[str, Any]       				=       tokenizer.decode(output_ids[0]							,							skip_special_tokens=__lowerCamelCase)

								UpperCAmelCase__					:   int       				=       (
								    """Today is a nice day and warm evening here over Southern Alberta!! Today when they closed schools due"""
								)
								self.assertEqual(__lowerCamelCase							,							__lowerCamelCase)




					@slow
					def 			snake_case__  ( self):
								UpperCAmelCase__					:   Tuple       				=       TFXGLMForCausalLM.from_pretrained("""facebook/xglm-564M""")
								UpperCAmelCase__					:   str       				=       XGLMTokenizer.from_pretrained("""facebook/xglm-564M""")

								UpperCAmelCase__					:   Optional[int]       				=       """left"""

								# use different length sentences to test batching
								UpperCAmelCase__					:   str       				=       [
								    """This is an extremelly long sentence that only exists to test the ability of the model to cope with """
								    """left-padding, such as in batched generation. The output for the sequence below should be the same """
								    """regardless of whether left padding is applied or not. When""",
								    """Hello, my dog is a little""",
								]

								UpperCAmelCase__					:   Optional[int]       				=       tokenizer(__lowerCamelCase							,							return_tensors="""tf"""							,							padding=__lowerCamelCase)
								UpperCAmelCase__					:   int       				=       inputs["""input_ids"""]

								UpperCAmelCase__					:   Optional[int]       				=       model.generate(input_ids=__lowerCamelCase							,							attention_mask=inputs["""attention_mask"""]							,							max_new_tokens=12)

								UpperCAmelCase__					:   str       				=       tokenizer(sentences[0]							,							return_tensors="""tf""").input_ids
								UpperCAmelCase__					:   List[Any]       				=       model.generate(input_ids=__lowerCamelCase							,							max_new_tokens=12)

								UpperCAmelCase__					:   Dict       				=       tokenizer(sentences[1]							,							return_tensors="""tf""").input_ids
								UpperCAmelCase__					:   str       				=       model.generate(input_ids=__lowerCamelCase							,							max_new_tokens=12)

								UpperCAmelCase__					:   Union[str, Any]       				=       tokenizer.batch_decode(__lowerCamelCase							,							skip_special_tokens=__lowerCamelCase)
								UpperCAmelCase__					:   Union[str, Any]       				=       tokenizer.decode(output_non_padded[0]							,							skip_special_tokens=__lowerCamelCase)
								UpperCAmelCase__					:   List[Any]       				=       tokenizer.decode(output_padded[0]							,							skip_special_tokens=__lowerCamelCase)

								UpperCAmelCase__					:   str       				=       [
								    """This is an extremelly long sentence that only exists to test the ability of the model to cope with """
								    """left-padding, such as in batched generation. The output for the sequence below should be the same """
								    """regardless of whether left padding is applied or not. When left padding is applied, the sequence will be """
								    """a single""",
								    """Hello, my dog is a little bit of a shy one, but he is very friendly""",
								]
								self.assertListEqual(__lowerCamelCase							,							__lowerCamelCase)
								self.assertListEqual(__lowerCamelCase							,							[non_padded_sentence, padded_sentence])



'''simple docstring'''



import os
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple

import sentencepiece as spm

from ...tokenization_utils import AddedToken, BatchEncoding, PreTrainedTokenizer
from ...utils import logging


__A		=logging.get_logger(__name__)

__A		='▁'

__A		={'vocab_file': 'sentencepiece.bpe.model'}

__A		={
    'vocab_file': {
        'facebook/mbart-large-50-one-to-many-mmt': (
            'https://huggingface.co/facebook/mbart-large-50-one-to-many-mmt/resolve/main/sentencepiece.bpe.model'
        ),
    }
}

__A		={
    'facebook/mbart-large-50-one-to-many-mmt': 10_24,
}

# fmt: off
__A		=['ar_AR', 'cs_CZ', 'de_DE', 'en_XX', 'es_XX', 'et_EE', 'fi_FI', 'fr_XX', 'gu_IN', 'hi_IN', 'it_IT', 'ja_XX', 'kk_KZ', 'ko_KR', 'lt_LT', 'lv_LV', 'my_MM', 'ne_NP', 'nl_XX', 'ro_RO', 'ru_RU', 'si_LK', 'tr_TR', 'vi_VN', 'zh_CN', 'af_ZA', 'az_AZ', 'bn_IN', 'fa_IR', 'he_IL', 'hr_HR', 'id_ID', 'ka_GE', 'km_KH', 'mk_MK', 'ml_IN', 'mn_MN', 'mr_IN', 'pl_PL', 'ps_AF', 'pt_XX', 'sv_SE', 'sw_KE', 'ta_IN', 'te_IN', 'th_TH', 'tl_XX', 'uk_UA', 'ur_PK', 'xh_ZA', 'gl_ES', 'sl_SI']


class 						_snake_case   (       a__		):
					lowerCAmelCase :int						=   VOCAB_FILES_NAMES
					lowerCAmelCase :Dict						=   PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
					lowerCAmelCase :str						=   PRETRAINED_VOCAB_FILES_MAP
					lowerCAmelCase :List[str]						=   ['''input_ids''', '''attention_mask''']

					lowerCAmelCase :List[int]						=   []
					lowerCAmelCase :List[int]						=   []




					def __init__( self							,							_lowerCamelCase							,							_lowerCamelCase=None							,							_lowerCamelCase=None							,							_lowerCamelCase="</s>"							,							_lowerCamelCase="</s>"							,							_lowerCamelCase="<s>"							,							_lowerCamelCase="<unk>"							,							_lowerCamelCase="<pad>"							,							_lowerCamelCase="<mask>"							,							_lowerCamelCase = None							,							**_lowerCamelCase							,							):
								# Mask token behave like a normal word, i.e. include the space before it
								UpperCAmelCase__					:   List[str]       				=       AddedToken(_lowerCamelCase							,							lstrip=_lowerCamelCase							,							rstrip=_lowerCamelCase) if isinstance(_lowerCamelCase							,							_lowerCamelCase) else mask_token

								UpperCAmelCase__					:   Dict       				=       {} if sp_model_kwargs is None else sp_model_kwargs

								UpperCAmelCase__					:   Dict       				=       kwargs.get("""additional_special_tokens"""							,							[])
								kwargs["additional_special_tokens"] += [
								    code for code in FAIRSEQ_LANGUAGE_CODES if code not in kwargs["additional_special_tokens"]
								]

								super().__init__(
								    src_lang=_lowerCamelCase							,							tgt_lang=_lowerCamelCase							,							eos_token=_lowerCamelCase							,							unk_token=_lowerCamelCase							,							sep_token=_lowerCamelCase							,							cls_token=_lowerCamelCase							,							pad_token=_lowerCamelCase							,							mask_token=_lowerCamelCase							,							sp_model_kwargs=self.sp_model_kwargs							,							**_lowerCamelCase							,							)

								UpperCAmelCase__					:   str       				=       spm.SentencePieceProcessor(**self.sp_model_kwargs)
								self.sp_model.Load(str(_lowerCamelCase))
								UpperCAmelCase__					:   int       				=       vocab_file

								# Original fairseq vocab and spm vocab must be "aligned":
								# Vocab    |    0    |    1    |   2    |    3    |  4  |  5  |  6  |   7   |   8   |  9
								# -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ----
								# fairseq  | '<s>'   | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's'   | '▁de' | '-'
								# spm      | '<unk>' | '<s>'   | '</s>' | ','     | '.' | '▁' | 's' | '▁de' | '-'   | '▁a'

								# Mimic fairseq token-to-id alignment for the first 4 token
								UpperCAmelCase__					:   Union[str, Any]       				=       {"""<s>""": 0, """<pad>""": 1, """</s>""": 2, """<unk>""": 3}

								# The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab
								UpperCAmelCase__					:   List[str]       				=       1

								UpperCAmelCase__					:   Optional[int]       				=       len(self.sp_model)
								UpperCAmelCase__					:   List[str]       				=       {
								    code: self.sp_model_size + i + self.fairseq_offset for i, code in enumerate(_lowerCamelCase)
								}
								UpperCAmelCase__					:   Optional[int]       				=       {v: k for k, v in self.lang_code_to_id.items()}
								UpperCAmelCase__					:   Optional[int]       				=       len(self.sp_model) + len(self.lang_code_to_id) + self.fairseq_offset

								self.fairseq_tokens_to_ids.update(self.lang_code_to_id)
								UpperCAmelCase__					:   Union[str, Any]       				=       {v: k for k, v in self.fairseq_tokens_to_ids.items()}

								UpperCAmelCase__					:   Dict       				=       src_lang if src_lang is not None else """en_XX"""
								UpperCAmelCase__					:   str       				=       self.lang_code_to_id[self._src_lang]
								UpperCAmelCase__					:   Tuple       				=       tgt_lang
								self.set_src_lang_special_tokens(self._src_lang)




					@property
					def 			snake_case__  ( self):
								return len(self.sp_model) + len(self.lang_code_to_id) + self.fairseq_offset + 1  # Plus 1 for the mask token




					@property
					def 			snake_case__  ( self):
								return self._src_lang




					@src_lang.setter
					def 			snake_case__  ( self							,							_lowerCamelCase):
								UpperCAmelCase__					:   str       				=       new_src_lang
								self.set_src_lang_special_tokens(self._src_lang)




					def __getstate__( self):
								UpperCAmelCase__					:   int       				=       self.__dict__.copy()
								UpperCAmelCase__					:   Tuple       				=       None
								return state




					def __setstate__( self							,							_lowerCamelCase):
								UpperCAmelCase__					:   Union[str, Any]       				=       d

								# for backward compatibility
								if not hasattr(self							,							"""sp_model_kwargs"""):
											UpperCAmelCase__					:   Optional[Any]       				=       {}

								UpperCAmelCase__					:   Any       				=       spm.SentencePieceProcessor(**self.sp_model_kwargs)
								self.sp_model.Load(self.vocab_file)




					def 			snake_case__  ( self):
								UpperCAmelCase__					:   Dict       				=       {self.convert_ids_to_tokens(_lowerCamelCase): i for i in range(self.vocab_size)}
								vocab.update(self.added_tokens_encoder)
								return vocab




					def 			snake_case__  ( self							,							_lowerCamelCase):
								return self.sp_model.encode(_lowerCamelCase							,							out_type=_lowerCamelCase)




					def 			snake_case__  ( self							,							_lowerCamelCase):
								if token in self.fairseq_tokens_to_ids:
											return self.fairseq_tokens_to_ids[token]
								UpperCAmelCase__					:   Dict       				=       self.sp_model.PieceToId(_lowerCamelCase)

								# Need to return unknown token if the SP model returned 0
								return spm_id + self.fairseq_offset if spm_id else self.unk_token_id




					def 			snake_case__  ( self							,							_lowerCamelCase):
								if index in self.fairseq_ids_to_tokens:
											return self.fairseq_ids_to_tokens[index]
								return self.sp_model.IdToPiece(index - self.fairseq_offset)




					def 			snake_case__  ( self							,							_lowerCamelCase):
								UpperCAmelCase__					:   Optional[Any]       				=       []
								UpperCAmelCase__					:   List[Any]       				=       """"""
								UpperCAmelCase__					:   Optional[int]       				=       False
								for token in tokens:
											# make sure that special tokens are not decoded using sentencepiece model
											if token in self.all_special_tokens:
														if not prev_is_special:
																	out_string += " "
														out_string += self.sp_model.decode(_lowerCamelCase) + token
														UpperCAmelCase__					:   Tuple       				=       True
														UpperCAmelCase__					:   List[str]       				=       []
											else:
														current_sub_tokens.append(_lowerCamelCase)
														UpperCAmelCase__					:   Dict       				=       False
								out_string += self.sp_model.decode(_lowerCamelCase)
								return out_string.strip()




					def 			snake_case__  ( self							,							_lowerCamelCase							,							_lowerCamelCase = None):
								if not os.path.isdir(_lowerCamelCase):
											logger.error(f'''Vocabulary path ({save_directory}) should be a directory''')
											return
								UpperCAmelCase__					:   Any       				=       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:
														UpperCAmelCase__					:   List[str]       				=       self.sp_model.serialized_model_proto()
														fi.write(_lowerCamelCase)

								return (out_vocab_file,)




					def 			snake_case__  ( self							,							_lowerCamelCase							,							_lowerCamelCase = None							,							_lowerCamelCase = False):

								if already_has_special_tokens:
											return super().get_special_tokens_mask(
											    token_ids_a=_lowerCamelCase							,							token_ids_a=_lowerCamelCase							,							already_has_special_tokens=_lowerCamelCase)

								UpperCAmelCase__					:   Tuple       				=       [1] * len(self.prefix_tokens)
								UpperCAmelCase__					:   Dict       				=       [1] * len(self.suffix_tokens)
								if token_ids_a is None:
											return prefix_ones + ([0] * len(_lowerCamelCase)) + suffix_ones
								return prefix_ones + ([0] * len(_lowerCamelCase)) + ([0] * len(_lowerCamelCase)) + suffix_ones




					def 			snake_case__  ( self							,							_lowerCamelCase							,							_lowerCamelCase = None):
								if token_ids_a is None:
											return self.prefix_tokens + token_ids_a + self.suffix_tokens
								# We don't expect to process pairs, but leave the pair logic for API consistency
								return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens




					def 			snake_case__  ( self							,							_lowerCamelCase							,							_lowerCamelCase							,							_lowerCamelCase							,							_lowerCamelCase							,							**_lowerCamelCase):
								if src_lang is None or tgt_lang is None:
											raise ValueError("""Translation requires a `src_lang` and a `tgt_lang` for this model""")
								UpperCAmelCase__					:   Any       				=       src_lang
								UpperCAmelCase__					:   Dict       				=       self(_lowerCamelCase							,							add_special_tokens=_lowerCamelCase							,							return_tensors=_lowerCamelCase							,							**_lowerCamelCase)
								UpperCAmelCase__					:   List[Any]       				=       self.convert_tokens_to_ids(_lowerCamelCase)
								UpperCAmelCase__					:   List[str]       				=       tgt_lang_id
								return inputs




					def 			snake_case__  ( self							,							_lowerCamelCase							,							_lowerCamelCase = "en_XX"							,							_lowerCamelCase = None							,							_lowerCamelCase = "ro_RO"							,							**_lowerCamelCase							,							):
								UpperCAmelCase__					:   Tuple       				=       src_lang
								UpperCAmelCase__					:   Optional[Any]       				=       tgt_lang
								return super().prepare_seqaseq_batch(_lowerCamelCase							,							_lowerCamelCase							,							**_lowerCamelCase)




					def 			snake_case__  ( self):
								return self.set_src_lang_special_tokens(self.src_lang)




					def 			snake_case__  ( self):
								return self.set_tgt_lang_special_tokens(self.tgt_lang)




					def 			snake_case__  ( self							,							_lowerCamelCase):
								UpperCAmelCase__					:   Tuple       				=       self.lang_code_to_id[src_lang]
								UpperCAmelCase__					:   Optional[int]       				=       [self.cur_lang_code_id]
								UpperCAmelCase__					:   Optional[int]       				=       [self.eos_token_id]




					def 			snake_case__  ( self							,							_lowerCamelCase):
								UpperCAmelCase__					:   List[Any]       				=       self.lang_code_to_id[tgt_lang]
								UpperCAmelCase__					:   Dict       				=       [self.cur_lang_code_id]
								UpperCAmelCase__					:   Optional[int]       				=       [self.eos_token_id]