




import unittest

from transformers import EsmConfig, is_torch_available
from transformers.testing_utils import TestCasePlus, require_torch, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
							import torch

							from transformers import EsmForMaskedLM, EsmForSequenceClassification, EsmForTokenClassification, EsmModel
							from transformers.models.esm.modeling_esm import (
							    ESM_PRETRAINED_MODEL_ARCHIVE_LIST,
							    EsmEmbeddings,
							    create_position_ids_from_input_ids,
							)




class 		__A      :

						def __init__(		self   :List[str]    , __snake_case   :Tuple    , __snake_case   :List[Any]=13    , __snake_case   :List[Any]=7    , __snake_case   :List[Any]=False    , __snake_case   :List[Any]=True    , __snake_case   :Union[str, Any]=False    , __snake_case   :List[str]=True    , __snake_case   :Any=33    , __snake_case   :Any=32    , __snake_case   :int=5    , __snake_case   :List[str]=4    , __snake_case   :int=37    , __snake_case   :Dict="gelu"    , __snake_case   :int=0.1    , __snake_case   :Optional[Any]=0.1    , __snake_case   :List[Any]=5_12    , __snake_case   :Any=16    , __snake_case   :str=2    , __snake_case   :Dict=0.02    , __snake_case   :Any=3    , __snake_case   :int=4    , __snake_case   :Optional[int]=None    , ):
										'''simple docstring'''

										__magic_name__	:	Dict								=parent
										__magic_name__	:	int								=batch_size
										__magic_name__	:	Tuple								=seq_length
										__magic_name__	:	List[Any]								=is_training
										__magic_name__	:	Tuple								=use_input_mask
										__magic_name__	:	Dict								=use_token_type_ids
										__magic_name__	:	Optional[int]								=use_labels
										__magic_name__	:	List[Any]								=vocab_size
										__magic_name__	:	Optional[int]								=hidden_size
										__magic_name__	:	List[Any]								=num_hidden_layers
										__magic_name__	:	Optional[Any]								=num_attention_heads
										__magic_name__	:	List[str]								=intermediate_size
										__magic_name__	:	str								=hidden_act
										__magic_name__	:	List[str]								=hidden_dropout_prob
										__magic_name__	:	str								=attention_probs_dropout_prob
										__magic_name__	:	Tuple								=max_position_embeddings
										__magic_name__	:	List[str]								=type_vocab_size
										__magic_name__	:	Optional[int]								=type_sequence_label_size
										__magic_name__	:	Optional[int]								=initializer_range
										__magic_name__	:	Optional[int]								=num_labels
										__magic_name__	:	List[Any]								=num_choices
										__magic_name__	:	Tuple								=scope

						def     A__						(		self   :Any ):
										'''simple docstring'''

										__magic_name__	:	Optional[int]								=ids_tensor([self.batch_size, self.seq_length]    , self.vocab_size )

										__magic_name__	:	Optional[Any]								=None
										if self.use_input_mask:
														__magic_name__	:	Any								=random_attention_mask([self.batch_size, self.seq_length] )

										__magic_name__	:	str								=None
										__magic_name__	:	Dict								=None
										__magic_name__	:	Union[str, Any]								=None
										if self.use_labels:
														__magic_name__	:	int								=ids_tensor([self.batch_size]    , self.type_sequence_label_size )
														__magic_name__	:	str								=ids_tensor([self.batch_size, self.seq_length]    , self.num_labels )
														__magic_name__	:	List[Any]								=ids_tensor([self.batch_size]    , self.num_choices )

										__magic_name__	:	Any								=self.get_config()

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

						def     A__						(		self   :Any ):
										'''simple docstring'''

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

						def     A__						(		self   :Optional[Any]    , __snake_case   :Optional[Any]    , __snake_case   :Any    , __snake_case   :List[Any]    , __snake_case   :int    , __snake_case   :Union[str, Any]    , __snake_case   :int ):
										'''simple docstring'''

										__magic_name__	:	str								=EsmModel(config=__snake_case )
										model.to(__snake_case )
										model.eval()
										__magic_name__	:	List[str]								=model(__snake_case    , attention_mask=__snake_case )
										__magic_name__	:	Tuple								=model(__snake_case )
										__magic_name__	:	Optional[int]								=model(__snake_case )

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

						def     A__						(		self   :Optional[Any]    , __snake_case   :Union[str, Any]    , __snake_case   :int    , __snake_case   :int    , __snake_case   :str    , __snake_case   :Any    , __snake_case   :Dict ):
										'''simple docstring'''

										__magic_name__	:	Optional[int]								=EsmForMaskedLM(config=__snake_case )
										model.to(__snake_case )
										model.eval()
										__magic_name__	:	Union[str, Any]								=model(__snake_case    , attention_mask=__snake_case    , labels=__snake_case )
										self.parent.assertEqual(result.logits.shape    , (self.batch_size, self.seq_length, self.vocab_size) )

						def     A__						(		self   :Any    , __snake_case   :Any    , __snake_case   :Dict    , __snake_case   :Dict    , __snake_case   :Union[str, Any]    , __snake_case   :Union[str, Any]    , __snake_case   :List[Any] ):
										'''simple docstring'''

										__magic_name__	:	Union[str, Any]								=self.num_labels
										__magic_name__	:	List[str]								=EsmForTokenClassification(config=__snake_case )
										model.to(__snake_case )
										model.eval()
										__magic_name__	:	List[str]								=model(__snake_case    , attention_mask=__snake_case    , labels=__snake_case )
										self.parent.assertEqual(result.logits.shape    , (self.batch_size, self.seq_length, self.num_labels) )


						def     A__						(		self   :str ):
										'''simple docstring'''

										__magic_name__	:	List[Any]								=self.prepare_config_and_inputs()
										(
										    (
										    __magic_name__
										)				, (
										    __magic_name__
										)				, (
										    __magic_name__
										)				, (
										    __magic_name__
										)				, (
										    __magic_name__
										)				, (
										    __magic_name__
										)				, 
										)	:	List[str]								=config_and_inputs
										__magic_name__	:	List[str]								={"""input_ids""": input_ids, """attention_mask""": input_mask}
										return config, inputs_dict




@require_torch
class 		__A      (			UpperCamelCase__					,						UpperCamelCase__					,						unittest.TestCase			):
						UpperCamelCase     						=					False

						UpperCamelCase     						=					(
						    (
						        EsmForMaskedLM,
						        EsmModel,
						        EsmForSequenceClassification,
						        EsmForTokenClassification,
						    )
						    if is_torch_available()
						    else ()
						)
						UpperCamelCase     						=					()
						UpperCamelCase     						=					(
						    {
						        """feature-extraction""": EsmModel,
						        """fill-mask""": EsmForMaskedLM,
						        """text-classification""": EsmForSequenceClassification,
						        """token-classification""": EsmForTokenClassification,
						        """zero-shot""": EsmForSequenceClassification,
						    }
						    if is_torch_available()
						    else {}
						)
						UpperCamelCase     						=					True

						def     A__						(		self   :Optional[Any] ):
										'''simple docstring'''

										__magic_name__	:	List[Any]								=EsmModelTester(self )
										__magic_name__	:	Any								=ConfigTester(self    , config_class=__snake_case    , hidden_size=37 )

						def     A__						(		self   :int ):
										'''simple docstring'''

										self.config_tester.run_common_tests()

						def     A__						(		self   :Any ):
										'''simple docstring'''

										__magic_name__	:	str								=self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_model(*__snake_case )

						def     A__						(		self   :List[str] ):
										'''simple docstring'''

										__magic_name__	:	str								=self.model_tester.prepare_config_and_inputs()
										for type in ["absolute", "relative_key", "relative_key_query"]:
														__magic_name__	:	str								=type
														self.model_tester.create_and_check_model(*__snake_case )

						def     A__						(		self   :Optional[int] ):
										'''simple docstring'''

										__magic_name__	:	Optional[int]								=self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_masked_lm(*__snake_case )

						def     A__						(		self   :List[Any] ):
										'''simple docstring'''

										__magic_name__	:	List[str]								=self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_token_classification(*__snake_case )

						@slow
						def     A__						(		self   :Dict ):
										'''simple docstring'''

										for model_name in ESM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
														__magic_name__	:	str								=EsmModel.from_pretrained(__snake_case )
														self.assertIsNotNone(__snake_case )

						def     A__						(		self   :int ):
										'''simple docstring'''

										__magic_name__	:	Union[str, Any]								=self.model_tester.prepare_config_and_inputs()[0]
										__magic_name__	:	Dict								=EsmEmbeddings(config=__snake_case )

										__magic_name__	:	int								=torch.as_tensor([[12, 31, 13, model.padding_idx]] )
										__magic_name__	:	Optional[int]								=torch.as_tensor(
										    [
										        [
										            0 + model.padding_idx + 1,
										            1 + model.padding_idx + 1,
										            2 + model.padding_idx + 1,
										            model.padding_idx,
										        ]
										    ] )
										__magic_name__	:	Union[str, Any]								=create_position_ids_from_input_ids(__snake_case    , model.padding_idx )
										self.assertEqual(position_ids.shape    , expected_positions.shape )
										self.assertTrue(torch.all(torch.eq(__snake_case    , __snake_case ) ) )

						def     A__						(		self   :Optional[int] ):
										'''simple docstring'''

										__magic_name__	:	Any								=self.model_tester.prepare_config_and_inputs()[0]
										__magic_name__	:	Tuple								=EsmEmbeddings(config=__snake_case )

										__magic_name__	:	Dict								=torch.empty(2    , 4    , 30 )
										__magic_name__	:	List[str]								=[
										    0 + embeddings.padding_idx + 1,
										    1 + embeddings.padding_idx + 1,
										    2 + embeddings.padding_idx + 1,
										    3 + embeddings.padding_idx + 1,
										]
										__magic_name__	:	List[Any]								=torch.as_tensor([expected_single_positions, expected_single_positions] )
										__magic_name__	:	Any								=embeddings.create_position_ids_from_inputs_embeds(__snake_case )
										self.assertEqual(position_ids.shape    , expected_positions.shape )
										self.assertTrue(torch.all(torch.eq(__snake_case    , __snake_case ) ) )

						@unittest.skip("""Esm does not support embedding resizing""" )
						def     A__						(		self   :List[Any] ):
										'''simple docstring'''

										pass

						@unittest.skip("""Esm does not support embedding resizing""" )
						def     A__						(		self   :Any ):
										'''simple docstring'''

										pass


						@unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" )
						def     A__						(		self   :Dict ):
										'''simple docstring'''

										pass




@require_torch
class 		__A      (			UpperCamelCase__			):

						@slow
						def     A__						(		self   :List[Any] ):
										'''simple docstring'''

										with torch.no_grad():
														__magic_name__	:	Any								=EsmForMaskedLM.from_pretrained("""facebook/esm2_t6_8M_UR50D""" )
														model.eval()
														__magic_name__	:	List[str]								=torch.tensor([[0, 1, 2, 3, 4, 5]] )
														__magic_name__	:	List[Any]								=model(__snake_case )[0]

														__magic_name__	:	Dict								=33

														__magic_name__	:	Optional[Any]								=torch.Size((1, 6, vocab_size) )
														self.assertEqual(output.shape    , __snake_case )

														__magic_name__	:	Optional[Any]								=torch.tensor(
														    [[[8.9215, -10.5898, -6.4671], [-6.3967, -13.9114, -1.1212], [-7.7812, -13.9516, -3.7406]]] )
														self.assertTrue(torch.allclose(output[:, :3, :3]    , __snake_case    , atol=1E-4 ) )


						@slow
						def     A__						(		self   :Dict ):
										'''simple docstring'''

										with torch.no_grad():
														__magic_name__	:	Union[str, Any]								=EsmModel.from_pretrained("""facebook/esm2_t6_8M_UR50D""" )
														model.eval()

														__magic_name__	:	int								=torch.tensor([[0, 6, 4, 13, 5, 4, 16, 12, 11, 7, 2]] )
														__magic_name__	:	int								=model(__snake_case )[0]
														# compare the actual values for a slice.
														__magic_name__	:	Any								=torch.tensor(
														    [[[0.1444, 0.5413, 0.3248], [0.3034, 0.0053, 0.3108], [0.3228, -0.2499, 0.3415]]] )
														self.assertTrue(torch.allclose(output[:, :3, :3]    , __snake_case    , atol=1E-4 ) )










import logging
import os
from dataclasses import dataclass, field
from typing import Dict, Optional

import datasets
import numpy as np
import tensorflow as tf

from transformers import (
    AutoConfig,
    AutoTokenizer,
    EvalPrediction,
    HfArgumentParser,
    PreTrainedTokenizer,
    TFAutoModelForSequenceClassification,
    TFTrainer,
    TFTrainingArguments,
)
from transformers.utils import logging as hf_logging


hf_logging.set_verbosity_info()
hf_logging.enable_default_handler()
hf_logging.enable_explicit_format()




def 		lowerCAmelCase_   (	lowerCamelCase	,     lowerCamelCase	,     lowerCamelCase	,     lowerCamelCase	,     lowerCamelCase	,     lowerCamelCase = None	,     ):
				__magic_name__	:	Optional[int]								={}

				if train_file is not None:
								__magic_name__	:	Optional[int]								=[train_file]
				if eval_file is not None:
								__magic_name__	:	Any								=[eval_file]
				if test_file is not None:
								__magic_name__	:	int								=[test_file]

				__magic_name__	:	Any								=datasets.load_dataset("""csv"""	,     data_files=lowerCamelCase   )
				__magic_name__	:	Optional[Any]								=list(ds[list(files.keys()   )[0]].features.keys()   )
				__magic_name__	:	Optional[Any]								=features_name.pop(lowerCamelCase   )
				__magic_name__	:	str								=list(set(ds[list(files.keys()   )[0]][label_name]   )   )
				__magic_name__	:	Union[str, Any]								={label: i for i, label in enumerate(lowerCamelCase   )}
				__magic_name__	:	Dict								=tokenizer.model_input_names
				__magic_name__	:	Any								={}

				if len(lowerCamelCase   ) == 1:
								for k in files.keys():
												__magic_name__	:	Dict								=ds[k].map(
												    lambda lowerCamelCase   : tokenizer.batch_encode_plus(
												        example[features_name[0]]	,     truncation=lowerCamelCase	,     max_length=lowerCamelCase	,     padding="""max_length"""   )	,     batched=lowerCamelCase	,     )
				elif len(lowerCamelCase   ) == 2:
								for k in files.keys():
												__magic_name__	:	Optional[Any]								=ds[k].map(
												    lambda lowerCamelCase   : tokenizer.batch_encode_plus(
												        (example[features_name[0]], example[features_name[1]])	,     truncation=lowerCamelCase	,     max_length=lowerCamelCase	,     padding="""max_length"""	,     )	,     batched=lowerCamelCase	,     )

				def gen_train():
								for ex in transformed_ds[datasets.Split.TRAIN]:
												__magic_name__	:	Any								={k: v for k, v in ex.items() if k in input_names}
												__magic_name__	:	Any								=labelaid[ex[label_name]]
												yield (d, label)

				def gen_val():
								for ex in transformed_ds[datasets.Split.VALIDATION]:
												__magic_name__	:	Dict								={k: v for k, v in ex.items() if k in input_names}
												__magic_name__	:	str								=labelaid[ex[label_name]]
												yield (d, label)

				def gen_test():
								for ex in transformed_ds[datasets.Split.TEST]:
												__magic_name__	:	Union[str, Any]								={k: v for k, v in ex.items() if k in input_names}
												__magic_name__	:	Optional[int]								=labelaid[ex[label_name]]
												yield (d, label)

				__magic_name__	:	Union[str, Any]								=(
				    tf.data.Dataset.from_generator(
				        lowerCamelCase	,     ({k: tf.intaa for k in input_names}, tf.intaa)	,     ({k: tf.TensorShape([None]   ) for k in input_names}, tf.TensorShape([]   ))	,     )
				    if datasets.Split.TRAIN in transformed_ds
				    else None
				)

				if train_ds is not None:
								__magic_name__	:	Optional[Any]								=train_ds.apply(tf.data.experimental.assert_cardinality(len(ds[datasets.Split.TRAIN]   )   )   )

				__magic_name__	:	Optional[Any]								=(
				    tf.data.Dataset.from_generator(
				        lowerCamelCase	,     ({k: tf.intaa for k in input_names}, tf.intaa)	,     ({k: tf.TensorShape([None]   ) for k in input_names}, tf.TensorShape([]   ))	,     )
				    if datasets.Split.VALIDATION in transformed_ds
				    else None
				)

				if val_ds is not None:
								__magic_name__	:	Any								=val_ds.apply(tf.data.experimental.assert_cardinality(len(ds[datasets.Split.VALIDATION]   )   )   )

				__magic_name__	:	Any								=(
				    tf.data.Dataset.from_generator(
				        lowerCamelCase	,     ({k: tf.intaa for k in input_names}, tf.intaa)	,     ({k: tf.TensorShape([None]   ) for k in input_names}, tf.TensorShape([]   ))	,     )
				    if datasets.Split.TEST in transformed_ds
				    else None
				)

				if test_ds is not None:
								__magic_name__	:	Optional[int]								=test_ds.apply(tf.data.experimental.assert_cardinality(len(ds[datasets.Split.TEST]   )   )   )

				return train_ds, val_ds, test_ds, labelaid


UpperCAmelCase_		:				int									=     logging.getLogger(__name__)




@dataclass
class 		__A      :
						UpperCamelCase     						=					field(metadata={"""help""": """Which column contains the label"""}			)
						UpperCamelCase     						=					field(default=UpperCamelCase__					,						metadata={"""help""": """The path of the training file"""}			)
						UpperCamelCase     						=					field(default=UpperCamelCase__					,						metadata={"""help""": """The path of the development file"""}			)
						UpperCamelCase     						=					field(default=UpperCamelCase__					,						metadata={"""help""": """The path of the test file"""}			)
						UpperCamelCase     						=					field(
						    default=128					,						metadata={
						        """help""": (
						            """The maximum total input sequence length after tokenization. Sequences longer """
						            """than this will be truncated, sequences shorter will be padded."""
						        )
						    }					,						)
						UpperCamelCase     						=					field(
						    default=UpperCamelCase__					,						metadata={"""help""": """Overwrite the cached training and evaluation sets"""}			)




@dataclass
class 		__A      :
						UpperCamelCase     						=					field(
						    metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""}			)
						UpperCamelCase     						=					field(
						    default=UpperCamelCase__					,						metadata={"""help""": """Pretrained config name or path if not the same as model_name"""}			)
						UpperCamelCase     						=					field(
						    default=UpperCamelCase__					,						metadata={"""help""": """Pretrained tokenizer name or path if not the same as model_name"""}			)
						UpperCamelCase     						=					field(default=UpperCamelCase__					,						metadata={"""help""": """Set this flag to use fast tokenization."""}			)
						# If you want to tweak more attributes on your tokenizer, you should do it in a distinct script,
						# or just modify its tokenizer_config.json.
						UpperCamelCase     						=					field(
						    default=UpperCamelCase__					,						metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""}					,						)




def 		lowerCAmelCase_   (	):
				# See all possible arguments in src/transformers/training_args.py
				# or by passing the --help flag to this script.
				# We now keep distinct sets of args, for a cleaner separation of concerns.
				__magic_name__	:	List[Any]								=HfArgumentParser((ModelArguments, DataTrainingArguments, TFTrainingArguments)   )
				__magic_name__				, __magic_name__				, __magic_name__	:	Union[str, Any]								=parser.parse_args_into_dataclasses()

				if (
				    os.path.exists(training_args.output_dir   )
				    and os.listdir(training_args.output_dir   )
				    and training_args.do_train
				    and not training_args.overwrite_output_dir
				):
								raise ValueError(
								    F"Output directory ({training_args.output_dir}) already exists and is not empty. Use"
								    """ --overwrite_output_dir to overcome."""   )

				# Setup logging
				logging.basicConfig(
				    format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s"""	,     datefmt="""%m/%d/%Y %H:%M:%S"""	,     level=logging.INFO	,     )
				logger.info(
				    F"n_replicas: {training_args.n_replicas}, distributed training: {bool(training_args.n_replicas > 1   )}, "
				    F"16-bits training: {training_args.fpaa}"   )
				logger.info(F"Training/evaluation parameters {training_args}"   )

				# Load pretrained model and tokenizer
				#
				# Distributed training:
				# The .from_pretrained methods guarantee that only one local process can concurrently
				# download model & vocab.

				__magic_name__	:	Dict								=AutoTokenizer.from_pretrained(
				    model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path	,     cache_dir=model_args.cache_dir	,     )

				__magic_name__				, __magic_name__				, __magic_name__				, __magic_name__	:	Optional[Any]								=get_tfds(
				    train_file=data_args.train_file	,     eval_file=data_args.dev_file	,     test_file=data_args.test_file	,     tokenizer=lowerCamelCase	,     label_column_id=data_args.label_column_id	,     max_seq_length=data_args.max_seq_length	,     )

				__magic_name__	:	Any								=AutoConfig.from_pretrained(
				    model_args.config_name if model_args.config_name else model_args.model_name_or_path	,     num_labels=len(lowerCamelCase   )	,     labelaid=lowerCamelCase	,     idalabel={id: label for label, id in labelaid.items()}	,     finetuning_task="""text-classification"""	,     cache_dir=model_args.cache_dir	,     )

				with training_args.strategy.scope():
								__magic_name__	:	Any								=TFAutoModelForSequenceClassification.from_pretrained(
								    model_args.model_name_or_path	,     from_pt=bool(""".bin""" in model_args.model_name_or_path   )	,     config=lowerCamelCase	,     cache_dir=model_args.cache_dir	,     )

				def compute_metrics(lowerCamelCase   ) -> Dict:
								__magic_name__	:	Tuple								=np.argmax(p.predictions	,     axis=1   )

								return {"acc": (preds == p.label_ids).mean()}

				# Initialize our Trainer
				__magic_name__	:	int								=TFTrainer(
				    model=lowerCamelCase	,     args=lowerCamelCase	,     train_dataset=lowerCamelCase	,     eval_dataset=lowerCamelCase	,     compute_metrics=lowerCamelCase	,     )

				# Training
				if training_args.do_train:
								trainer.train()
								trainer.save_model()
								tokenizer.save_pretrained(training_args.output_dir   )

				# Evaluation
				__magic_name__	:	List[str]								={}
				if training_args.do_eval:
								logger.info("""*** Evaluate ***"""   )
								__magic_name__	:	List[str]								=trainer.evaluate()
								__magic_name__	:	Optional[Any]								=os.path.join(training_args.output_dir	,     """eval_results.txt"""   )

								with open(lowerCamelCase	,     """w"""   ) as writer:
												logger.info("""***** Eval results *****"""   )

												for key, value in result.items():
																logger.info(F"  {key} = {value}"   )
																writer.write(F"{key} = {value}\n"   )

												results.update(lowerCamelCase   )

				return results


if __name__ == "__main__":
							main()




