






"""simple docstring"""







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

import sentencepiece as spm

from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging


__a       :	Optional[Any]             = logging.get_logger(__name__)

__a       :	Dict             = '▁'

__a       :	Optional[int]             = {'vocab_file': 'sentencepiece.bpe.model'}

__a       :	Union[str, Any]             = {
    'vocab_file': {
        'facebook/xglm-564M': 'https://huggingface.co/facebook/xglm-564M/resolve/main/sentencepiece.bpe.model',
    }
}

__a       :	Any             = {
    'facebook/xglm-564M': 2048,
}







class        _SCREAMING_SNAKE_CASE						(  __snake_case							):





							"""simple docstring"""





							_SCREAMING_SNAKE_CASE    =VOCAB_FILES_NAMES
							_SCREAMING_SNAKE_CASE    =PRETRAINED_VOCAB_FILES_MAP
							_SCREAMING_SNAKE_CASE    =PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
							_SCREAMING_SNAKE_CASE    =['input_ids', 'attention_mask']




							def __init__(   self:     Union[str, Any]				,		__A:     str				,		__A:     Tuple="<s>"				,		__A:     List[str]="</s>"				,		__A:     List[Any]="</s>"				,		__A:     str="<s>"				,		__A:     str="<unk>"				,		__A:     int="<pad>"				,		__A:     Optional[Dict[str, Any]] = None				,		**__A:     Dict				,		):

												'''simple docstring'''

												a__          =  {} if sp_model_kwargs is None else sp_model_kwargs

												# Compatibility with the original tokenizer
												a__          =  7
												a__          =  [F'<madeupword{i}>' for i in range(self.num_madeup_words    )]

												a__          =  kwargs.get('''additional_special_tokens'''				,		[]    )
												kwargs["additional_special_tokens"] += [
												    word for word in madeup_words if word not in kwargs["additional_special_tokens"]
												]

												super().__init__(
												    bos_token=__A				,		eos_token=__A				,		unk_token=__A				,		sep_token=__A				,		cls_token=__A				,		pad_token=__A				,		sp_model_kwargs=self.sp_model_kwargs				,		**__A				,		)

												a__          =  spm.SentencePieceProcessor(**self.sp_model_kwargs    )
												self.sp_model.Load(str(__A    )    )
												a__          =  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'

												# The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab
												a__          =  1

												# Mimic fairseq token-to-id alignment for the first 4 token
												a__          =  {'''<s>''': 0, '''<pad>''': 1, '''</s>''': 2, '''<unk>''': 3}

												a__          =  len(self.sp_model    )
												a__          =  {F'<madeupword{i}>': sp_size + i + self.fairseq_offset for i in range(self.num_madeup_words    )}
												self.fairseq_tokens_to_ids.update(__A    )

												a__          =  {v: k for k, v in self.fairseq_tokens_to_ids.items()}




							def __getstate__(   self:     Optional[Any]    ):

												'''simple docstring'''

												a__          =  self.__dict__.copy()
												a__          =  None
												a__          =  self.sp_model.serialized_model_proto()
												return state




							def __setstate__(   self:     Any				,		__A:     Any    ):

												'''simple docstring'''

												a__          =  d

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

												a__          =  spm.SentencePieceProcessor(**self.sp_model_kwargs    )
												self.sp_model.LoadFromSerializedProto(self.sp_model_proto    )




							def  lowercase		(   self:     str				,		__A:     List[int]				,		__A:     Optional[List[int]] = None    ):

												'''simple docstring'''

												if token_ids_a is None:
																	return [self.sep_token_id] + token_ids_a
												a__          =  [self.sep_token_id]
												return sep + token_ids_a + sep + sep + token_ids_a




							def  lowercase		(   self:     Optional[int]				,		__A:     List[int]				,		__A:     Optional[List[int]] = None				,		__A:     bool = False    ):

												'''simple docstring'''

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

												if token_ids_a is None:
																	return [1] + ([0] * len(__A    ))
												return [1] + ([0] * len(__A    )) + [1, 1] + ([0] * len(__A    ))




							def  lowercase		(   self:     int				,		__A:     List[int]				,		__A:     Optional[List[int]] = None    ):

												'''simple docstring'''

												a__          =  [self.sep_token_id]

												if token_ids_a is None:
																	return len(sep + token_ids_a    ) * [0]
												return len(sep + token_ids_a + sep + sep + token_ids_a    ) * [0]




							@property
							def  lowercase		(   self:     List[Any]    ):

												'''simple docstring'''

												return len(self.sp_model    ) + self.fairseq_offset + self.num_madeup_words




							def  lowercase		(   self:     Optional[int]    ):

												'''simple docstring'''

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




							def  lowercase		(   self:     Optional[int]				,		__A:     str    ):

												'''simple docstring'''

												return self.sp_model.encode(__A				,		out_type=__A    )




							def  lowercase		(   self:     Dict				,		__A:     Optional[Any]    ):

												'''simple docstring'''

												if token in self.fairseq_tokens_to_ids:
																	return self.fairseq_tokens_to_ids[token]
												a__          =  self.sp_model.PieceToId(__A    )

												# 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  lowercase		(   self:     Dict				,		__A:     int    ):

												'''simple docstring'''

												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  lowercase		(   self:     Optional[Any]				,		__A:     int    ):

												'''simple docstring'''

												a__          =  ''''''.join(__A    ).replace(__A				,		''' '''    ).strip()
												return out_string





							def  lowercase		(   self:     Dict				,		__A:     str				,		__A:     Optional[str] = None    ):

												'''simple docstring'''

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

												return (out_vocab_file,)










"""simple docstring"""







import unittest

from transformers import BertGenerationConfig, is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device

from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
	import torch

	from transformers import BertGenerationDecoder, BertGenerationEncoder







class        _SCREAMING_SNAKE_CASE						:





							"""simple docstring"""





							def __init__(   self:     Optional[Any]				,		__A:     List[Any]				,		__A:     Optional[int]=13				,		__A:     Tuple=7				,		__A:     Optional[Any]=True				,		__A:     Tuple=True				,		__A:     str=99				,		__A:     int=32				,		__A:     Union[str, Any]=5				,		__A:     Optional[Any]=4				,		__A:     Any=37				,		__A:     Union[str, Any]="gelu"				,		__A:     int=0.1				,		__A:     Optional[Any]=0.1				,		__A:     Optional[int]=50				,		__A:     str=0.0_2				,		__A:     Dict=True				,		__A:     Dict=None				,		):

												'''simple docstring'''

												a__          =  parent
												a__          =  batch_size
												a__          =  seq_length
												a__          =  is_training
												a__          =  use_input_mask
												a__          =  vocab_size
												a__          =  hidden_size
												a__          =  num_hidden_layers
												a__          =  num_attention_heads
												a__          =  intermediate_size
												a__          =  hidden_act
												a__          =  hidden_dropout_prob
												a__          =  attention_probs_dropout_prob
												a__          =  max_position_embeddings
												a__          =  initializer_range
												a__          =  use_labels
												a__          =  scope




							def  lowercase		(   self:     List[Any]    ):

												'''simple docstring'''

												a__          =  ids_tensor([self.batch_size, self.seq_length]				,		self.vocab_size    )

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

												if self.use_labels:
																	a__          =  ids_tensor([self.batch_size, self.seq_length]				,		self.vocab_size    )

												a__          =  self.get_config()

												return config, input_ids, input_mask, token_labels




							def  lowercase		(   self:     int    ):

												'''simple docstring'''

												return BertGenerationConfig(
												    vocab_size=self.vocab_size				,		hidden_size=self.hidden_size				,		num_hidden_layers=self.num_hidden_layers				,		num_attention_heads=self.num_attention_heads				,		intermediate_size=self.intermediate_size				,		hidden_act=self.hidden_act				,		hidden_dropout_prob=self.hidden_dropout_prob				,		attention_probs_dropout_prob=self.attention_probs_dropout_prob				,		max_position_embeddings=self.max_position_embeddings				,		is_decoder=__A				,		initializer_range=self.initializer_range				,		)




							def  lowercase		(   self:     List[str]    ):

												'''simple docstring'''

												(
												    (
												    a__
												)       ,(
												    a__
												)       ,(
												    a__
												)       ,(
												    a__
												)       ,
												)          =  self.prepare_config_and_inputs()

												a__          =  True
												a__          =  floats_tensor([self.batch_size, self.seq_length, self.hidden_size]    )
												a__          =  ids_tensor([self.batch_size, self.seq_length]				,		vocab_size=2    )

												return (
												    config,
												    input_ids,
												    input_mask,
												    token_labels,
												    encoder_hidden_states,
												    encoder_attention_mask,
												)




							def  lowercase		(   self:     str				,		__A:     List[str]				,		__A:     Optional[int]				,		__A:     Union[str, Any]				,		__A:     Optional[int]				,		**__A:     Union[str, Any]				,		):

												'''simple docstring'''

												a__          =  BertGenerationEncoder(config=__A    )
												model.to(__A    )
												model.eval()
												a__          =  model(__A				,		attention_mask=__A    )
												a__          =  model(__A    )
												self.parent.assertEqual(result.last_hidden_state.shape				,		(self.batch_size, self.seq_length, self.hidden_size)    )




							def  lowercase		(   self:     Optional[Any]				,		__A:     Any				,		__A:     int				,		__A:     Optional[int]				,		__A:     int				,		__A:     List[Any]				,		__A:     Any				,		**__A:     List[str]				,		):

												'''simple docstring'''

												a__          =  True
												a__          =  BertGenerationEncoder(config=__A    )
												model.to(__A    )
												model.eval()
												a__          =  model(
												    __A				,		attention_mask=__A				,		encoder_hidden_states=__A				,		encoder_attention_mask=__A				,		)
												a__          =  model(
												    __A				,		attention_mask=__A				,		encoder_hidden_states=__A				,		)
												self.parent.assertEqual(result.last_hidden_state.shape				,		(self.batch_size, self.seq_length, self.hidden_size)    )




							def  lowercase		(   self:     Dict				,		__A:     Tuple				,		__A:     str				,		__A:     str				,		__A:     Any				,		__A:     int				,		__A:     Any				,		**__A:     Dict				,		):

												'''simple docstring'''

												a__          =  True
												a__          =  True
												a__          =  BertGenerationDecoder(config=__A    ).to(__A    ).eval()

												# first forward pass
												a__          =  model(
												    __A				,		attention_mask=__A				,		encoder_hidden_states=__A				,		encoder_attention_mask=__A				,		use_cache=__A				,		)
												a__          =  outputs.past_key_values

												# create hypothetical multiple next token and extent to next_input_ids
												a__          =  ids_tensor((self.batch_size, 3)				,		config.vocab_size    )
												a__          =  ids_tensor((self.batch_size, 3)				,		vocab_size=2    )

												# append to next input_ids and
												a__          =  torch.cat([input_ids, next_tokens]				,		dim=-1    )
												a__          =  torch.cat([input_mask, next_mask]				,		dim=-1    )

												a__          =  model(
												    __A				,		attention_mask=__A				,		encoder_hidden_states=__A				,		encoder_attention_mask=__A				,		output_hidden_states=__A				,		)['''hidden_states'''][0]
												a__          =  model(
												    __A				,		attention_mask=__A				,		encoder_hidden_states=__A				,		encoder_attention_mask=__A				,		past_key_values=__A				,		output_hidden_states=__A				,		)['''hidden_states'''][0]

												# select random slice
												a__          =  ids_tensor((1,)				,		output_from_past.shape[-1]    ).item()
												a__          =  output_from_no_past[:, -3:, random_slice_idx].detach()
												a__          =  output_from_past[:, :, random_slice_idx].detach()

												self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1]    )

												# test that outputs are equal for slice
												self.parent.assertTrue(torch.allclose(__A				,		__A				,		atol=1e-3    )    )




							def  lowercase		(   self:     Optional[Any]				,		__A:     List[Any]				,		__A:     List[Any]				,		__A:     Union[str, Any]				,		__A:     Optional[Any]				,		*__A:     Optional[int]				,		):

												'''simple docstring'''

												a__          =  BertGenerationDecoder(__A    )
												model.to(__A    )
												model.eval()
												a__          =  model(__A				,		attention_mask=__A				,		labels=__A    )
												self.parent.assertEqual(result.logits.shape				,		(self.batch_size, self.seq_length, self.vocab_size)    )





							def  lowercase		(   self:     Dict    ):

												'''simple docstring'''

												a__       ,a__       ,a__       ,a__          =  self.prepare_config_and_inputs()
												a__          =  {'''input_ids''': input_ids, '''attention_mask''': input_mask}
												return config, inputs_dict







@require_torch
class        _SCREAMING_SNAKE_CASE						(  __snake_case       , __snake_case       , __snake_case       , unittest.TestCase							):





							"""simple docstring"""





							_SCREAMING_SNAKE_CASE    =(BertGenerationEncoder, BertGenerationDecoder) if is_torch_available() else ()
							_SCREAMING_SNAKE_CASE    =(BertGenerationDecoder,) if is_torch_available() else ()
							_SCREAMING_SNAKE_CASE    =(
							    {'feature-extraction': BertGenerationEncoder, 'text-generation': BertGenerationDecoder}
							    if is_torch_available()
							    else {}
							)




							def  lowercase		(   self:     Optional[int]    ):

												'''simple docstring'''

												a__          =  BertGenerationEncoderTester(self    )
												a__          =  ConfigTester(self				,		config_class=__A				,		hidden_size=37    )




							def  lowercase		(   self:     Optional[int]    ):

												'''simple docstring'''

												self.config_tester.run_common_tests()




							def  lowercase		(   self:     Union[str, Any]    ):

												'''simple docstring'''

												a__          =  self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_model(*__A    )




							def  lowercase		(   self:     Any    ):

												'''simple docstring'''

												a__       ,a__       ,a__       ,a__          =  self.model_tester.prepare_config_and_inputs()
												a__          =  '''bert'''
												self.model_tester.create_and_check_model(__A				,		__A				,		__A				,		__A    )




							def  lowercase		(   self:     int    ):

												'''simple docstring'''

												a__          =  self.model_tester.prepare_config_and_inputs_for_decoder()
												self.model_tester.create_and_check_model_as_decoder(*__A    )




							def  lowercase		(   self:     List[str]    ):

												'''simple docstring'''

												a__          =  self.model_tester.prepare_config_and_inputs_for_decoder()
												self.model_tester.create_and_check_decoder_model_past_large_inputs(*__A    )




							def  lowercase		(   self:     Union[str, Any]    ):

												'''simple docstring'''

												(
												    (
												    a__
												)       ,(
												    a__
												)       ,(
												    a__
												)       ,(
												    a__
												)       ,(
												    a__
												)       ,(
												    a__
												)       ,
												)          =  self.model_tester.prepare_config_and_inputs_for_decoder()

												a__          =  None

												self.model_tester.create_and_check_model_as_decoder(
												    __A				,		__A				,		__A				,		__A				,		__A				,		__A				,		)




							def  lowercase		(   self:     str    ):

												'''simple docstring'''

												a__          =  self.model_tester.prepare_config_and_inputs_for_decoder()
												self.model_tester.create_and_check_for_causal_lm(*__A    )





							@slow
							def  lowercase		(   self:     Dict    ):

												'''simple docstring'''

												a__          =  BertGenerationEncoder.from_pretrained('''google/bert_for_seq_generation_L-24_bbc_encoder'''    )
												self.assertIsNotNone(__A    )







@require_torch
class        _SCREAMING_SNAKE_CASE						(  unittest.TestCase							):





							"""simple docstring"""





							@slow
							def  lowercase		(   self:     Optional[Any]    ):

												'''simple docstring'''

												a__          =  BertGenerationEncoder.from_pretrained('''google/bert_for_seq_generation_L-24_bbc_encoder'''    )
												a__          =  torch.tensor([[101, 7592, 1010, 2026, 3899, 2003, 10140, 102]]    )
												with torch.no_grad():
																	a__          =  model(__A    )[0]
												a__          =  torch.Size([1, 8, 1024]    )
												self.assertEqual(output.shape				,		__A    )
												a__          =  torch.tensor(
												    [[[0.1_7_7_5, 0.0_0_8_3, -0.0_3_2_1], [1.6_0_0_2, 0.1_2_8_7, 0.3_9_1_2], [2.1_4_7_3, 0.5_7_9_1, 0.6_0_6_6]]]    )
												self.assertTrue(torch.allclose(output[:, :3, :3]				,		__A				,		atol=1e-4    )    )







@require_torch
class        _SCREAMING_SNAKE_CASE						(  unittest.TestCase							):





							"""simple docstring"""





							@slow
							def  lowercase		(   self:     List[Any]    ):

												'''simple docstring'''

												a__          =  BertGenerationDecoder.from_pretrained('''google/bert_for_seq_generation_L-24_bbc_encoder'''    )
												a__          =  torch.tensor([[101, 7592, 1010, 2026, 3899, 2003, 10140, 102]]    )
												with torch.no_grad():
																	a__          =  model(__A    )[0]
												a__          =  torch.Size([1, 8, 50358]    )
												self.assertEqual(output.shape				,		__A    )
												a__          =  torch.tensor(
												    [[[-0.5_7_8_8, -2.5_9_9_4, -3.7_0_5_4], [0.0_4_3_8, 4.7_9_9_7, 1.8_7_9_5], [1.5_8_6_2, 6.6_4_0_9, 4.4_6_3_8]]]    )
												self.assertTrue(torch.allclose(output[:, :3, :3]				,		__A				,		atol=1e-4    )    )


