






"""simple docstring"""







import json
import os
import sys
import tempfile
import unittest
from pathlib import Path
from shutil import copyfile

from huggingface_hub import HfFolder, Repository, create_repo, delete_repo
from requests.exceptions import HTTPError

import transformers
from transformers import (
    CONFIG_MAPPING,
    FEATURE_EXTRACTOR_MAPPING,
    PROCESSOR_MAPPING,
    TOKENIZER_MAPPING,
    AutoConfig,
    AutoFeatureExtractor,
    AutoProcessor,
    AutoTokenizer,
    BertTokenizer,
    ProcessorMixin,
    WavaVecaConfig,
    WavaVecaFeatureExtractor,
    WavaVecaProcessor,
)
from transformers.testing_utils import TOKEN, USER, get_tests_dir, is_staging_test
from transformers.tokenization_utils import TOKENIZER_CONFIG_FILE
from transformers.utils import FEATURE_EXTRACTOR_NAME, is_tokenizers_available


sys.path.append(str(Path(__file__).parent.parent.parent.parent / 'utils'))

from test_module.custom_configuration import CustomConfig  # noqa E402
from test_module.custom_feature_extraction import CustomFeatureExtractor  # noqa E402
from test_module.custom_processing import CustomProcessor  # noqa E402
from test_module.custom_tokenization import CustomTokenizer  # noqa E402


__a       :	Any             = get_tests_dir('fixtures/dummy_feature_extractor_config.json')
__a       :	Optional[Any]             = get_tests_dir('fixtures/vocab.json')
__a       :	List[Any]             = get_tests_dir('fixtures')







class        _SCREAMING_SNAKE_CASE						(  unittest.TestCase							):





							"""simple docstring"""





							_SCREAMING_SNAKE_CASE    =['[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'bla', 'blou']




							def  lowercase		(   self:     int    ):

												'''simple docstring'''

												a__          =  0




							def  lowercase		(   self:     int    ):

												'''simple docstring'''

												a__          =  AutoProcessor.from_pretrained('''facebook/wav2vec2-base-960h'''    )
												self.assertIsInstance(__A				,		__A    )




							def  lowercase		(   self:     Any    ):

												'''simple docstring'''

												with tempfile.TemporaryDirectory() as tmpdirname:
																	a__          =  WavaVecaConfig()
																	a__          =  AutoProcessor.from_pretrained('''facebook/wav2vec2-base-960h'''    )

																	# save in new folder
																	model_config.save_pretrained(__A    )
																	processor.save_pretrained(__A    )

																	a__          =  AutoProcessor.from_pretrained(__A    )

												self.assertIsInstance(__A				,		__A    )




							def  lowercase		(   self:     Any    ):

												'''simple docstring'''

												with tempfile.TemporaryDirectory() as tmpdirname:
																	# copy relevant files
																	copyfile(__A				,		os.path.join(__A				,		__A    )    )
																	copyfile(__A				,		os.path.join(__A				,		'''vocab.json'''    )    )

																	a__          =  AutoProcessor.from_pretrained(__A    )

												self.assertIsInstance(__A				,		__A    )




							def  lowercase		(   self:     Optional[int]    ):

												'''simple docstring'''

												with tempfile.TemporaryDirectory() as tmpdirname:
																	a__          =  WavaVecaFeatureExtractor()
																	a__          =  AutoTokenizer.from_pretrained('''facebook/wav2vec2-base-960h'''    )

																	a__          =  WavaVecaProcessor(__A				,		__A    )

																	# save in new folder
																	processor.save_pretrained(__A    )

																	# drop `processor_class` in tokenizer
																	with open(os.path.join(__A				,		__A    )				,		'''r'''    ) as f:
																						a__          =  json.load(__A    )
																						config_dict.pop('''processor_class'''    )

																	with open(os.path.join(__A				,		__A    )				,		'''w'''    ) as f:
																						f.write(json.dumps(__A    )    )

																	a__          =  AutoProcessor.from_pretrained(__A    )

												self.assertIsInstance(__A				,		__A    )




							def  lowercase		(   self:     Optional[Any]    ):

												'''simple docstring'''

												with tempfile.TemporaryDirectory() as tmpdirname:
																	a__          =  WavaVecaFeatureExtractor()
																	a__          =  AutoTokenizer.from_pretrained('''facebook/wav2vec2-base-960h'''    )

																	a__          =  WavaVecaProcessor(__A				,		__A    )

																	# save in new folder
																	processor.save_pretrained(__A    )

																	# drop `processor_class` in feature extractor
																	with open(os.path.join(__A				,		__A    )				,		'''r'''    ) as f:
																						a__          =  json.load(__A    )
																						config_dict.pop('''processor_class'''    )

																	with open(os.path.join(__A				,		__A    )				,		'''w'''    ) as f:
																						f.write(json.dumps(__A    )    )

																	a__          =  AutoProcessor.from_pretrained(__A    )

												self.assertIsInstance(__A				,		__A    )




							def  lowercase		(   self:     Dict    ):

												'''simple docstring'''

												with tempfile.TemporaryDirectory() as tmpdirname:
																	a__          =  WavaVecaConfig(processor_class='''Wav2Vec2Processor'''    )
																	model_config.save_pretrained(__A    )
																	# copy relevant files
																	copyfile(__A				,		os.path.join(__A				,		'''vocab.json'''    )    )
																	# create emtpy sample processor
																	with open(os.path.join(__A				,		__A    )				,		'''w'''    ) as f:
																						f.write('''{}'''    )

																	a__          =  AutoProcessor.from_pretrained(__A    )

												self.assertIsInstance(__A				,		__A    )




							def  lowercase		(   self:     Tuple    ):

												'''simple docstring'''

												with self.assertRaises(__A    ):
																	a__          =  AutoProcessor.from_pretrained('''hf-internal-testing/test_dynamic_processor'''    )
												# If remote code is disabled, we can't load this config.
												with self.assertRaises(__A    ):
																	a__          =  AutoProcessor.from_pretrained(
																	    '''hf-internal-testing/test_dynamic_processor'''				,		trust_remote_code=__A    )

												a__          =  AutoProcessor.from_pretrained('''hf-internal-testing/test_dynamic_processor'''				,		trust_remote_code=__A    )
												self.assertTrue(processor.special_attribute_present    )
												self.assertEqual(processor.__class__.__name__				,		'''NewProcessor'''    )

												a__          =  processor.feature_extractor
												self.assertTrue(feature_extractor.special_attribute_present    )
												self.assertEqual(feature_extractor.__class__.__name__				,		'''NewFeatureExtractor'''    )

												a__          =  processor.tokenizer
												self.assertTrue(tokenizer.special_attribute_present    )
												if is_tokenizers_available():
																	self.assertEqual(tokenizer.__class__.__name__				,		'''NewTokenizerFast'''    )

																	# Test we can also load the slow version
																	a__          =  AutoProcessor.from_pretrained(
																	    '''hf-internal-testing/test_dynamic_processor'''				,		trust_remote_code=__A				,		use_fast=__A    )
																	a__          =  new_processor.tokenizer
																	self.assertTrue(new_tokenizer.special_attribute_present    )
																	self.assertEqual(new_tokenizer.__class__.__name__				,		'''NewTokenizer'''    )
												else:
																	self.assertEqual(tokenizer.__class__.__name__				,		'''NewTokenizer'''    )




							def  lowercase		(   self:     str    ):

												'''simple docstring'''

												try:
																	AutoConfig.register('''custom'''				,		__A    )
																	AutoFeatureExtractor.register(__A				,		__A    )
																	AutoTokenizer.register(__A				,		slow_tokenizer_class=__A    )
																	AutoProcessor.register(__A				,		__A    )
																	# Trying to register something existing in the Transformers library will raise an error
																	with self.assertRaises(__A    ):
																						AutoProcessor.register(__A				,		__A    )

																	# Now that the config is registered, it can be used as any other config with the auto-API
																	a__          =  CustomFeatureExtractor.from_pretrained(__A    )

																	with tempfile.TemporaryDirectory() as tmp_dir:
																						a__          =  os.path.join(__A				,		'''vocab.txt'''    )
																						with open(__A				,		'''w'''				,		encoding='''utf-8'''    ) as vocab_writer:
																											vocab_writer.write(''''''.join([x + '''\n''' for x in self.vocab_tokens]    )    )
																						a__          =  CustomTokenizer(__A    )

																	a__          =  CustomProcessor(__A				,		__A    )

																	with tempfile.TemporaryDirectory() as tmp_dir:
																						processor.save_pretrained(__A    )
																						a__          =  AutoProcessor.from_pretrained(__A    )
																						self.assertIsInstance(__A				,		__A    )

												finally:
																	if "custom" in CONFIG_MAPPING._extra_content:
																						del CONFIG_MAPPING._extra_content["custom"]
																	if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content:
																						del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig]
																	if CustomConfig in TOKENIZER_MAPPING._extra_content:
																						del TOKENIZER_MAPPING._extra_content[CustomConfig]
																	if CustomConfig in PROCESSOR_MAPPING._extra_content:
																						del PROCESSOR_MAPPING._extra_content[CustomConfig]




							def  lowercase		(   self:     List[str]    ):

												'''simple docstring'''

												class        _SCREAMING_SNAKE_CASE						(  __snake_case							):





																			"""simple docstring"""





																			_SCREAMING_SNAKE_CASE    =False







												class        _SCREAMING_SNAKE_CASE						(  __snake_case							):





																			"""simple docstring"""





																			_SCREAMING_SNAKE_CASE    =False







												class        _SCREAMING_SNAKE_CASE						(  __snake_case							):





																			"""simple docstring"""





																			_SCREAMING_SNAKE_CASE    ='AutoFeatureExtractor'
																			_SCREAMING_SNAKE_CASE    ='AutoTokenizer'
																			_SCREAMING_SNAKE_CASE    =False

												try:
																	AutoConfig.register('''custom'''				,		__A    )
																	AutoFeatureExtractor.register(__A				,		__A    )
																	AutoTokenizer.register(__A				,		slow_tokenizer_class=__A    )
																	AutoProcessor.register(__A				,		__A    )
																	# If remote code is not set, the default is to use local classes.
																	a__          =  AutoProcessor.from_pretrained('''hf-internal-testing/test_dynamic_processor'''    )
																	self.assertEqual(processor.__class__.__name__				,		'''NewProcessor'''    )
																	self.assertFalse(processor.special_attribute_present    )
																	self.assertFalse(processor.feature_extractor.special_attribute_present    )
																	self.assertFalse(processor.tokenizer.special_attribute_present    )

																	# If remote code is disabled, we load the local ones.
																	a__          =  AutoProcessor.from_pretrained(
																	    '''hf-internal-testing/test_dynamic_processor'''				,		trust_remote_code=__A    )
																	self.assertEqual(processor.__class__.__name__				,		'''NewProcessor'''    )
																	self.assertFalse(processor.special_attribute_present    )
																	self.assertFalse(processor.feature_extractor.special_attribute_present    )
																	self.assertFalse(processor.tokenizer.special_attribute_present    )

																	# If remote is enabled, we load from the Hub.
																	a__          =  AutoProcessor.from_pretrained(
																	    '''hf-internal-testing/test_dynamic_processor'''				,		trust_remote_code=__A    )
																	self.assertEqual(processor.__class__.__name__				,		'''NewProcessor'''    )
																	self.assertTrue(processor.special_attribute_present    )
																	self.assertTrue(processor.feature_extractor.special_attribute_present    )
																	self.assertTrue(processor.tokenizer.special_attribute_present    )

												finally:
																	if "custom" in CONFIG_MAPPING._extra_content:
																						del CONFIG_MAPPING._extra_content["custom"]
																	if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content:
																						del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig]
																	if CustomConfig in TOKENIZER_MAPPING._extra_content:
																						del TOKENIZER_MAPPING._extra_content[CustomConfig]
																	if CustomConfig in PROCESSOR_MAPPING._extra_content:
																						del PROCESSOR_MAPPING._extra_content[CustomConfig]




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

												'''simple docstring'''

												a__          =  AutoProcessor.from_pretrained('''hf-internal-testing/tiny-random-bert'''    )
												self.assertEqual(processor.__class__.__name__				,		'''BertTokenizerFast'''    )





							def  lowercase		(   self:     str    ):

												'''simple docstring'''

												a__          =  AutoProcessor.from_pretrained('''hf-internal-testing/tiny-random-convnext'''    )
												self.assertEqual(processor.__class__.__name__				,		'''ConvNextImageProcessor'''    )







@is_staging_test
class        _SCREAMING_SNAKE_CASE						(  unittest.TestCase							):





							"""simple docstring"""





							_SCREAMING_SNAKE_CASE    =['[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'bla', 'blou']




							@classmethod
							def  lowercase		(   cls:     List[Any]    ):

												'''simple docstring'''

												a__          =  TOKEN
												HfFolder.save_token(__A    )




							@classmethod
							def  lowercase		(   cls:     Tuple    ):

												'''simple docstring'''

												try:
																	delete_repo(token=cls._token				,		repo_id='''test-processor'''    )
												except HTTPError:
																	pass

												try:
																	delete_repo(token=cls._token				,		repo_id='''valid_org/test-processor-org'''    )
												except HTTPError:
																	pass

												try:
																	delete_repo(token=cls._token				,		repo_id='''test-dynamic-processor'''    )
												except HTTPError:
																	pass




							def  lowercase		(   self:     Tuple    ):

												'''simple docstring'''

												a__          =  WavaVecaProcessor.from_pretrained(__A    )
												with tempfile.TemporaryDirectory() as tmp_dir:
																	processor.save_pretrained(
																	    os.path.join(__A				,		'''test-processor'''    )				,		push_to_hub=__A				,		use_auth_token=self._token    )

																	a__          =  WavaVecaProcessor.from_pretrained(F'{USER}/test-processor'    )
																	for k, v in processor.feature_extractor.__dict__.items():
																						self.assertEqual(__A				,		getattr(new_processor.feature_extractor				,		__A    )    )
																	self.assertDictEqual(new_processor.tokenizer.get_vocab()				,		processor.tokenizer.get_vocab()    )




							def  lowercase		(   self:     Dict    ):

												'''simple docstring'''

												a__          =  WavaVecaProcessor.from_pretrained(__A    )

												with tempfile.TemporaryDirectory() as tmp_dir:
																	processor.save_pretrained(
																	    os.path.join(__A				,		'''test-processor-org'''    )				,		push_to_hub=__A				,		use_auth_token=self._token				,		organization='''valid_org'''				,		)

																	a__          =  WavaVecaProcessor.from_pretrained('''valid_org/test-processor-org'''    )
																	for k, v in processor.feature_extractor.__dict__.items():
																						self.assertEqual(__A				,		getattr(new_processor.feature_extractor				,		__A    )    )
																	self.assertDictEqual(new_processor.tokenizer.get_vocab()				,		processor.tokenizer.get_vocab()    )





							def  lowercase		(   self:     Optional[int]    ):

												'''simple docstring'''

												CustomFeatureExtractor.register_for_auto_class()
												CustomTokenizer.register_for_auto_class()
												CustomProcessor.register_for_auto_class()

												a__          =  CustomFeatureExtractor.from_pretrained(__A    )

												with tempfile.TemporaryDirectory() as tmp_dir:
																	a__          =  os.path.join(__A				,		'''vocab.txt'''    )
																	with open(__A				,		'''w'''				,		encoding='''utf-8'''    ) as vocab_writer:
																						vocab_writer.write(''''''.join([x + '''\n''' for x in self.vocab_tokens]    )    )
																	a__          =  CustomTokenizer(__A    )

												a__          =  CustomProcessor(__A				,		__A    )

												with tempfile.TemporaryDirectory() as tmp_dir:
																	create_repo(F'{USER}/test-dynamic-processor'				,		token=self._token    )
																	a__          =  Repository(__A				,		clone_from=F'{USER}/test-dynamic-processor'				,		token=self._token    )
																	processor.save_pretrained(__A    )

																	# This has added the proper auto_map field to the feature extractor config
																	self.assertDictEqual(
																	    processor.feature_extractor.auto_map				,		{
																	        '''AutoFeatureExtractor''': '''custom_feature_extraction.CustomFeatureExtractor''',
																	        '''AutoProcessor''': '''custom_processing.CustomProcessor''',
																	    }				,		)

																	# This has added the proper auto_map field to the tokenizer config
																	with open(os.path.join(__A				,		'''tokenizer_config.json'''    )    ) as f:
																						a__          =  json.load(__A    )
																	self.assertDictEqual(
																	    tokenizer_config['''auto_map''']				,		{
																	        '''AutoTokenizer''': ['''custom_tokenization.CustomTokenizer''', None],
																	        '''AutoProcessor''': '''custom_processing.CustomProcessor''',
																	    }				,		)

																	# The code has been copied from fixtures
																	self.assertTrue(os.path.isfile(os.path.join(__A				,		'''custom_feature_extraction.py'''    )    )    )
																	self.assertTrue(os.path.isfile(os.path.join(__A				,		'''custom_tokenization.py'''    )    )    )
																	self.assertTrue(os.path.isfile(os.path.join(__A				,		'''custom_processing.py'''    )    )    )

																	repo.push_to_hub()

												a__          =  AutoProcessor.from_pretrained(F'{USER}/test-dynamic-processor'				,		trust_remote_code=__A    )
												# Can't make an isinstance check because the new_processor is from the CustomProcessor class of a dynamic module
												self.assertEqual(new_processor.__class__.__name__				,		'''CustomProcessor'''    )










"""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    )    )


