'''simple docstring'''




# Copyright 2021 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import json
import os
from dataclasses import dataclass
from enum import Enum
from typing import List, Optional, Union

import yaml

from ...utils import ComputeEnvironment, DistributedType, SageMakerDistributedType
from ...utils.constants import SAGEMAKER_PYTHON_VERSION, SAGEMAKER_PYTORCH_VERSION, SAGEMAKER_TRANSFORMERS_VERSION


_lowercase		:					Optional[Any]													=		os.path.expanduser(
    os.getenv("HF_HOME", os.path.join(os.getenv("XDG_CACHE_HOME", "~/.cache"), "huggingface"))
)
_lowercase		:					Optional[int]													=		os.path.join(hf_cache_home, "accelerate")
_lowercase		:					int													=		os.path.join(cache_dir, "default_config.yaml")
_lowercase		:					Optional[int]													=		os.path.join(cache_dir, "default_config.yaml")

# For backward compatibility: the default config is the json one if it's the only existing file.
if os.path.isfile(default_yaml_config_file) or not os.path.isfile(default_json_config_file):
						_lowercase		:					Any													=		default_yaml_config_file
else:
						_lowercase		:					List[Any]													=		default_json_config_file




def 				lowerCamelCase      ( UpperCAmelCase__			:   Optional[int]					)     -> Dict:
							if config_file is not None:
														if not os.path.isfile(UpperCAmelCase__					):
																					raise FileNotFoundError(
																					    F'''The passed configuration file `{config_file}` does not exist. '''
																					    """Please pass an existing file to `accelerate launch`, or use the the default one """
																					    """created through `accelerate config` and run `accelerate launch` """
																					    """without the `--config_file` argument."""					)
							else:
														lowercase_   :     int									=			default_config_file
							with open(UpperCAmelCase__ , """r""" , encoding="""utf-8"""					) as f:
														if config_file.endswith(""".json"""					):
																					if (
																					    json.load(UpperCAmelCase__					).get("""compute_environment""" , ComputeEnvironment.LOCAL_MACHINE					)
																					    == ComputeEnvironment.LOCAL_MACHINE
																					):
																												lowercase_   :     Union[str, Any]									=			ClusterConfig
																					else:
																												lowercase_   :     List[str]									=			SageMakerConfig
																					return config_class.from_json_file(json_file=UpperCAmelCase__					)
														else:
																					if (
																					    yaml.safe_load(UpperCAmelCase__					).get("""compute_environment""" , ComputeEnvironment.LOCAL_MACHINE					)
																					    == ComputeEnvironment.LOCAL_MACHINE
																					):
																												lowercase_   :     List[str]									=			ClusterConfig
																					else:
																												lowercase_   :     Union[str, Any]									=			SageMakerConfig
																					return config_class.from_yaml_file(yaml_file=UpperCAmelCase__					)





@dataclass
class        __magic_name__		:
			UpperCamelCase__							=			42
			UpperCamelCase__							=			42
			UpperCamelCase__							=			42
			UpperCamelCase__							=			42







			def       SCREAMING_SNAKE_CASE_	(      self							:    List[Any]       ):
										lowercase_   :     str									=			self.__dict__
										# For serialization, it's best to convert Enums to strings (or their underlying value type).
										for key, value in result.items():
																	if isinstance(lowercase_							,     lowercase_       ):
																								lowercase_   :     Optional[Any]									=			value.value
																	if isinstance(lowercase_							,     lowercase_       ) and not bool(lowercase_       ):
																								lowercase_   :     Dict									=			None
										lowercase_   :     str									=			{k: v for k, v in result.items() if v is not None}
										return result







			@classmethod
			def       SCREAMING_SNAKE_CASE_	(      cls							:    Any							,     lowercase_							:    Optional[int]=None       ):
										lowercase_   :     Optional[int]									=			default_json_config_file if json_file is None else json_file
										with open(lowercase_							,     """r"""							,     encoding="""utf-8"""       ) as f:
																	lowercase_   :     Union[str, Any]									=			json.load(lowercase_       )
										if "compute_environment" not in config_dict:
																	lowercase_   :     Tuple									=			ComputeEnvironment.LOCAL_MACHINE
										if "mixed_precision" not in config_dict:
																	lowercase_   :     List[str]									=			"""fp16""" if ("""fp16""" in config_dict and config_dict["""fp16"""]) else None
										if "fp16" in config_dict:  # Convert the config to the new format.
																	del config_dict["fp16"]
										if "dynamo_backend" in config_dict:  # Convert the config to the new format.
																	lowercase_   :     Union[str, Any]									=			config_dict.pop("""dynamo_backend"""       )
																	lowercase_   :     Optional[int]									=			{} if dynamo_backend == """NO""" else {"""dynamo_backend""": dynamo_backend}
										if "use_cpu" not in config_dict:
																	lowercase_   :     int									=			False
										return cls(**lowercase_       )







			def       SCREAMING_SNAKE_CASE_	(      self							:    int							,     lowercase_							:    Optional[Any]       ):
										with open(lowercase_							,     """w"""							,     encoding="""utf-8"""       ) as f:
																	lowercase_   :     Tuple									=			json.dumps(self.to_dict()							,     indent=2							,     sort_keys=lowercase_       ) + """\n"""
																	f.write(lowercase_       )







			@classmethod
			def       SCREAMING_SNAKE_CASE_	(      cls							:    int							,     lowercase_							:    str=None       ):
										lowercase_   :     Dict									=			default_yaml_config_file if yaml_file is None else yaml_file
										with open(lowercase_							,     """r"""							,     encoding="""utf-8"""       ) as f:
																	lowercase_   :     List[str]									=			yaml.safe_load(lowercase_       )
										if "compute_environment" not in config_dict:
																	lowercase_   :     Dict									=			ComputeEnvironment.LOCAL_MACHINE

										if "mixed_precision" not in config_dict:
																	lowercase_   :     str									=			"""fp16""" if ("""fp16""" in config_dict and config_dict["""fp16"""]) else None
										if isinstance(config_dict["""mixed_precision"""]							,     lowercase_       ) and not config_dict["mixed_precision"]:
																	lowercase_   :     str									=			"""no"""
										if "fp16" in config_dict:  # Convert the config to the new format.
																	del config_dict["fp16"]
										if "dynamo_backend" in config_dict:  # Convert the config to the new format.
																	lowercase_   :     str									=			config_dict.pop("""dynamo_backend"""       )
																	lowercase_   :     Optional[Any]									=			{} if dynamo_backend == """NO""" else {"""dynamo_backend""": dynamo_backend}
										if "use_cpu" not in config_dict:
																	lowercase_   :     int									=			False
										return cls(**lowercase_       )







			def       SCREAMING_SNAKE_CASE_	(      self							:    Any							,     lowercase_							:    List[str]       ):
										with open(lowercase_							,     """w"""							,     encoding="""utf-8"""       ) as f:
																	yaml.safe_dump(self.to_dict()							,     lowercase_       )







			def       SCREAMING_SNAKE_CASE_	(      self							:    Dict       ):
										if isinstance(self.compute_environment							,     lowercase_       ):
																	lowercase_   :     Optional[int]									=			ComputeEnvironment(self.compute_environment       )
										if isinstance(self.distributed_type							,     lowercase_       ):
																	if self.compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER:
																								lowercase_   :     str									=			SageMakerDistributedType(self.distributed_type       )
																	else:
																								lowercase_   :     Optional[int]									=			DistributedType(self.distributed_type       )
										if self.dynamo_config is None:
																	lowercase_   :     List[Any]									=			{}





@dataclass
class        __magic_name__		(       _UpperCAmelCase):
			UpperCamelCase__							=			42
			UpperCamelCase__							=			0
			UpperCamelCase__							=			1
			UpperCamelCase__							=			None
			UpperCamelCase__							=			None
			UpperCamelCase__							=			None
			UpperCamelCase__							=			"static"
			UpperCamelCase__							=			False
			UpperCamelCase__							=			"main"

			# args for deepspeed_plugin
			UpperCamelCase__							=			None
			# args for fsdp
			UpperCamelCase__							=			None
			# args for megatron_lm
			UpperCamelCase__							=			None
			# args for ipex
			UpperCamelCase__							=			None
			# args for TPU
			UpperCamelCase__							=			False

			# args for TPU pods
			UpperCamelCase__							=			None
			UpperCamelCase__							=			None
			UpperCamelCase__							=			False
			UpperCamelCase__							=			False
			UpperCamelCase__							=			None
			UpperCamelCase__							=			None
			UpperCamelCase__							=			None
			UpperCamelCase__							=			None

			# args for dynamo
			UpperCamelCase__							=			None







			def       SCREAMING_SNAKE_CASE_	(      self							:    Union[str, Any]       ):
										if self.deepspeed_config is None:
																	lowercase_   :     Any									=			{}
										if self.fsdp_config is None:
																	lowercase_   :     Optional[int]									=			{}
										if self.megatron_lm_config is None:
																	lowercase_   :     List[str]									=			{}
										if self.ipex_config is None:
																	lowercase_   :     Tuple									=			{}
										return super().__post_init__()





@dataclass
class        __magic_name__		(       _UpperCAmelCase):
			UpperCamelCase__							=			42
			UpperCamelCase__							=			42
			UpperCamelCase__							=			None
			UpperCamelCase__							=			None
			UpperCamelCase__							=			"us-east-1"
			UpperCamelCase__							=			1
			UpperCamelCase__							=			"all"
			UpperCamelCase__							=			f"accelerate-sagemaker-{num_machines}"
			UpperCamelCase__							=			SAGEMAKER_PYTORCH_VERSION
			UpperCamelCase__							=			SAGEMAKER_TRANSFORMERS_VERSION
			UpperCamelCase__							=			SAGEMAKER_PYTHON_VERSION
			UpperCamelCase__							=			None
			UpperCamelCase__							=			None
			UpperCamelCase__							=			None
			UpperCamelCase__							=			None






'''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        __magic_name__		:
			UpperCamelCase__							=			MarianConfig
			UpperCamelCase__							=			{}
			UpperCamelCase__							=			'''gelu'''







			def __init__(      self							:    Optional[Any]							,     lowercase_							:    Tuple							,     lowercase_							:    Optional[int]=13							,     lowercase_							:    Dict=7							,     lowercase_							:    str=True							,     lowercase_							:    str=False							,     lowercase_							:    Tuple=99							,     lowercase_							:    int=32							,     lowercase_							:    int=2							,     lowercase_							:    Optional[int]=4							,     lowercase_							:    Optional[int]=37							,     lowercase_							:    Any=0.1							,     lowercase_							:    List[Any]=0.1							,     lowercase_							:    Union[str, Any]=20							,     lowercase_							:    List[str]=2							,     lowercase_							:    int=1							,     lowercase_							:    Union[str, Any]=0							,     ):
										lowercase_   :     str									=			parent
										lowercase_   :     Any									=			batch_size
										lowercase_   :     List[Any]									=			seq_length
										lowercase_   :     str									=			is_training
										lowercase_   :     str									=			use_labels
										lowercase_   :     str									=			vocab_size
										lowercase_   :     Optional[Any]									=			hidden_size
										lowercase_   :     Optional[Any]									=			num_hidden_layers
										lowercase_   :     List[Any]									=			num_attention_heads
										lowercase_   :     List[Any]									=			intermediate_size

										lowercase_   :     List[str]									=			hidden_dropout_prob
										lowercase_   :     Union[str, Any]									=			attention_probs_dropout_prob
										lowercase_   :     str									=			max_position_embeddings
										lowercase_   :     Optional[int]									=			eos_token_id
										lowercase_   :     Dict									=			pad_token_id
										lowercase_   :     Any									=			bos_token_id







			def       SCREAMING_SNAKE_CASE_	(      self							:    Optional[int]       ):
										lowercase_   :     Optional[int]									=			ids_tensor([self.batch_size, self.seq_length - 1]							,     self.vocab_size       )
										lowercase_   :     Tuple									=			tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size       )							,     1       )
										lowercase_   :     Dict									=			tf.concat([input_ids, eos_tensor]							,     axis=1       )

										lowercase_   :     List[Any]									=			ids_tensor([self.batch_size, self.seq_length]							,     self.vocab_size       )

										lowercase_   :     List[Any]									=			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							,     )
										lowercase_   :     List[Any]									=			prepare_marian_inputs_dict(lowercase_							,     lowercase_							,     lowercase_       )
										return config, inputs_dict







			def       SCREAMING_SNAKE_CASE_	(      self							:    Optional[Any]							,     lowercase_							:    List[Any]							,     lowercase_							:    Optional[int]       ):
										lowercase_   :     Any									=			TFMarianModel(config=lowercase_       ).get_decoder()
										lowercase_   :     Optional[Any]									=			inputs_dict["""input_ids"""]

										lowercase_   :     Tuple									=			input_ids[:1, :]
										lowercase_   :     Optional[Any]									=			inputs_dict["""attention_mask"""][:1, :]
										lowercase_   :     List[str]									=			inputs_dict["""head_mask"""]
										lowercase_   :     Dict									=			1

										# first forward pass
										lowercase_   :     List[Any]									=			model(lowercase_							,     attention_mask=lowercase_							,     head_mask=lowercase_							,     use_cache=lowercase_       )

										lowercase_		,		lowercase_   :     Any									=			outputs.to_tuple()

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

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

										lowercase_   :     Optional[int]									=			model(lowercase_							,     attention_mask=lowercase_       )[0]
										lowercase_   :     Union[str, Any]									=			model(lowercase_							,     attention_mask=lowercase_							,     past_key_values=lowercase_       )[0]

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

										# select random slice
										lowercase_   :     Union[str, Any]									=			int(ids_tensor((1,)							,     output_from_past.shape[-1]       )       )
										lowercase_   :     List[str]									=			output_from_no_past[:, -3:, random_slice_idx]
										lowercase_   :     Any									=			output_from_past[:, :, random_slice_idx]

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




def 				lowerCamelCase      ( UpperCAmelCase__			:   List[str] , UpperCAmelCase__			:   Dict , UpperCAmelCase__			:   List[Any] , UpperCAmelCase__			:   Tuple=None , UpperCAmelCase__			:   Union[str, Any]=None , UpperCAmelCase__			:   str=None , UpperCAmelCase__			:   Any=None , UpperCAmelCase__			:   Any=None , )     -> List[Any]:
							if attention_mask is None:
														lowercase_   :     Tuple									=			tf.cast(tf.math.not_equal(UpperCAmelCase__ , config.pad_token_id					) , tf.inta					)
							if decoder_attention_mask is None:
														lowercase_   :     Optional[int]									=			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:
														lowercase_   :     Union[str, Any]									=			tf.ones((config.encoder_layers, config.encoder_attention_heads)					)
							if decoder_head_mask is None:
														lowercase_   :     Optional[int]									=			tf.ones((config.decoder_layers, config.decoder_attention_heads)					)
							if cross_attn_head_mask is None:
														lowercase_   :     Any									=			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        __magic_name__		(       _UpperCAmelCase,	_UpperCAmelCase,	unittest.TestCase):
			UpperCamelCase__							=			(TFMarianMTModel, TFMarianModel) if is_tf_available() else ()
			UpperCamelCase__							=			(TFMarianMTModel,) if is_tf_available() else ()
			UpperCamelCase__							=			(
			    {
			        '''conversational''': TFMarianMTModel,
			        '''feature-extraction''': TFMarianModel,
			        '''summarization''': TFMarianMTModel,
			        '''text2text-generation''': TFMarianMTModel,
			        '''translation''': TFMarianMTModel,
			    }
			    if is_tf_available()
			    else {}
			)
			UpperCamelCase__							=			True
			UpperCamelCase__							=			False
			UpperCamelCase__							=			False







			def       SCREAMING_SNAKE_CASE_	(      self							:    Dict       ):
										lowercase_   :     Dict									=			TFMarianModelTester(self       )
										lowercase_   :     Tuple									=			ConfigTester(self							,     config_class=lowercase_       )







			def       SCREAMING_SNAKE_CASE_	(      self							:    Optional[Any]       ):
										self.config_tester.run_common_tests()







			def       SCREAMING_SNAKE_CASE_	(      self							:    Any       ):
										lowercase_   :     Dict									=			self.model_tester.prepare_config_and_inputs_for_common()
										self.model_tester.check_decoder_model_past_large_inputs(*lowercase_       )





@require_tf
class        __magic_name__		(       unittest.TestCase):
			UpperCamelCase__							=			1000  # show more chars for failing integration tests







			@classmethod
			def       SCREAMING_SNAKE_CASE_	(      cls							:    Optional[int]       ):
										lowercase_   :     Optional[Any]									=			f'''Helsinki-NLP/opus-mt-{cls.src}-{cls.tgt}'''
										return cls







			@cached_property
			def       SCREAMING_SNAKE_CASE_	(      self							:    Tuple       ):
										return AutoTokenizer.from_pretrained(self.model_name       )







			@property
			def       SCREAMING_SNAKE_CASE_	(      self							:    Tuple       ):
										return self.tokenizer.eos_token_id







			@cached_property
			def       SCREAMING_SNAKE_CASE_	(      self							:    Optional[int]       ):
										warnings.simplefilter("""error"""       )
										lowercase_   :     TFMarianMTModel									=			TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name       )
										assert isinstance(lowercase_							,     lowercase_       )
										lowercase_   :     List[Any]									=			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       SCREAMING_SNAKE_CASE_	(      self							:    Union[str, Any]							,     **lowercase_							:    str       ):
										lowercase_   :     List[Any]									=			self.translate_src_text(**lowercase_       )
										self.assertListEqual(self.expected_text							,     lowercase_       )







			def       SCREAMING_SNAKE_CASE_	(      self							:    Union[str, Any]							,     **lowercase_							:    Dict       ):
										lowercase_   :     Dict									=			self.tokenizer(self.src_text							,     **lowercase_							,     padding=lowercase_							,     return_tensors="""tf"""       )
										lowercase_   :     Tuple									=			self.model.generate(
										    model_inputs.input_ids							,     attention_mask=model_inputs.attention_mask							,     num_beams=2							,     max_length=128       )
										lowercase_   :     Any									=			self.tokenizer.batch_decode(generated_ids.numpy()							,     skip_special_tokens=lowercase_       )
										return generated_words





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







			@unittest.skip("""Skipping until #12647 is resolved."""       )
			@slow
			def       SCREAMING_SNAKE_CASE_	(      self							:    List[str]       ):
										self._assert_generated_batch_equal_expected()





@require_sentencepiece
@require_tokenizers
@require_tf
class        __magic_name__		(       _UpperCAmelCase):
			UpperCamelCase__							=			'''en'''
			UpperCamelCase__							=			'''zh'''
			UpperCamelCase__							=			['''My name is Wolfgang and I live in Berlin''']
			UpperCamelCase__							=			['''我叫沃尔夫冈 我住在柏林''']







			@unittest.skip("""Skipping until #12647 is resolved."""       )
			@slow
			def       SCREAMING_SNAKE_CASE_	(      self							:    str       ):
										self._assert_generated_batch_equal_expected()





@require_sentencepiece
@require_tokenizers
@require_tf
class        __magic_name__		(       _UpperCAmelCase):
			UpperCamelCase__							=			'''en'''
			UpperCamelCase__							=			'''ROMANCE'''
			UpperCamelCase__							=			[
			    '''>>fr<< Don\'t spend so much time watching TV.''',
			    '''>>pt<< Your message has been sent.''',
			    '''>>es<< He\'s two years older than me.''',
			]
			UpperCamelCase__							=			[
			    '''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       SCREAMING_SNAKE_CASE_	(      self							:    Optional[int]       ):
										self._assert_generated_batch_equal_expected()







			@unittest.skip("""Skipping until #12647 is resolved."""       )
			@slow
			def       SCREAMING_SNAKE_CASE_	(      self							:    Tuple       ):
										lowercase_   :     List[str]									=			TranslationPipeline(self.model							,     self.tokenizer							,     framework="""tf"""       )
										lowercase_   :     Optional[int]									=			pipeline(self.src_text       )
										self.assertEqual(self.expected_text							,     [x["""translation_text"""] for x in output]       )





