



"""simple docstring"""


import unittest

import numpy as np
import timeout_decorator  # noqa

from transformers import MarianConfig, is_flax_available
from transformers.testing_utils import require_flax, require_sentencepiece, require_tokenizers, slow
from transformers.utils import cached_property

from ...generation.test_flax_utils import FlaxGenerationTesterMixin
from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor


if is_flax_available():
				import os

				# The slow tests are often failing with OOM error on GPU
				# This makes JAX allocate exactly what is needed on demand, and deallocate memory that is no longer needed
				# but will be slower as stated here https://jax.readthedocs.io/en/latest/gpu_memory_allocation.html
				snake_case_								=			"""platform"""

				import jax
				import jax.numpy as jnp

				from transformers import MarianTokenizer
				from transformers.models.marian.modeling_flax_marian import FlaxMarianModel, FlaxMarianMTModel, shift_tokens_right

def 					_lowerCAmelCase (  lowercase_						,      lowercase_						,      lowercase_=None						,      lowercase_=None						,      lowercase_=None						,      lowercase_=None						,      lowercase_=None						,      lowercase_=None						,      ):
						if attention_mask is None:
												UpperCAmelCase			 =					np.where(input_ids != config.pad_token_id						,      1						,      0		)
						if decoder_attention_mask is None:
												UpperCAmelCase			 =					np.where(decoder_input_ids != config.pad_token_id						,      1						,      0		)
						if head_mask is None:
												UpperCAmelCase			 =					np.ones((config.encoder_layers, config.encoder_attention_heads)		)
						if decoder_head_mask is None:
												UpperCAmelCase			 =					np.ones((config.decoder_layers, config.decoder_attention_heads)		)
						if cross_attn_head_mask is None:
												UpperCAmelCase			 =					np.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": attention_mask,
						}







class  A_     :



						"""simple docstring"""






						def __init__(   self					:Any  ,    lowercase_					:Tuple  ,    lowercase_					:List[str]=13  ,    lowercase_					:Optional[int]=7  ,    lowercase_					:List[Any]=True  ,    lowercase_					:Any=False  ,    lowercase_					:Optional[Any]=99  ,    lowercase_					:Optional[int]=16  ,    lowercase_					:List[Any]=2  ,    lowercase_					:Tuple=4  ,    lowercase_					:Optional[int]=4  ,    lowercase_					:Union[str, Any]="gelu"  ,    lowercase_					:List[Any]=0.1  ,    lowercase_					:int=0.1  ,    lowercase_					:List[str]=32  ,    lowercase_					:Dict=2  ,    lowercase_					:Optional[Any]=1  ,    lowercase_					:int=0  ,    lowercase_					:Union[str, Any]=0.02  ,    )							->     Any:
												UpperCAmelCase			 =					parent
												UpperCAmelCase			 =					batch_size
												UpperCAmelCase			 =					seq_length
												UpperCAmelCase			 =					is_training
												UpperCAmelCase			 =					use_labels
												UpperCAmelCase			 =					vocab_size
												UpperCAmelCase			 =					hidden_size
												UpperCAmelCase			 =					num_hidden_layers
												UpperCAmelCase			 =					num_attention_heads
												UpperCAmelCase			 =					intermediate_size
												UpperCAmelCase			 =					hidden_act
												UpperCAmelCase			 =					hidden_dropout_prob
												UpperCAmelCase			 =					attention_probs_dropout_prob
												UpperCAmelCase			 =					max_position_embeddings
												UpperCAmelCase			 =					eos_token_id
												UpperCAmelCase			 =					pad_token_id
												UpperCAmelCase			 =					bos_token_id
												UpperCAmelCase			 =					initializer_range






						def       UpperCAmelCase__	(   self					:List[str]   )							->     Tuple:
												UpperCAmelCase			 =					np.clip(ids_tensor([self.batch_size, self.seq_length - 1]  ,    self.vocab_size   )  ,    3  ,    self.vocab_size   )
												UpperCAmelCase			 =					np.concatenate((input_ids, 2 * np.ones((self.batch_size, 1)  ,    dtype=np.intaa   ))  ,    -1   )

												UpperCAmelCase			 =					shift_tokens_right(lowercase_  ,    1  ,    2   )

												UpperCAmelCase			 =					MarianConfig(
												    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_id=self.eos_token_id  ,    bos_token_id=self.bos_token_id  ,    pad_token_id=self.pad_token_id  ,    initializer_range=self.initializer_range  ,    use_cache=lowercase_  ,    )
												UpperCAmelCase			 =					prepare_marian_inputs_dict(lowercase_  ,    lowercase_  ,    lowercase_   )
												return config, inputs_dict






						def       UpperCAmelCase__	(   self					:Tuple   )							->     Any:
												UpperCAmelCase ,       UpperCAmelCase			 =					self.prepare_config_and_inputs()
												return config, inputs_dict






						def       UpperCAmelCase__	(   self					:Tuple  ,    lowercase_					:List[Any]  ,    lowercase_					:Any  ,    lowercase_					:str   )							->     Tuple:
												UpperCAmelCase			 =					20
												UpperCAmelCase			 =					model_class_name(lowercase_   )

												UpperCAmelCase			 =					model.encode(inputs_dict['input_ids']   )

												UpperCAmelCase ,       UpperCAmelCase			 =					(
												    inputs_dict['decoder_input_ids'],
												    inputs_dict['decoder_attention_mask'],
												)

												UpperCAmelCase			 =					model.init_cache(decoder_input_ids.shape[0]  ,    lowercase_  ,    lowercase_   )
												UpperCAmelCase			 =					jnp.ones((decoder_input_ids.shape[0], max_decoder_length)  ,    dtype='i4'   )

												UpperCAmelCase			 =					jnp.broadcast_to(
												    jnp.arange(decoder_input_ids.shape[-1] - 1   )[None, :]  ,    (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1)  ,    )
												UpperCAmelCase			 =					model.decode(
												    decoder_input_ids[:, :-1]  ,    lowercase_  ,    decoder_attention_mask=lowercase_  ,    past_key_values=lowercase_  ,    decoder_position_ids=lowercase_  ,    )

												UpperCAmelCase			 =					jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]]  ,    dtype='i4'   )
												UpperCAmelCase			 =					model.decode(
												    decoder_input_ids[:, -1:]  ,    lowercase_  ,    decoder_attention_mask=lowercase_  ,    past_key_values=outputs_cache.past_key_values  ,    decoder_position_ids=lowercase_  ,    )

												UpperCAmelCase			 =					model.decode(lowercase_  ,    lowercase_   )

												UpperCAmelCase			 =					np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5])   )   )
												self.parent.assertTrue(diff < 1E-3  ,    msg=f"""Max diff is {diff}"""   )






						def       UpperCAmelCase__	(   self					:Optional[int]  ,    lowercase_					:List[Any]  ,    lowercase_					:Union[str, Any]  ,    lowercase_					:Any   )							->     Optional[Any]:
												UpperCAmelCase			 =					20
												UpperCAmelCase			 =					model_class_name(lowercase_   )

												UpperCAmelCase			 =					model.encode(inputs_dict['input_ids']   )

												UpperCAmelCase ,       UpperCAmelCase			 =					(
												    inputs_dict['decoder_input_ids'],
												    inputs_dict['decoder_attention_mask'],
												)

												UpperCAmelCase			 =					jnp.concatenate(
												    [
												        decoder_attention_mask,
												        jnp.zeros((decoder_attention_mask.shape[0], max_decoder_length - decoder_attention_mask.shape[1])   ),
												    ]  ,    axis=-1  ,    )

												UpperCAmelCase			 =					model.init_cache(decoder_input_ids.shape[0]  ,    lowercase_  ,    lowercase_   )
												UpperCAmelCase			 =					jnp.broadcast_to(
												    jnp.arange(decoder_input_ids.shape[-1] - 1   )[None, :]  ,    (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1)  ,    )

												UpperCAmelCase			 =					model.decode(
												    decoder_input_ids[:, :-1]  ,    lowercase_  ,    decoder_attention_mask=lowercase_  ,    past_key_values=lowercase_  ,    decoder_position_ids=lowercase_  ,    )
												UpperCAmelCase			 =					jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]]  ,    dtype='i4'   )
												UpperCAmelCase			 =					model.decode(
												    decoder_input_ids[:, -1:]  ,    lowercase_  ,    past_key_values=outputs_cache.past_key_values  ,    decoder_attention_mask=lowercase_  ,    decoder_position_ids=lowercase_  ,    )

												UpperCAmelCase			 =					model.decode(lowercase_  ,    lowercase_  ,    decoder_attention_mask=lowercase_   )

												UpperCAmelCase			 =					np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5])   )   )
												self.parent.assertTrue(diff < 1E-3  ,    msg=f"""Max diff is {diff}"""   )







@require_flax
class  A_     (	SCREAMING_SNAKE_CASE_      ,  unittest.TestCase      ,  SCREAMING_SNAKE_CASE_							):



						"""simple docstring"""
						__UpperCamelCase													=				True
						__UpperCamelCase													=				(FlaxMarianModel, FlaxMarianMTModel) if is_flax_available() else ()
						__UpperCamelCase													=				(FlaxMarianMTModel,) if is_flax_available() else ()






						def       UpperCAmelCase__	(   self					:List[str]   )							->     Tuple:
												UpperCAmelCase			 =					FlaxMarianModelTester(self   )






						def       UpperCAmelCase__	(   self					:Optional[Any]   )							->     Optional[Any]:
												UpperCAmelCase ,       UpperCAmelCase			 =					self.model_tester.prepare_config_and_inputs()
												for model_class in self.all_model_classes:
																		self.model_tester.check_use_cache_forward(lowercase_  ,    lowercase_  ,    lowercase_   )






						def       UpperCAmelCase__	(   self					:List[str]   )							->     str:
												UpperCAmelCase ,       UpperCAmelCase			 =					self.model_tester.prepare_config_and_inputs()
												for model_class in self.all_model_classes:
																		self.model_tester.check_use_cache_forward_with_attn_mask(lowercase_  ,    lowercase_  ,    lowercase_   )






						def       UpperCAmelCase__	(   self					:Dict   )							->     Tuple:
												UpperCAmelCase ,       UpperCAmelCase			 =					self.model_tester.prepare_config_and_inputs_for_common()

												for model_class in self.all_model_classes:
																		with self.subTest(model_class.__name__   ):
																								UpperCAmelCase			 =					self._prepare_for_class(lowercase_  ,    lowercase_   )
																								UpperCAmelCase			 =					model_class(lowercase_   )

																								@jax.jit
																								def encode_jitted(lowercase_					:List[Any]  ,    lowercase_					:int=None  ,    **lowercase_					:List[str]   ):
																														return model.encode(input_ids=lowercase_  ,    attention_mask=lowercase_   )

																								with self.subTest('JIT Enabled'   ):
																														UpperCAmelCase			 =					encode_jitted(**lowercase_   ).to_tuple()

																								with self.subTest('JIT Disabled'   ):
																														with jax.disable_jit():
																																				UpperCAmelCase			 =					encode_jitted(**lowercase_   ).to_tuple()

																								self.assertEqual(len(lowercase_   )  ,    len(lowercase_   )   )
																								for jitted_output, output in zip(lowercase_  ,    lowercase_   ):
																														self.assertEqual(jitted_output.shape  ,    output.shape   )






						def       UpperCAmelCase__	(   self					:List[str]   )							->     List[str]:
												UpperCAmelCase ,       UpperCAmelCase			 =					self.model_tester.prepare_config_and_inputs_for_common()

												for model_class in self.all_model_classes:
																		with self.subTest(model_class.__name__   ):
																								UpperCAmelCase			 =					model_class(lowercase_   )
																								UpperCAmelCase			 =					model.encode(inputs_dict['input_ids']  ,    inputs_dict['attention_mask']   )

																								UpperCAmelCase			 =					{
																								    'decoder_input_ids': inputs_dict['decoder_input_ids'],
																								    'decoder_attention_mask': inputs_dict['decoder_attention_mask'],
																								    'encoder_outputs': encoder_outputs,
																								}

																								@jax.jit
																								def decode_jitted(lowercase_					:List[str]  ,    lowercase_					:Any  ,    lowercase_					:int   ):
																														return model.decode(
																														    decoder_input_ids=lowercase_  ,    decoder_attention_mask=lowercase_  ,    encoder_outputs=lowercase_  ,    )

																								with self.subTest('JIT Enabled'   ):
																														UpperCAmelCase			 =					decode_jitted(**lowercase_   ).to_tuple()

																								with self.subTest('JIT Disabled'   ):
																														with jax.disable_jit():
																																				UpperCAmelCase			 =					decode_jitted(**lowercase_   ).to_tuple()

																								self.assertEqual(len(lowercase_   )  ,    len(lowercase_   )   )
																								for jitted_output, output in zip(lowercase_  ,    lowercase_   ):
																														self.assertEqual(jitted_output.shape  ,    output.shape   )






						@slow
						def       UpperCAmelCase__	(   self					:str   )							->     Optional[Any]:
												for model_class_name in self.all_model_classes:
																		UpperCAmelCase			 =					model_class_name.from_pretrained('Helsinki-NLP/opus-mt-en-de'   )
																		# FlaxMarianForSequenceClassification expects eos token in input_ids
																		UpperCAmelCase			 =					np.ones((1, 1)   ) * model.config.eos_token_id
																		UpperCAmelCase			 =					model(lowercase_   )
																		self.assertIsNotNone(lowercase_   )







@require_flax
@require_sentencepiece
@require_tokenizers
class  A_     (	unittest.TestCase							):



						"""simple docstring"""
						__UpperCamelCase													=				None
						__UpperCamelCase													=				None






						@classmethod
						def       UpperCAmelCase__	(   cls					:Any   )							->     None:
												UpperCAmelCase			 =					f"""Helsinki-NLP/opus-mt-{cls.src}-{cls.tgt}"""
												return cls






						@cached_property
						def       UpperCAmelCase__	(   self					:Optional[int]   )							->     Tuple:
												return MarianTokenizer.from_pretrained(self.model_name   )






						@property
						def       UpperCAmelCase__	(   self					:Optional[Any]   )							->     int:
												return self.tokenizer.eos_token_id






						@cached_property
						def       UpperCAmelCase__	(   self					:Dict   )							->     Union[str, Any]:
												UpperCAmelCase			 =					FlaxMarianMTModel.from_pretrained(self.model_name   )
												self.assertEqual(model.config.decoder_start_token_id  ,    model.config.pad_token_id   )
												return model






						def       UpperCAmelCase__	(   self					:List[str]  ,    **lowercase_					:int   )							->     Union[str, Any]:
												UpperCAmelCase			 =					self.translate_src_text(**lowercase_   )
												self.assertListEqual(self.expected_text  ,    lowercase_   )






						def       UpperCAmelCase__	(   self					:Dict  ,    **lowercase_					:Tuple   )							->     List[Any]:
												UpperCAmelCase			 =					self.tokenizer(self.src_text  ,    padding=lowercase_  ,    return_tensors='np'  ,    **lowercase_   )
												UpperCAmelCase			 =					self.model.generate(
												    model_inputs.input_ids  ,    attention_mask=model_inputs.attention_mask  ,    num_beams=2  ,    max_length=1_28  ,    ).sequences
												UpperCAmelCase			 =					self.tokenizer.batch_decode(lowercase_  ,    skip_special_tokens=lowercase_   )
												return generated_words







@require_flax
@require_sentencepiece
@require_tokenizers
class  A_     (	SCREAMING_SNAKE_CASE_							):



						"""simple docstring"""
						__UpperCamelCase													=				"""en"""
						__UpperCamelCase													=				"""fr"""
						__UpperCamelCase													=				[
						    """I am a small frog.""",
						    """Now I can forget the 100 words of german that I know.""",
						]
						__UpperCamelCase													=				[
						    """Je suis une petite grenouille.""",
						    """Maintenant, je peux oublier les 100 mots d'allemand que je connais.""",
						]






						@slow
						def       UpperCAmelCase__	(   self					:List[Any]   )							->     List[str]:
												self._assert_generated_batch_equal_expected()







@require_flax
@require_sentencepiece
@require_tokenizers
class  A_     (	SCREAMING_SNAKE_CASE_							):



						"""simple docstring"""
						__UpperCamelCase													=				"""fr"""
						__UpperCamelCase													=				"""en"""
						__UpperCamelCase													=				[
						    """Donnez moi le micro.""",
						    """Tom et Mary étaient assis à une table.""",  # Accents
						]
						__UpperCamelCase													=				[
						    """Give me the microphone.""",
						    """Tom and Mary were sitting at a table.""",
						]






						@slow
						def       UpperCAmelCase__	(   self					:Optional[int]   )							->     int:
												self._assert_generated_batch_equal_expected()







@require_flax
@require_sentencepiece
@require_tokenizers
class  A_     (	SCREAMING_SNAKE_CASE_							):



						"""simple docstring"""
						__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."""]






						@slow
						def       UpperCAmelCase__	(   self					:List[Any]   )							->     Optional[Any]:
												self._assert_generated_batch_equal_expected()







@require_flax
@require_sentencepiece
@require_tokenizers
class  A_     (	SCREAMING_SNAKE_CASE_							):



						"""simple docstring"""
						__UpperCamelCase													=				"""en"""
						__UpperCamelCase													=				"""de"""
						__UpperCamelCase													=				[
						    """I am a small frog.""",
						    """Now I can forget the 100 words of german that I know.""",
						    """Tom asked his teacher for advice.""",
						    """That's how I would do it.""",
						    """Tom really admired Mary's courage.""",
						    """Turn around and close your eyes.""",
						]
						__UpperCamelCase													=				[
						    """Ich bin ein kleiner Frosch.""",
						    """Jetzt kann ich die 100 Wörter des Deutschen vergessen, die ich kenne.""",
						    """Tom bat seinen Lehrer um Rat.""",
						    """So würde ich das machen.""",
						    """Tom bewunderte Marias Mut wirklich.""",
						    """Drehen Sie sich um und schließen Sie die Augen.""",
						]






						@slow
						def       UpperCAmelCase__	(   self					:Optional[Any]   )							->     Union[str, Any]:
												self._assert_generated_batch_equal_expected()







@require_flax
@require_sentencepiece
@require_tokenizers
class  A_     (	SCREAMING_SNAKE_CASE_							):



						"""simple docstring"""
						__UpperCamelCase													=				"""en"""
						__UpperCamelCase													=				"""zh"""
						__UpperCamelCase													=				["""My name is Wolfgang and I live in Berlin"""]
						__UpperCamelCase													=				["""我叫沃尔夫冈 我住在柏林"""]






						@slow
						def       UpperCAmelCase__	(   self					:Any   )							->     Union[str, Any]:
												self._assert_generated_batch_equal_expected()







@require_flax
@require_sentencepiece
@require_tokenizers
class  A_     (	SCREAMING_SNAKE_CASE_							):



						"""simple docstring"""
						__UpperCamelCase													=				"""ru"""
						__UpperCamelCase													=				"""fr"""
						__UpperCamelCase													=				["""Он показал мне рукопись своей новой пьесы."""]
						__UpperCamelCase													=				["""Il m'a montré le manuscrit de sa nouvelle pièce."""]






						@slow
						def       UpperCAmelCase__	(   self					:str   )							->     Any:
												self._assert_generated_batch_equal_expected()







@require_flax
@require_sentencepiece
@require_tokenizers
class  A_     (	SCREAMING_SNAKE_CASE_							):



						"""simple docstring"""
						__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.""",
						]






						@slow
						def       UpperCAmelCase__	(   self					:List[str]   )							->     Any:
												self._assert_generated_batch_equal_expected()











import importlib.util
import weakref
from functools import partialmethod

from .dependency_versions_check import dep_version_check
from .utils import is_accelerate_available, is_torch_available, logging


if is_torch_available():
				import torch

lowercase_      :							int    							=					logging.get_logger(__name__)


def 				__SCREAMING_SNAKE_CASE    (     ):

						'''simple docstring'''


						return importlib.util.find_spec("deepspeed"		) is not None


if is_accelerate_available() and is_deepspeed_available():
				from accelerate.utils.deepspeed import HfDeepSpeedConfig as DeepSpeedConfig
else:
				# Inherits from a dummy `object` if accelerate is not available, so that python succeeds to import this file.
				# Deepspeed glue code will never inherit this dummy object as it checks if accelerate is available.
				from builtins import object as DeepSpeedConfig






class        __lowerCAmelCase					(			UpperCAmelCase__					):







			def __init__(			self       :     Dict       ,       snake_case__       :     Dict ):




									"""simple docstring"""


									set_hf_deepspeed_config(self )
									dep_version_check("accelerate" )
									dep_version_check("deepspeed" )
									super().__init__(snake_case__ )






class        __lowerCAmelCase					(			UpperCAmelCase__					):







			def __init__(			self       :     str       ,       snake_case__       :     Optional[Any] ):




									"""simple docstring"""


									super().__init__(snake_case__ )
									_UpperCAmelCase						=	None
									_UpperCAmelCase						=	[]







			def UpperCamelCase     (			self       :     List[Any] ):




									"""simple docstring"""


									if self._dtype is None:
															raise ValueError("trainer_config_process() wasn't called yet to tell dtype" )
									return self._dtype







			def UpperCamelCase     (			self       :     str       ,       snake_case__       :     Dict ):




									"""simple docstring"""


									_UpperCAmelCase						=	self.get_value(snake_case__ )
									if val is None:
															return False
									else:
															return val == "auto"







			def UpperCamelCase     (			self       :     Union[str, Any]       ,       snake_case__       :     Optional[int]       ,       snake_case__       :     Optional[Any]       ,       snake_case__       :     Dict=None       ,       snake_case__       :     int=True ):




									"""simple docstring"""


									_UpperCAmelCase				,					_UpperCAmelCase						=	self.find_config_node(snake_case__ )
									if config is None:
															return

									if config.get(snake_case__ ) == "auto":
															_UpperCAmelCase						=	hf_val
															return

									if not must_match:
															return

									_UpperCAmelCase						=	config.get(snake_case__ )
									if ds_val is not None and ds_val != hf_val:
															self.mismatches.append(F"""- ds {ds_key_long}={ds_val} vs hf {hf_key}={hf_val}""" )

			snake_case_ :					Optional[Any]						=	partialmethod(UpperCAmelCase__   ,						must_match=UpperCAmelCase__					)







			def UpperCamelCase     (			self       :     Any       ,       snake_case__       :     Optional[int] ):




									"""simple docstring"""


									_UpperCAmelCase						=	args.world_size * args.per_device_train_batch_size * args.gradient_accumulation_steps
									self.fill_match(
									    "train_micro_batch_size_per_gpu"       ,       args.per_device_train_batch_size       ,       "per_device_train_batch_size" )
									self.fill_match("gradient_accumulation_steps"       ,       args.gradient_accumulation_steps       ,       "gradient_accumulation_steps" )
									self.fill_match("train_batch_size"       ,       snake_case__       ,       "train_batch_size (calculated)" )
									self.fill_match("gradient_clipping"       ,       args.max_grad_norm       ,       "max_grad_norm" )

									self.fill_match("optimizer.params.lr"       ,       args.learning_rate       ,       "learning_rate" )
									self.fill_match("optimizer.params.betas"       ,       [args.adam_betaa, args.adam_betaa]       ,       "adam_beta1+adam_beta2" )
									self.fill_match("optimizer.params.eps"       ,       args.adam_epsilon       ,       "adam_epsilon" )
									self.fill_match("optimizer.params.weight_decay"       ,       args.weight_decay       ,       "weight_decay" )

									self.fill_only("scheduler.params.warmup_min_lr"       ,       0 )  # not a trainer arg
									self.fill_match("scheduler.params.warmup_max_lr"       ,       args.learning_rate       ,       "learning_rate" )
									# total_num_steps - will get set in trainer_config_finalize

									# fp16
									if args.fpaa or args.fpaa_full_eval:
															_UpperCAmelCase						=	"apex" if args.fpaa_backend == "apex" else "amp"
									else:
															_UpperCAmelCase						=	None

									if args.save_on_each_node:
															# deepspeed uses shared storage by default. Let's override this setting if save_on_each_node == True
															_UpperCAmelCase						=	self.config.get("checkpoint"       ,       {} )
															_UpperCAmelCase						=	args.save_on_each_node

									# amp: similar to the pytorch native amp - it has a bunch of optional params but we won't set
									# any here unless the user did the work
									self.fill_match(
									    "fp16.enabled"       ,       ((args.fpaa or args.fpaa_full_eval) and fpaa_backend == "amp")       ,       "fp16|fp16_full_eval+fp16_backend(amp)"       ,       )

									# apex: delegates amp work to apex (which needs to be available), but it cannot be used with any
									# ZeRO features
									self.fill_match("amp.enabled"       ,       fpaa_backend == "apex"       ,       "fp16+fp16_backend(apex)" )
									self.fill_match("amp.opt_level"       ,       args.fpaa_opt_level       ,       "fp16_opt_level" )

									self.fill_match("bf16.enabled"       ,       (args.bfaa or args.bfaa_full_eval)       ,       "bf16|bf16_full_eval" )

									# deepspeed's default mode is fp16 unless there is a config that says differently
									if self.is_true("bf16.enabled" ):
															_UpperCAmelCase						=	torch.bfloataa
									elif self.is_false("fp16.enabled" ):
															_UpperCAmelCase						=	torch.floataa
									else:
															_UpperCAmelCase						=	torch.floataa







			def UpperCamelCase     (			self       :     Tuple       ,       snake_case__       :     Union[str, Any]       ,       snake_case__       :     Dict       ,       snake_case__       :     List[Any] ):




									"""simple docstring"""


									_UpperCAmelCase						=	[
									    "zero_optimization.reduce_bucket_size",
									    "zero_optimization.stage3_prefetch_bucket_size",
									    "zero_optimization.stage3_param_persistence_threshold",
									]
									_UpperCAmelCase						=	[x for x in hidden_size_based_keys if self.is_auto(snake_case__ )]

									if len(snake_case__ ) > 0:
															if hasattr(model.config       ,       "hidden_size" ):
																					_UpperCAmelCase						=	model.config.hidden_size
															elif hasattr(model.config       ,       "hidden_sizes" ):
																					# if there are many hidden sizes pick the largest one
																					_UpperCAmelCase						=	max(model.config.hidden_sizes )
															else:
																					raise ValueError(
																					    "The model's config file has neither `hidden_size` nor `hidden_sizes` entry, "
																					    "therefore it's not possible to automatically fill out the following `auto` entries "
																					    F"""in the DeepSpeed config file: {hidden_size_auto_keys}. You can fix that by replacing """
																					    "`auto` values for these keys with an integer value of your choice." )

															self.fill_only("zero_optimization.reduce_bucket_size"       ,       hidden_size * hidden_size )
															if self.is_zeroa():
																					# automatically assign the optimal config values based on model config
																					self.fill_only("zero_optimization.stage3_prefetch_bucket_size"       ,       0.9 * hidden_size * hidden_size )
																					self.fill_only("zero_optimization.stage3_param_persistence_threshold"       ,       10 * hidden_size )

        # scheduler
									self.fill_match("scheduler.params.total_num_steps"       ,       snake_case__       ,       "num_training_steps (calculated)" )
									self.fill_match("scheduler.params.warmup_num_steps"       ,       args.get_warmup_steps(snake_case__ )       ,       "warmup_steps" )

									if len(self.mismatches ) > 0:
															_UpperCAmelCase						=	"\n".join(self.mismatches )
															raise ValueError(
															    "Please correct the following DeepSpeed config values that mismatch TrainingArguments"
															    F""" values:\n{mismatches}\nThe easiest method is to set these DeepSpeed config values to 'auto'.""" )




lowercase_      :							Union[str, Any]    							=					None


def 				__SCREAMING_SNAKE_CASE    (     snake_case_		):

						'''simple docstring'''


						global _hf_deepspeed_config_weak_ref
						# will go away automatically when HfDeepSpeedConfig is destroyed (when TrainingArguments is destroyed)
						_UpperCAmelCase						=	weakref.ref(snake_case_		)


def 				__SCREAMING_SNAKE_CASE    (     ):

						'''simple docstring'''


						global _hf_deepspeed_config_weak_ref
						_UpperCAmelCase						=	None


def 				__SCREAMING_SNAKE_CASE    (     ):

						'''simple docstring'''


						if _hf_deepspeed_config_weak_ref is not None and _hf_deepspeed_config_weak_ref() is not None:
												return _hf_deepspeed_config_weak_ref().is_zeroa()
						else:
												return False


def 				__SCREAMING_SNAKE_CASE    (     ):

						'''simple docstring'''


						if _hf_deepspeed_config_weak_ref is not None and _hf_deepspeed_config_weak_ref() is not None:
												return _hf_deepspeed_config_weak_ref().config
						else:
												return None


def 				__SCREAMING_SNAKE_CASE    (     snake_case_      ,       snake_case_      ,       snake_case_      ,       snake_case_      ,       snake_case_		):

						'''simple docstring'''


						from accelerate.utils import DummyOptim, DummyScheduler

						_UpperCAmelCase						=	hf_deepspeed_config.config

						# Optimizer + Scheduler
						# Currently supported combos:
						# 1. DS scheduler + DS optimizer: Yes
						# 2. HF scheduler + HF optimizer: Yes
						# 3. DS scheduler + HF optimizer: Yes
						# 4. HF scheduler + DS optimizer: No
						#
						# Unless Offload is enabled in which case it's:
						# 1. DS scheduler + DS optimizer: Yes
						# 2. HF scheduler + HF optimizer: Mostly*
						# 3. DS scheduler + HF optimizer: Mostly*
						# 4. HF scheduler + DS optimizer: No
						#
						# Mostly*: All non-native DeepSpeed optimizers that have both CPU and GPU implementation should work (except LAMB)

						_UpperCAmelCase						=	None
						if "optimizer" in config:
												if args.adafactor:
																		raise ValueError(
																		    "--adafactor was passed, but also found `optimizer` configured in the DeepSpeed config. "
																		    "Only one optimizer can be configured."		)
												_UpperCAmelCase						=	DummyOptim(params=snake_case_		)
						else:
												if hf_deepspeed_config.is_offload():
																		logger.info(
																		    "Detected ZeRO Offload and non-DeepSpeed optimizers: This combination should work as long as the"
																		    " custom optimizer has both CPU and GPU implementation (except LAMB)"		)

												# ds supports Adam, OneBitAdam, and Lamb optimizers and can import other optimizers from torch.
												# But trainer uses AdamW by default.
												_UpperCAmelCase						=	trainer.create_optimizer()
												# To use other optimizers requires voiding warranty with: `zero_allow_untested_optimizer`
												_UpperCAmelCase						=	True

						_UpperCAmelCase						=	None
						if "scheduler" in config:
												_UpperCAmelCase						=	DummyScheduler(snake_case_		)
						else:
												if isinstance(snake_case_      ,       snake_case_		):
																		raise ValueError(
																		    "Found `optimizer` configured in the DeepSpeed config, but no `scheduler`. "
																		    "Please configure a scheduler in the DeepSpeed config."		)
												_UpperCAmelCase						=	trainer.create_scheduler(num_training_steps=snake_case_      ,       optimizer=snake_case_		)

						return optimizer, lr_scheduler


def 				__SCREAMING_SNAKE_CASE    (     snake_case_      ,       snake_case_      ,       snake_case_=False		):

						'''simple docstring'''


						from deepspeed.utils import logger as ds_logger

						_UpperCAmelCase						=	trainer.model
						_UpperCAmelCase						=	trainer.args

						_UpperCAmelCase						=	trainer.accelerator.state.deepspeed_plugin.hf_ds_config

						# resume config update - some bits like `model` and `num_training_steps` only become available during train
						hf_deepspeed_config.trainer_config_finalize(snake_case_      ,       snake_case_      ,       snake_case_		)

						# set the Deepspeed log level consistent with the Trainer
						ds_logger.setLevel(args.get_process_log_level()		)

						if inference:
												# only Z3 makes sense for the inference
												if not hf_deepspeed_config.is_zeroa():
																		raise ValueError("ZeRO inference only makes sense with ZeRO Stage 3 - please adjust your config"		)

												# in case the training config is re-used for inference
												hf_deepspeed_config.del_config_sub_tree("optimizer"		)
												hf_deepspeed_config.del_config_sub_tree("lr_scheduler"		)
												_UpperCAmelCase				,					_UpperCAmelCase						=	None, None
												_UpperCAmelCase						=	None
						else:
												_UpperCAmelCase						=	None  # important for when deepspeed_init is used as re-init
												_UpperCAmelCase						=	list(filter(lambda snake_case_		: p.requires_grad      ,       model.parameters()		)		)
												_UpperCAmelCase				,					_UpperCAmelCase						=	deepspeed_optim_sched(
												    snake_case_      ,       snake_case_      ,       snake_case_      ,       snake_case_      ,       snake_case_		)

						# keep for quick debug:
						# from pprint import pprint; pprint(config)

						return optimizer, lr_scheduler





def 				__SCREAMING_SNAKE_CASE    (     snake_case_      ,       snake_case_		):

						'''simple docstring'''


						import glob

						_UpperCAmelCase						=	sorted(glob.glob(f"""{checkpoint_path}/global_step*"""		)		)

						if len(snake_case_		) > 0:
												logger.info(f"""Attempting to resume from {checkpoint_path}"""		)
												# this magically updates self.optimizer and self.lr_scheduler
												_UpperCAmelCase				,					_UpperCAmelCase						=	deepspeed_engine.load_checkpoint(
												    snake_case_      ,       load_optimizer_states=snake_case_      ,       load_lr_scheduler_states=snake_case_		)
												if load_path is None:
																		raise ValueError(f"""[deepspeed] failed to resume from checkpoint {checkpoint_path}"""		)
						else:
												raise ValueError(f"""Can't find a valid checkpoint at {checkpoint_path}"""		)




