



"""simple docstring"""







import csv
import json
import logging
import os
import re
import subprocess
import tempfile
import unittest
import zipfile
from pathlib import Path
from typing import Optional
from unittest import mock

import torch

# We use TF to parse the logs
from accelerate import Accelerator
from accelerate.test_utils.testing import (
    MockingTestCase,
    TempDirTestCase,
    require_comet_ml,
    require_tensorboard,
    require_wandb,
    skip,
)
from accelerate.tracking import CometMLTracker, GeneralTracker
from accelerate.utils import ProjectConfiguration, is_comet_ml_available, is_tensorboard_available


if is_comet_ml_available():
							from comet_ml import OfflineExperiment

if is_tensorboard_available():
							import struct

							import tensorboard.compat.proto.event_pba as event_pba

A     =      logging.getLogger(__name__)






@require_tensorboard
class   UpperCAmelCase__		(   unittest.TestCase  ):



		def        A_		(			self	:     int					)      ->    Any:






									'''simple docstring'''

									A    =       'test_project_with_config'
									with tempfile.TemporaryDirectory() as dirpath:
																A    =       Accelerator(log_with='tensorboard'   ,				project_dir=snake_case					)
																A    =       {'num_iterations': 12, 'learning_rate': 1E-2, 'some_boolean': False, 'some_string': 'some_value'}
																accelerator.init_trackers(snake_case   ,				snake_case					)
																accelerator.end_training()
																for child in Path(f"""{dirpath}/{project_name}"""					).glob('*/**'					):
																							A    =       list(filter(lambda snake_case					: x.is_file()   ,				child.iterdir()					)					)[0]
																self.assertNotEqual(str(snake_case					)   ,				''					)



		def        A_		(			self	:     str					)      ->    int:






									'''simple docstring'''

									A    =       'test_project_with_log'
									with tempfile.TemporaryDirectory() as dirpath:
																A    =       Accelerator(log_with='tensorboard'   ,				project_dir=snake_case					)
																accelerator.init_trackers(snake_case					)
																A    =       {'total_loss': 0.1, 'iteration': 1, 'my_text': 'some_value'}
																accelerator.log(snake_case   ,				step=0					)
																accelerator.end_training()
																# Logged values are stored in the outermost-tfevents file and can be read in as a TFRecord
																# Names are randomly generated each time
																A    =       list(filter(lambda snake_case					: x.is_file()   ,				Path(f"""{dirpath}/{project_name}"""					).iterdir()					)					)[0]
																self.assertNotEqual(str(snake_case					)   ,				''					)



		def        A_		(			self	:     Dict					)      ->    List[Any]:






									'''simple docstring'''

									A    =       'test_project_with_log'
									with tempfile.TemporaryDirectory() as dirpath:
																A    =       Accelerator(log_with='tensorboard'   ,				project_dir=snake_case					)
																accelerator.init_trackers(snake_case					)
																A    =       {'tensor': torch.tensor(1					)}
																accelerator.log(snake_case   ,				step=0					)
																accelerator.end_training()
																# Logged values are stored in the outermost-tfevents file and can be read in as a TFRecord
																# Names are randomly generated each time
																A    =       list(filter(lambda snake_case					: x.is_file()   ,				Path(f"""{dirpath}/{project_name}"""					).iterdir()					)					)[0]
																# Reading implementation based on https://github.com/pytorch/pytorch/issues/45327#issuecomment-703757685
																with open(snake_case   ,				'rb'					) as f:
																							A    =       f.read()
																A    =       False
																while data:
																							A    =       struct.unpack('Q'   ,				data[:8]					)

																							A    =       data[12 : 12 + int(header[0]					)]  # 8+4
																							A    =       data[12 + int(header[0]					) + 4 :]
																							A    =       event_pba.Event()

																							event.ParseFromString(snake_case					)
																							if event.HasField('summary'					):
																														for value in event.summary.value:
																																					if value.simple_value == 1.0 and value.tag == "tensor":
																																												A    =       True
																self.assertTrue(snake_case   ,				'Converted tensor was not found in the log file!'					)



		def        A_		(			self	:     List[Any]					)      ->    List[str]:






									'''simple docstring'''

									with self.assertRaisesRegex(snake_case   ,				'Logging with `tensorboard` requires a `logging_dir`'					):
																A    =       Accelerator(log_with='tensorboard'					)
									with tempfile.TemporaryDirectory() as dirpath:
																A    =       Accelerator(log_with='tensorboard'   ,				project_dir=snake_case					)



		def        A_		(			self	:     List[Any]					)      ->    Optional[Any]:






									'''simple docstring'''

									A    =       ProjectConfiguration(total_limit=30					)
									with tempfile.TemporaryDirectory() as dirpath:
																A    =       Accelerator(log_with='tensorboard'   ,				project_dir=snake_case   ,				project_config=snake_case					)






@require_wandb
@mock.patch.dict(os.environ ,{"""WANDB_MODE""": """offline"""}  )
class   UpperCAmelCase__		(   UpperCamelCase ,UpperCamelCase  ):



		def        A_		(			self	:     List[str]					)      ->    Any:






									'''simple docstring'''

									super().setUp()
									# wandb let's us override where logs are stored to via the WANDB_DIR env var
									self.add_mocks(mock.patch.dict(os.environ   ,				{'WANDB_DIR': self.tmpdir}					)					)



		@staticmethod
		def        A_		(			snake_case	:     str   ,				snake_case	:     str   ,				snake_case	:     bool = True					)      ->    Optional[Any]:






									'''simple docstring'''

									A    =       rf"""{section} ([\S\s]*?)\n\n"""
									if record:
																A    =       rf"""Record: {pattern}"""
									A    =       re.findall(snake_case   ,				snake_case					)[0]
									# A config
									if section == "config" or section == "history":
																A    =       re.findall(r'"([a-zA-Z0-9_.,]+)'   ,				snake_case					)
																return {key: val for key, val in zip(cleaned_record[0::2]   ,				cleaned_record[1::2]					)}
									# Everything else
									else:
																return dict(re.findall(r'(\w+): "([^\s]+)"'   ,				snake_case					)					)



		@skip
		def        A_		(			self	:     Optional[Any]					)      ->    Dict:






									'''simple docstring'''

									A    =       'test_project_with_config'
									A    =       Accelerator(log_with='wandb'					)
									A    =       {'num_iterations': 12, 'learning_rate': 1E-2, 'some_boolean': False, 'some_string': 'some_value'}
									A    =       {'wandb': {'tags': ['my_tag']}}
									accelerator.init_trackers(snake_case   ,				snake_case   ,				snake_case					)
									A    =       {'total_loss': 0.1, 'iteration': 1, 'my_text': 'some_value'}
									accelerator.log(snake_case   ,				step=0					)
									accelerator.end_training()
									# The latest offline log is stored at wandb/latest-run/*.wandb
									for child in Path(f"""{self.tmpdir}/wandb/latest-run"""					).glob('*'					):
																if child.is_file() and child.suffix == ".wandb":
																							A    =       subprocess.check_output(
																							    ['wandb', 'sync', '--view', '--verbose', str(snake_case					)]   ,				env=os.environ.copy()					).decode('utf8'   ,				'ignore'					)
																							break

        # Check HPS through careful parsing and cleaning
									A    =       self.parse_log(snake_case   ,				'config'					)
									self.assertEqual(logged_items['num_iterations']   ,				'12'					)
									self.assertEqual(logged_items['learning_rate']   ,				'0.01'					)
									self.assertEqual(logged_items['some_boolean']   ,				'false'					)
									self.assertEqual(logged_items['some_string']   ,				'some_value'					)
									self.assertEqual(logged_items['some_string']   ,				'some_value'					)

									# Run tags
									A    =       self.parse_log(snake_case   ,				'run'   ,				snake_case					)
									self.assertEqual(logged_items['tags']   ,				'my_tag'					)

									# Actual logging
									A    =       self.parse_log(snake_case   ,				'history'					)
									self.assertEqual(logged_items['total_loss']   ,				'0.1'					)
									self.assertEqual(logged_items['iteration']   ,				'1'					)
									self.assertEqual(logged_items['my_text']   ,				'some_value'					)
									self.assertEqual(logged_items['_step']   ,				'0'					)



def 	lowerCAmelCase__      (  self					,   lowerCamelCase__					,   lowerCamelCase__      )			->				List[str]:
							A    =       run_name
							A    =       OfflineExperiment(project_name=lowerCamelCase__					,   offline_directory=lowerCamelCase__      )
							logger.info(f"""Initialized offline CometML project {self.run_name}"""      )
							logger.info('Make sure to log any initial configurations with `self.store_init_configuration` before training!'      )






@require_comet_ml
@mock.patch.object(UpperCamelCase ,"""__init__""" ,UpperCamelCase  )
class   UpperCAmelCase__		(   unittest.TestCase  ):



		@staticmethod
		def        A_		(			snake_case	:     List[str]   ,				snake_case	:     str   ,				snake_case	:     bool = False					)      ->    str:






									'''simple docstring'''

									for log in log_list:
																A    =       json.loads(snake_case					)['payload']
																if is_param and "param" in j.keys():
																							if j["param"]["paramName"] == key:
																														return j["param"]["paramValue"]
																if "log_other" in j.keys():
																							if j["log_other"]["key"] == key:
																														return j["log_other"]["val"]
																if "metric" in j.keys():
																							if j["metric"]["metricName"] == key:
																														return j["metric"]["metricValue"]



		def        A_		(			self	:     Optional[Any]					)      ->    Optional[Any]:






									'''simple docstring'''

									with tempfile.TemporaryDirectory() as d:
																A    =       CometMLTracker('test_project_with_config'   ,				snake_case					)
																A    =       Accelerator(log_with=snake_case					)
																A    =       {'num_iterations': 12, 'learning_rate': 1E-2, 'some_boolean': False, 'some_string': 'some_value'}
																accelerator.init_trackers(snake_case   ,				snake_case					)
																accelerator.end_training()
																A    =       os.listdir(snake_case					)[0]  # Comet is nice, it's just a zip file here
																# We parse the raw logs
																A    =       os.path.join(snake_case   ,				snake_case					)
																A    =       zipfile.ZipFile(snake_case   ,				'r'					)
																A    =       archive.open('messages.json'					).read().decode('utf-8'					)
									A    =       log.split('\n'					)[:-1]
									self.assertEqual(self.get_value_from_key(snake_case   ,				'num_iterations'   ,				snake_case					)   ,				12					)
									self.assertEqual(self.get_value_from_key(snake_case   ,				'learning_rate'   ,				snake_case					)   ,				0.01					)
									self.assertEqual(self.get_value_from_key(snake_case   ,				'some_boolean'   ,				snake_case					)   ,				snake_case					)
									self.assertEqual(self.get_value_from_key(snake_case   ,				'some_string'   ,				snake_case					)   ,				'some_value'					)



		def        A_		(			self	:     Dict					)      ->    str:






									'''simple docstring'''

									with tempfile.TemporaryDirectory() as d:
																A    =       CometMLTracker('test_project_with_config'   ,				snake_case					)
																A    =       Accelerator(log_with=snake_case					)
																accelerator.init_trackers(snake_case					)
																A    =       {'total_loss': 0.1, 'iteration': 1, 'my_text': 'some_value'}
																accelerator.log(snake_case   ,				step=0					)
																accelerator.end_training()
																A    =       os.listdir(snake_case					)[0]  # Comet is nice, it's just a zip file here
																# We parse the raw logs
																A    =       os.path.join(snake_case   ,				snake_case					)
																A    =       zipfile.ZipFile(snake_case   ,				'r'					)
																A    =       archive.open('messages.json'					).read().decode('utf-8'					)
									A    =       log.split('\n'					)[:-1]
									self.assertEqual(self.get_value_from_key(snake_case   ,				'curr_step'   ,				snake_case					)   ,				0					)
									self.assertEqual(self.get_value_from_key(snake_case   ,				'total_loss'					)   ,				0.1					)
									self.assertEqual(self.get_value_from_key(snake_case   ,				'iteration'					)   ,				1					)
									self.assertEqual(self.get_value_from_key(snake_case   ,				'my_text'					)   ,				'some_value'					)






class   UpperCAmelCase__		(   UpperCamelCase  ):
		lowerCAmelCase_							:						int							=  [
		    """total_loss""",
		    """iteration""",
		    """my_text""",
		    """learning_rate""",
		    """num_iterations""",
		    """some_boolean""",
		    """some_string""",
		]

		lowerCAmelCase_							:						int							=  """my_custom_tracker"""
		lowerCAmelCase_							:						str							=  False



		def __init__(			self	:     Optional[Any]   ,				snake_case	:     str					)      ->    Any:






									'''simple docstring'''

									A    =       open(f"""{dir}/log.csv"""   ,				'w+'					)
									A    =       csv.DictWriter(self.f   ,				fieldnames=self._col_names					)
									self.writer.writeheader()



		@property
		def        A_		(			self	:     Dict					)      ->    Union[str, Any]:






									'''simple docstring'''

									return self.writer



		def        A_		(			self	:     Union[str, Any]   ,				snake_case	:     dict					)      ->    Tuple:






									'''simple docstring'''

									logger.info('Call init'					)
									self.writer.writerow(snake_case					)



		def        A_		(			self	:     List[Any]   ,				snake_case	:     dict   ,				snake_case	:     Optional[int]					)      ->    Optional[int]:






									'''simple docstring'''

									logger.info('Call log'					)
									self.writer.writerow(snake_case					)



		def        A_		(			self	:     Optional[int]					)      ->    List[Any]:






									'''simple docstring'''

									self.f.close()






class   UpperCAmelCase__		(   unittest.TestCase  ):



		def        A_		(			self	:     Tuple					)      ->    Union[str, Any]:






									'''simple docstring'''

									with tempfile.TemporaryDirectory() as d:
																A    =       MyCustomTracker(snake_case					)
																A    =       Accelerator(log_with=snake_case					)
																A    =       {'num_iterations': 12, 'learning_rate': 1E-2, 'some_boolean': False, 'some_string': 'some_value'}
																accelerator.init_trackers('Some name'   ,				snake_case					)
																accelerator.end_training()
																with open(f"""{d}/log.csv"""   ,				'r'					) as f:
																							A    =       csv.DictReader(snake_case					)
																							A    =       next(snake_case					)
																							A    =       {
																							    'total_loss': '',
																							    'iteration': '',
																							    'my_text': '',
																							    'learning_rate': '0.01',
																							    'num_iterations': '12',
																							    'some_boolean': 'False',
																							    'some_string': 'some_value',
																							}
																							self.assertDictEqual(snake_case   ,				snake_case					)



		def        A_		(			self	:     Optional[Any]					)      ->    List[str]:






									'''simple docstring'''

									with tempfile.TemporaryDirectory() as d:
																A    =       MyCustomTracker(snake_case					)
																A    =       Accelerator(log_with=snake_case					)
																accelerator.init_trackers('Some name'					)
																A    =       {'total_loss': 0.1, 'iteration': 1, 'my_text': 'some_value'}
																accelerator.log(snake_case   ,				step=0					)
																accelerator.end_training()
																with open(f"""{d}/log.csv"""   ,				'r'					) as f:
																							A    =       csv.DictReader(snake_case					)
																							A    =       next(snake_case					)
																							A    =       {
																							    'total_loss': '0.1',
																							    'iteration': '1',
																							    'my_text': 'some_value',
																							    'learning_rate': '',
																							    'num_iterations': '',
																							    'some_boolean': '',
																							    'some_string': '',
																							}
																							self.assertDictEqual(snake_case   ,				snake_case					)








"""simple docstring"""







from __future__ import annotations

import unittest
import warnings

from transformers import AutoTokenizer, MarianConfig, MarianTokenizer, TranslationPipeline, is_tf_available
from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow
from transformers.utils import cached_property

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


if is_tf_available():
							import tensorflow as tf

							from transformers import TFAutoModelForSeqaSeqLM, TFMarianModel, TFMarianMTModel






@require_tf
class   UpperCAmelCase__		:
		lowerCAmelCase_							:						Optional[Any]							=  MarianConfig
		lowerCAmelCase_							:						Dict							=  {}
		lowerCAmelCase_							:						List[str]							=  """gelu"""



		def __init__(			self	:     Optional[Any]   ,				snake_case	:     Any   ,				snake_case	:     int=13   ,				snake_case	:     Dict=7   ,				snake_case	:     Dict=True   ,				snake_case	:     List[str]=False   ,				snake_case	:     int=99   ,				snake_case	:     Optional[Any]=32   ,				snake_case	:     Optional[Any]=2   ,				snake_case	:     int=4   ,				snake_case	:     Optional[int]=37   ,				snake_case	:     Optional[int]=0.1   ,				snake_case	:     str=0.1   ,				snake_case	:     Any=20   ,				snake_case	:     Dict=2   ,				snake_case	:     List[Any]=1   ,				snake_case	:     str=0   ,				)      ->    str:






									'''simple docstring'''

									A    =       parent
									A    =       batch_size
									A    =       seq_length
									A    =       is_training
									A    =       use_labels
									A    =       vocab_size
									A    =       hidden_size
									A    =       num_hidden_layers
									A    =       num_attention_heads
									A    =       intermediate_size

									A    =       hidden_dropout_prob
									A    =       attention_probs_dropout_prob
									A    =       max_position_embeddings
									A    =       eos_token_id
									A    =       pad_token_id
									A    =       bos_token_id



		def        A_		(			self	:     List[Any]					)      ->    Tuple:






									'''simple docstring'''

									A    =       ids_tensor([self.batch_size, self.seq_length - 1]   ,				self.vocab_size					)
									A    =       tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size					)   ,				1					)
									A    =       tf.concat([input_ids, eos_tensor]   ,				axis=1					)

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

									A    =       self.config_cls(
									    vocab_size=self.vocab_size   ,				d_model=self.hidden_size   ,				encoder_layers=self.num_hidden_layers   ,				decoder_layers=self.num_hidden_layers   ,				encoder_attention_heads=self.num_attention_heads   ,				decoder_attention_heads=self.num_attention_heads   ,				encoder_ffn_dim=self.intermediate_size   ,				decoder_ffn_dim=self.intermediate_size   ,				dropout=self.hidden_dropout_prob   ,				attention_dropout=self.attention_probs_dropout_prob   ,				max_position_embeddings=self.max_position_embeddings   ,				eos_token_ids=[2]   ,				bos_token_id=self.bos_token_id   ,				pad_token_id=self.pad_token_id   ,				decoder_start_token_id=self.pad_token_id   ,				**self.config_updates   ,				)
									A    =       prepare_marian_inputs_dict(snake_case   ,				snake_case   ,				snake_case					)
									return config, inputs_dict



		def        A_		(			self	:     Tuple   ,				snake_case	:     Optional[int]   ,				snake_case	:     Optional[int]					)      ->    Optional[int]:






									'''simple docstring'''

									A    =       TFMarianModel(config=snake_case					).get_decoder()
									A    =       inputs_dict['input_ids']

									A    =       input_ids[:1, :]
									A    =       inputs_dict['attention_mask'][:1, :]
									A    =       inputs_dict['head_mask']
									A    =       1

									# first forward pass
									A    =       model(snake_case   ,				attention_mask=snake_case   ,				head_mask=snake_case   ,				use_cache=snake_case					)

									A   ,	A    =       outputs.to_tuple()

									# create hypothetical next token and extent to next_input_ids
									A    =       ids_tensor((self.batch_size, 3)   ,				config.vocab_size					)
									A    =       tf.cast(ids_tensor((self.batch_size, 3)   ,				2					)   ,				tf.inta					)

									# append to next input_ids and
									A    =       tf.concat([input_ids, next_tokens]   ,				axis=-1					)
									A    =       tf.concat([attention_mask, next_attn_mask]   ,				axis=-1					)

									A    =       model(snake_case   ,				attention_mask=snake_case					)[0]
									A    =       model(snake_case   ,				attention_mask=snake_case   ,				past_key_values=snake_case					)[0]

									self.parent.assertEqual(next_tokens.shape[1]   ,				output_from_past.shape[1]					)

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

									# test that outputs are equal for slice
									tf.debugging.assert_near(snake_case   ,				snake_case   ,				rtol=1E-3					)



def 	lowerCAmelCase__      (  lowerCamelCase__					,   lowerCamelCase__					,   lowerCamelCase__					,   lowerCamelCase__=None					,   lowerCamelCase__=None					,   lowerCamelCase__=None					,   lowerCamelCase__=None					,   lowerCamelCase__=None					,   )			->				Tuple:
							if attention_mask is None:
														A    =       tf.cast(tf.math.not_equal(lowerCamelCase__					,   config.pad_token_id      )					,   tf.inta      )
							if decoder_attention_mask is None:
														A    =       tf.concat(
														    [
														        tf.ones(decoder_input_ids[:, :1].shape					,   dtype=tf.inta      ),
														        tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:]					,   config.pad_token_id      )					,   tf.inta      ),
														    ]					,   axis=-1					,   )
							if head_mask is None:
														A    =       tf.ones((config.encoder_layers, config.encoder_attention_heads)      )
							if decoder_head_mask is None:
														A    =       tf.ones((config.decoder_layers, config.decoder_attention_heads)      )
							if cross_attn_head_mask is None:
														A    =       tf.ones((config.decoder_layers, config.decoder_attention_heads)      )
							return {
							    "input_ids": input_ids,
							    "decoder_input_ids": decoder_input_ids,
							    "attention_mask": attention_mask,
							    "decoder_attention_mask": decoder_attention_mask,
							    "head_mask": head_mask,
							    "decoder_head_mask": decoder_head_mask,
							    "cross_attn_head_mask": cross_attn_head_mask,
							}






@require_tf
class   UpperCAmelCase__		(   UpperCamelCase ,UpperCamelCase ,unittest.TestCase  ):
		lowerCAmelCase_							:						List[str]							=  (TFMarianMTModel, TFMarianModel) if is_tf_available() else ()
		lowerCAmelCase_							:						List[Any]							=  (TFMarianMTModel,) if is_tf_available() else ()
		lowerCAmelCase_							:						str							=  (
		    {
		        """conversational""": TFMarianMTModel,
		        """feature-extraction""": TFMarianModel,
		        """summarization""": TFMarianMTModel,
		        """text2text-generation""": TFMarianMTModel,
		        """translation""": TFMarianMTModel,
		    }
		    if is_tf_available()
		    else {}
		)
		lowerCAmelCase_							:						Dict							=  True
		lowerCAmelCase_							:						Any							=  False
		lowerCAmelCase_							:						int							=  False



		def        A_		(			self	:     str					)      ->    Optional[int]:






									'''simple docstring'''

									A    =       TFMarianModelTester(self					)
									A    =       ConfigTester(self   ,				config_class=snake_case					)



		def        A_		(			self	:     int					)      ->    Optional[int]:






									'''simple docstring'''

									self.config_tester.run_common_tests()



		def        A_		(			self	:     Dict					)      ->    int:






									'''simple docstring'''

									A    =       self.model_tester.prepare_config_and_inputs_for_common()
									self.model_tester.check_decoder_model_past_large_inputs(*snake_case					)






@require_tf
class   UpperCAmelCase__		(   unittest.TestCase  ):
		lowerCAmelCase_							:						str							=  10_00  # show more chars for failing integration tests



		@classmethod
		def        A_		(			cls	:     str					)      ->    None:






									'''simple docstring'''

									A    =       f"""Helsinki-NLP/opus-mt-{cls.src}-{cls.tgt}"""
									return cls



		@cached_property
		def        A_		(			self	:     Tuple					)      ->    MarianTokenizer:






									'''simple docstring'''

									return AutoTokenizer.from_pretrained(self.model_name					)



		@property
		def        A_		(			self	:     str					)      ->    int:






									'''simple docstring'''

									return self.tokenizer.eos_token_id



		@cached_property
		def        A_		(			self	:     List[Any]					)      ->    Optional[int]:






									'''simple docstring'''

									warnings.simplefilter('error'					)
									A    =       TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name					)
									assert isinstance(snake_case   ,				snake_case					)
									A    =       model.config
									self.assertListEqual(c.bad_words_ids   ,				[[c.pad_token_id]]					)
									self.assertEqual(c.max_length   ,				512					)
									self.assertEqual(c.decoder_start_token_id   ,				c.pad_token_id					)
									return model



		def        A_		(			self	:     List[Any]   ,				**snake_case	:     Optional[int]					)      ->    Any:






									'''simple docstring'''

									A    =       self.translate_src_text(**snake_case					)
									self.assertListEqual(self.expected_text   ,				snake_case					)



		def        A_		(			self	:     Optional[Any]   ,				**snake_case	:     int					)      ->    str:






									'''simple docstring'''

									A    =       self.tokenizer(self.src_text   ,				**snake_case   ,				padding=snake_case   ,				return_tensors='tf'					)
									A    =       self.model.generate(
									    model_inputs.input_ids   ,				attention_mask=model_inputs.attention_mask   ,				num_beams=2   ,				max_length=128					)
									A    =       self.tokenizer.batch_decode(generated_ids.numpy()   ,				skip_special_tokens=snake_case					)
									return generated_words






@require_sentencepiece
@require_tokenizers
@require_tf
class   UpperCAmelCase__		(   UpperCamelCase  ):
		lowerCAmelCase_							:						Dict							=  """mt"""
		lowerCAmelCase_							:						int							=  """en"""
		lowerCAmelCase_							:						Optional[int]							=  ["""Billi messu b'mod ġentili, Ġesù fejjaq raġel li kien milqut bil - marda kerha tal - ġdiem."""]
		lowerCAmelCase_							:						List[Any]							=  ["""Touching gently, Jesus healed a man who was affected by the sad disease of leprosy."""]



		@unittest.skip('Skipping until #12647 is resolved.'					)
		@slow
		def        A_		(			self	:     List[str]					)      ->    List[Any]:






									'''simple docstring'''

									self._assert_generated_batch_equal_expected()






@require_sentencepiece
@require_tokenizers
@require_tf
class   UpperCAmelCase__		(   UpperCamelCase  ):
		lowerCAmelCase_							:						List[str]							=  """en"""
		lowerCAmelCase_							:						Dict							=  """zh"""
		lowerCAmelCase_							:						Any							=  ["""My name is Wolfgang and I live in Berlin"""]
		lowerCAmelCase_							:						int							=  ["""我叫沃尔夫冈 我住在柏林"""]



		@unittest.skip('Skipping until #12647 is resolved.'					)
		@slow
		def        A_		(			self	:     Tuple					)      ->    List[str]:






									'''simple docstring'''

									self._assert_generated_batch_equal_expected()






@require_sentencepiece
@require_tokenizers
@require_tf
class   UpperCAmelCase__		(   UpperCamelCase  ):
		lowerCAmelCase_							:						str							=  """en"""
		lowerCAmelCase_							:						Dict							=  """ROMANCE"""
		lowerCAmelCase_							:						Optional[int]							=  [
		    """>>fr<< Don't spend so much time watching TV.""",
		    """>>pt<< Your message has been sent.""",
		    """>>es<< He's two years older than me.""",
		]
		lowerCAmelCase_							:						Union[str, Any]							=  [
		    """Ne passez pas autant de temps à regarder la télé.""",
		    """A sua mensagem foi enviada.""",
		    """Es dos años más viejo que yo.""",
		]



		@unittest.skip('Skipping until #12647 is resolved.'					)
		@slow
		def        A_		(			self	:     Optional[int]					)      ->    List[Any]:






									'''simple docstring'''

									self._assert_generated_batch_equal_expected()



		@unittest.skip('Skipping until #12647 is resolved.'					)
		@slow
		def        A_		(			self	:     Tuple					)      ->    List[str]:






									'''simple docstring'''

									A    =       TranslationPipeline(self.model   ,				self.tokenizer   ,				framework='tf'					)
									A    =       pipeline(self.src_text					)
									self.assertEqual(self.expected_text   ,				[x['translation_text'] for x in output]					)



