




'''simple docstring'''





from __future__ import annotations

import unittest

from transformers import EsmConfig, is_tf_available
from transformers.testing_utils import require_tf, slow

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


if is_tf_available():
		import numpy
		import tensorflow as tf

		from transformers.models.esm.modeling_tf_esm import (
		    TF_ESM_PRETRAINED_MODEL_ARCHIVE_LIST,
		    TFEsmForMaskedLM,
		    TFEsmForSequenceClassification,
		    TFEsmForTokenClassification,
		    TFEsmModel,
		)




class 			_snake_case		:




			def __init__( self    ,							a__    ,							)    ->    int:

										'''simple docstring'''




										snake_case_      =				parent
										snake_case_      =				13
										snake_case_      =				7
										snake_case_      =				True
										snake_case_      =				True
										snake_case_      =				True
										snake_case_      =				99
										snake_case_      =				32
										snake_case_      =				2
										snake_case_      =				4
										snake_case_      =				37
										snake_case_      =				"gelu"
										snake_case_      =				0.1
										snake_case_      =				0.1
										snake_case_      =				512
										snake_case_      =				16
										snake_case_      =				2
										snake_case_      =				0.0_2
										snake_case_      =				3
										snake_case_      =				4
										snake_case_      =				None




			def        lowerCAmelCase__    ( self							)    ->    Dict:

										'''simple docstring'''




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

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

										snake_case_      =				None
										snake_case_      =				None
										snake_case_      =				None
										if self.use_labels:
																	snake_case_      =				ids_tensor([self.batch_size]    ,							self.type_sequence_label_size							)
																	snake_case_      =				ids_tensor([self.batch_size, self.seq_length]    ,							self.num_labels							)
																	snake_case_      =				ids_tensor([self.batch_size]    ,							self.num_choices							)

										snake_case_      =				EsmConfig(
										    vocab_size=self.vocab_size    ,							hidden_size=self.hidden_size    ,							num_hidden_layers=self.num_hidden_layers    ,							pad_token_id=1    ,							num_attention_heads=self.num_attention_heads    ,							intermediate_size=self.intermediate_size    ,							hidden_act=self.hidden_act    ,							hidden_dropout_prob=self.hidden_dropout_prob    ,							attention_probs_dropout_prob=self.attention_probs_dropout_prob    ,							max_position_embeddings=self.max_position_embeddings    ,							type_vocab_size=self.type_vocab_size    ,							initializer_range=self.initializer_range    ,							)

										return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels




			def        lowerCAmelCase__    ( self							)    ->    str:

										'''simple docstring'''




										(
										    (
										    snake_case_
										) ,				(
										    snake_case_
										) ,				(
										    snake_case_
										) ,				(
										    snake_case_
										) ,				(
										    snake_case_
										) ,				(
										    snake_case_
										) ,				
										)      =				self.prepare_config_and_inputs()

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

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




			def        lowerCAmelCase__    ( self    ,							a__    ,							a__    ,							a__    ,							a__    ,							a__    ,							a__							)    ->    List[Any]:

										'''simple docstring'''




										snake_case_      =				TFEsmModel(config=a__							)
										snake_case_      =				{"input_ids": input_ids, "attention_mask": input_mask}
										snake_case_      =				model(a__							)

										snake_case_      =				[input_ids, input_mask]
										snake_case_      =				model(a__							)

										snake_case_      =				model(a__							)

										self.parent.assertEqual(result.last_hidden_state.shape    ,							(self.batch_size, self.seq_length, self.hidden_size)							)




			def        lowerCAmelCase__    ( self    ,							a__    ,							a__    ,							a__    ,							a__    ,							a__    ,							a__    ,							a__    ,							a__    ,							)    ->    List[str]:

										'''simple docstring'''




										snake_case_      =				True

										snake_case_      =				TFEsmModel(config=a__							)
										snake_case_      =				{
										    "input_ids": input_ids,
										    "attention_mask": input_mask,
										    "encoder_hidden_states": encoder_hidden_states,
										    "encoder_attention_mask": encoder_attention_mask,
										}
										snake_case_      =				model(a__							)

										snake_case_      =				[input_ids, input_mask]
										snake_case_      =				model(a__    ,							encoder_hidden_states=a__							)

										# Also check the case where encoder outputs are not passed
										snake_case_      =				model(a__    ,							attention_mask=a__							)

										self.parent.assertEqual(result.last_hidden_state.shape    ,							(self.batch_size, self.seq_length, self.hidden_size)							)




			def        lowerCAmelCase__    ( self    ,							a__    ,							a__    ,							a__    ,							a__    ,							a__    ,							a__							)    ->    Dict:

										'''simple docstring'''




										snake_case_      =				TFEsmForMaskedLM(config=a__							)
										snake_case_      =				model([input_ids, input_mask]							)
										self.parent.assertEqual(result.logits.shape    ,							(self.batch_size, self.seq_length, self.vocab_size)							)




			def        lowerCAmelCase__    ( self    ,							a__    ,							a__    ,							a__    ,							a__    ,							a__    ,							a__							)    ->    Union[str, Any]:

										'''simple docstring'''




										snake_case_      =				self.num_labels
										snake_case_      =				TFEsmForTokenClassification(config=a__							)
										snake_case_      =				{"input_ids": input_ids, "attention_mask": input_mask}
										snake_case_      =				model(a__							)
										self.parent.assertEqual(result.logits.shape    ,							(self.batch_size, self.seq_length, self.num_labels)							)




			def        lowerCAmelCase__    ( self							)    ->    int:

										'''simple docstring'''




										snake_case_      =				self.prepare_config_and_inputs()
										(
										    (
										    snake_case_
										) ,				(
										    snake_case_
										) ,				(
										    snake_case_
										) ,				(
										    snake_case_
										) ,				(
										    snake_case_
										) ,				(
										    snake_case_
										) ,				
										)      =				config_and_inputs
										snake_case_      =				{"input_ids": input_ids, "attention_mask": input_mask}
										return config, inputs_dict




@require_tf
class 			_snake_case		(     lowercase_						,						lowercase_						,						unittest.TestCase							):
			lowerCAmelCase_					:				List[Any]							=   (
			    (
			        TFEsmModel,
			        TFEsmForMaskedLM,
			        TFEsmForSequenceClassification,
			        TFEsmForTokenClassification,
			    )
			    if is_tf_available()
			    else ()
			)
			lowerCAmelCase_					:				Optional[Any]							=   (
			    {
			        "feature-extraction": TFEsmModel,
			        "fill-mask": TFEsmForMaskedLM,
			        "text-classification": TFEsmForSequenceClassification,
			        "token-classification": TFEsmForTokenClassification,
			        "zero-shot": TFEsmForSequenceClassification,
			    }
			    if is_tf_available()
			    else {}
			)
			lowerCAmelCase_					:				str							=   False
			lowerCAmelCase_					:				List[str]							=   False




			def        lowerCAmelCase__    ( self							)    ->    List[Any]:

										'''simple docstring'''




										snake_case_      =				TFEsmModelTester(self							)
										snake_case_      =				ConfigTester(self    ,							config_class=a__    ,							hidden_size=37							)




			def        lowerCAmelCase__    ( self							)    ->    Dict:

										'''simple docstring'''




										self.config_tester.run_common_tests()




			def        lowerCAmelCase__    ( self							)    ->    str:

										'''simple docstring'''




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




			def        lowerCAmelCase__    ( self							)    ->    int:

										'''simple docstring'''




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




			def        lowerCAmelCase__    ( self							)    ->    Dict:

										'''simple docstring'''




										snake_case_      =				self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_masked_lm(*a__							)




			def        lowerCAmelCase__    ( self							)    ->    int:

										'''simple docstring'''




										snake_case_      =				self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_token_classification(*a__							)




			@slow
			def        lowerCAmelCase__    ( self							)    ->    str:

										'''simple docstring'''




										for model_name in TF_ESM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																	snake_case_      =				TFEsmModel.from_pretrained(a__							)
																	self.assertIsNotNone(a__							)




			@unittest.skip("Protein models do not support embedding resizing."							)
			def        lowerCAmelCase__    ( self							)    ->    List[Any]:

										'''simple docstring'''




										pass




			@unittest.skip("Protein models do not support embedding resizing."							)
			def        lowerCAmelCase__    ( self							)    ->    Optional[int]:

										'''simple docstring'''




										pass




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

										'''simple docstring'''




										snake_case_ ,				snake_case_      =				self.model_tester.prepare_config_and_inputs_for_common()

										for model_class in self.all_model_classes:
																	snake_case_      =				model_class(a__							)
																	assert isinstance(model.get_input_embeddings()    ,							tf.keras.layers.Layer							)
																	if model_class is TFEsmForMaskedLM:
																								# Output embedding test differs from the main test because they're a matrix, not a layer
																								snake_case_      =				model.get_bias()
																								assert isinstance(a__    ,							a__							)
																								for k, v in name.items():
																															assert isinstance(a__    ,							tf.Variable							)
																	else:
																								snake_case_      =				model.get_output_embeddings()
																								assert x is None
																								snake_case_      =				model.get_bias()
																								assert name is None




@require_tf
class 			_snake_case		(     unittest.TestCase							):




			@slow
			def        lowerCAmelCase__    ( self							)    ->    Tuple:

										'''simple docstring'''




										snake_case_      =				TFEsmForMaskedLM.from_pretrained("facebook/esm2_t6_8M_UR50D"							)

										snake_case_      =				tf.constant([[0, 1, 2, 3, 4, 5]]							)
										snake_case_      =				model(a__							)[0]
										snake_case_      =				[1, 6, 33]
										self.assertEqual(list(output.numpy().shape							)    ,							a__							)
										# compare the actual values for a slice.
										snake_case_      =				tf.constant(
										    [
										        [
										            [8.9_2_1_5_1_8, -1_0.5_8_9_8_1_4, -6.4_6_7_1_3_0_7],
										            [-6.3_9_6_7_1_5_6, -1_3.9_1_1_3_7_7, -1.1_2_1_1_9_1_5],
										            [-7.7_8_1_2_4_7, -1_3.9_5_1_5_5_7, -3.7_4_0_5_9_2],
										        ]
										    ]							)
										self.assertTrue(numpy.allclose(output[:, :3, :3].numpy()    ,							expected_slice.numpy()    ,							atol=1e-2							)							)




			@slow
			def        lowerCAmelCase__    ( self							)    ->    str:

										'''simple docstring'''




										snake_case_      =				TFEsmModel.from_pretrained("facebook/esm2_t6_8M_UR50D"							)

										snake_case_      =				tf.constant([[0, 6, 4, 13, 5, 4, 16, 12, 11, 7, 2]]							)
										snake_case_      =				model(a__							)[0]
										# compare the actual values for a slice.
										snake_case_      =				tf.constant(
										    [
										        [
										            [0.1_4_4_4_3_0_9_2, 0.5_4_1_2_5_3_2_7, 0.3_2_4_7_7_3_9],
										            [0.3_0_3_4_0_4_8_4, 0.0_0_5_2_6_6_7_6, 0.3_1_0_7_7_7_2_2],
										            [0.3_2_2_7_8_0_4_3, -0.2_4_9_8_7_0_9_6, 0.3_4_1_4_6_2_8],
										        ]
										    ]							)
										self.assertTrue(numpy.allclose(output[:, :3, :3].numpy()    ,							expected_slice.numpy()    ,							atol=1e-4							)							)










'''simple docstring'''





import os

import torch

from ..logging import get_logger
from .constants import FSDP_PYTORCH_VERSION, MODEL_NAME, OPTIMIZER_NAME
from .versions import is_torch_version


if is_torch_version(">=", FSDP_PYTORCH_VERSION):
		import torch.distributed.checkpoint as dist_cp
		from torch.distributed.checkpoint.default_planner import DefaultLoadPlanner, DefaultSavePlanner
		from torch.distributed.checkpoint.optimizer import load_sharded_optimizer_state_dict
		from torch.distributed.fsdp.fully_sharded_data_parallel import FullyShardedDataParallel as FSDP
		from torch.distributed.fsdp.fully_sharded_data_parallel import StateDictType


_SCREAMING_SNAKE_CASE							:       Tuple						=			get_logger(__name__)


def 					UpperCamelCase_(     snake_case							:	Optional[Any]							,    snake_case							:	Optional[Any]							,    snake_case							:	Optional[Any]							,    snake_case							:	int							,    snake_case							:	List[Any]=0					):

							'''simple docstring'''






							os.makedirs(snake_case							,    exist_ok=snake_case					)
							with FSDP.state_dict_type(
							    snake_case							,    fsdp_plugin.state_dict_type							,    fsdp_plugin.state_dict_config							,    fsdp_plugin.optim_state_dict_config					):
														snake_case_      =				model.state_dict()
														if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT:
																					snake_case_      =				f'{MODEL_NAME}.bin' if model_index == 0 else f'{MODEL_NAME}_{model_index}.bin'
																					snake_case_      =				os.path.join(snake_case							,    snake_case					)
																					if accelerator.process_index == 0:
																												logger.info(f'Saving model to {output_model_file}'					)
																												torch.save(snake_case							,    snake_case					)
																												logger.info(f'Model saved to {output_model_file}'					)
														elif fsdp_plugin.state_dict_type == StateDictType.LOCAL_STATE_DICT:
																					snake_case_      =				(
																					    f'{MODEL_NAME}_rank{accelerator.process_index}.bin'
																					    if model_index == 0
																					    else f'{MODEL_NAME}_{model_index}_rank{accelerator.process_index}.bin'
																					)
																					snake_case_      =				os.path.join(snake_case							,    snake_case					)
																					logger.info(f'Saving model to {output_model_file}'					)
																					torch.save(snake_case							,    snake_case					)
																					logger.info(f'Model saved to {output_model_file}'					)
														elif fsdp_plugin.state_dict_type == StateDictType.SHARDED_STATE_DICT:
																					snake_case_      =				os.path.join(snake_case							,    f'{MODEL_NAME}_{model_index}'					)
																					os.makedirs(snake_case							,    exist_ok=snake_case					)
																					logger.info(f'Saving model to {ckpt_dir}'					)
																					snake_case_      =				{"model": state_dict}

																					dist_cp.save_state_dict(
																					    state_dict=snake_case							,    storage_writer=dist_cp.FileSystemWriter(snake_case					)							,    planner=DefaultSavePlanner()							,    )
																					logger.info(f'Model saved to {ckpt_dir}'					)


def 					UpperCamelCase_(     snake_case							:	Optional[int]							,    snake_case							:	Optional[Any]							,    snake_case							:	int							,    snake_case							:	Union[str, Any]							,    snake_case							:	Any=0					):

							'''simple docstring'''






							accelerator.wait_for_everyone()
							with FSDP.state_dict_type(
							    snake_case							,    fsdp_plugin.state_dict_type							,    fsdp_plugin.state_dict_config							,    fsdp_plugin.optim_state_dict_config					):
														if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT:
																					if type(snake_case					) != FSDP and accelerator.process_index != 0:
																												if not fsdp_plugin.sync_module_states:
																																			raise ValueError(
																																			    "Set the `sync_module_states` flag to `True` so that model states are synced across processes when "
																																			    "initializing FSDP object"					)
																												return
																					snake_case_      =				f'{MODEL_NAME}.bin' if model_index == 0 else f'{MODEL_NAME}_{model_index}.bin'
																					snake_case_      =				os.path.join(snake_case							,    snake_case					)
																					logger.info(f'Loading model from {input_model_file}'					)
																					snake_case_      =				torch.load(snake_case					)
																					logger.info(f'Model loaded from {input_model_file}'					)
														elif fsdp_plugin.state_dict_type == StateDictType.LOCAL_STATE_DICT:
																					snake_case_      =				(
																					    f'{MODEL_NAME}_rank{accelerator.process_index}.bin'
																					    if model_index == 0
																					    else f'{MODEL_NAME}_{model_index}_rank{accelerator.process_index}.bin'
																					)
																					snake_case_      =				os.path.join(snake_case							,    snake_case					)
																					logger.info(f'Loading model from {input_model_file}'					)
																					snake_case_      =				torch.load(snake_case					)
																					logger.info(f'Model loaded from {input_model_file}'					)
														elif fsdp_plugin.state_dict_type == StateDictType.SHARDED_STATE_DICT:
																					snake_case_      =				(
																					    os.path.join(snake_case							,    f'{MODEL_NAME}_{model_index}'					)
																					    if f'{MODEL_NAME}' not in input_dir
																					    else input_dir
																					)
																					logger.info(f'Loading model from {ckpt_dir}'					)
																					snake_case_      =				{"model": model.state_dict()}
																					dist_cp.load_state_dict(
																					    state_dict=snake_case							,    storage_reader=dist_cp.FileSystemReader(snake_case					)							,    planner=DefaultLoadPlanner()							,    )
																					snake_case_      =				state_dict["model"]
																					logger.info(f'Model loaded from {ckpt_dir}'					)
														model.load_state_dict(snake_case					)


def 					UpperCamelCase_(     snake_case							:	str							,    snake_case							:	List[str]							,    snake_case							:	Any							,    snake_case							:	Tuple							,    snake_case							:	Optional[Any]							,    snake_case							:	Tuple=0					):

							'''simple docstring'''






							os.makedirs(snake_case							,    exist_ok=snake_case					)
							with FSDP.state_dict_type(
							    snake_case							,    fsdp_plugin.state_dict_type							,    fsdp_plugin.state_dict_config							,    fsdp_plugin.optim_state_dict_config					):
														snake_case_      =				FSDP.optim_state_dict(snake_case							,    snake_case					)
														if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT:
																					if accelerator.process_index == 0:
																												snake_case_      =				(
																												    f'{OPTIMIZER_NAME}.bin' if optimizer_index == 0 else f'{OPTIMIZER_NAME}_{optimizer_index}.bin'
																												)
																												snake_case_      =				os.path.join(snake_case							,    snake_case					)
																												logger.info(f'Saving Optimizer state to {output_optimizer_file}'					)
																												torch.save(snake_case							,    snake_case					)
																												logger.info(f'Optimizer state saved in {output_optimizer_file}'					)
														else:
																					snake_case_      =				os.path.join(snake_case							,    f'{OPTIMIZER_NAME}_{optimizer_index}'					)
																					os.makedirs(snake_case							,    exist_ok=snake_case					)
																					logger.info(f'Saving Optimizer state to {ckpt_dir}'					)
																					dist_cp.save_state_dict(
																					    state_dict={"optimizer": optim_state}							,    storage_writer=dist_cp.FileSystemWriter(snake_case					)							,    planner=DefaultSavePlanner()							,    )
																					logger.info(f'Optimizer state saved in {ckpt_dir}'					)




def 					UpperCamelCase_(     snake_case							:	Optional[Any]							,    snake_case							:	List[str]							,    snake_case							:	Union[str, Any]							,    snake_case							:	int							,    snake_case							:	Optional[int]							,    snake_case							:	Union[str, Any]=0					):

							'''simple docstring'''






							accelerator.wait_for_everyone()
							with FSDP.state_dict_type(
							    snake_case							,    fsdp_plugin.state_dict_type							,    fsdp_plugin.state_dict_config							,    fsdp_plugin.optim_state_dict_config					):
														if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT:
																					snake_case_      =				None
																					# below check should work but currently it isn't working (mostly opytorch issue),
																					# in the meantime disabling it at the cost of excess memory usage
																					# if accelerator.process_index == 0 or not fsdp_plugin.optim_state_dict_config.rank0_only:
																					snake_case_      =				(
																					    f'{OPTIMIZER_NAME}.bin' if optimizer_index == 0 else f'{OPTIMIZER_NAME}_{optimizer_index}.bin'
																					)
																					snake_case_      =				os.path.join(snake_case							,    snake_case					)
																					logger.info(f'Loading Optimizer state from {input_optimizer_file}'					)
																					snake_case_      =				torch.load(snake_case					)
																					logger.info(f'Optimizer state loaded from {input_optimizer_file}'					)
														else:
																					snake_case_      =				(
																					    os.path.join(snake_case							,    f'{OPTIMIZER_NAME}_{optimizer_index}'					)
																					    if f'{OPTIMIZER_NAME}' not in input_dir
																					    else input_dir
																					)
																					logger.info(f'Loading Optimizer from {ckpt_dir}'					)
																					snake_case_      =				load_sharded_optimizer_state_dict(
																					    model_state_dict=model.state_dict()							,    optimizer_key="optimizer"							,    storage_reader=dist_cp.FileSystemReader(snake_case					)							,    )
																					snake_case_      =				optim_state["optimizer"]
																					logger.info(f'Optimizer loaded from {ckpt_dir}'					)
														snake_case_      =				FSDP.optim_state_dict_to_load(snake_case							,    snake_case							,    snake_case					)
														optimizer.load_state_dict(snake_case					)




