
"""simple docstring"""


import torch
from torch import nn
from torch.nn import CrossEntropyLoss, MSELoss

from ....modeling_outputs import BaseModelOutputWithPooling, SequenceClassifierOutput
from ....modeling_utils import ModuleUtilsMixin
from ....utils import add_start_docstrings, add_start_docstrings_to_model_forward, logging, replace_return_docstrings


__A 		= logging.get_logger(__name__)

__A 		= 'MMBTConfig'







class 	lowerCamelCase__      (      nn.Module       ):





   '''simple docstring'''



   def __init__(							self  ,  __UpperCAmelCase  ,  __UpperCAmelCase  ,  __UpperCAmelCase						)				->  Any:
    super().__init__()
    _lowerCAmelCase			=config
    _lowerCAmelCase			=encoder
    _lowerCAmelCase			=nn.Linear(config.modal_hidden_size  ,  config.hidden_size						)
    _lowerCAmelCase			=embeddings.position_embeddings
    _lowerCAmelCase			=embeddings.token_type_embeddings
    _lowerCAmelCase			=embeddings.word_embeddings
    _lowerCAmelCase			=embeddings.LayerNorm
    _lowerCAmelCase			=nn.Dropout(p=config.hidden_dropout_prob						)



   def       _lowerCAmelCase	(							self  ,  __UpperCAmelCase  ,  __UpperCAmelCase=None  ,  __UpperCAmelCase=None  ,  __UpperCAmelCase=None  ,  __UpperCAmelCase=None						)				->  List[Any]:
    _lowerCAmelCase			=self.proj_embeddings(self.encoder(lowercase_						)						)
    _lowerCAmelCase			=token_embeddings.size(1						)

    if start_token is not None:
     _lowerCAmelCase			=self.word_embeddings(lowercase_						)
     seq_length += 1
     _lowerCAmelCase			=torch.cat([start_token_embeds.unsqueeze(1						), token_embeddings]  ,  dim=1						)

    if end_token is not None:
     _lowerCAmelCase			=self.word_embeddings(lowercase_						)
     seq_length += 1
     _lowerCAmelCase			=torch.cat([token_embeddings, end_token_embeds.unsqueeze(1						)]  ,  dim=1						)

    if position_ids is None:
     _lowerCAmelCase			=torch.arange(lowercase_  ,  dtype=torch.long  ,  device=input_modal.device						)
     _lowerCAmelCase			=position_ids.unsqueeze(0						).expand(input_modal.size(0						)  ,  lowercase_						)

    if token_type_ids is None:
     _lowerCAmelCase			=torch.zeros(
         (input_modal.size(0						), seq_length)  ,  dtype=torch.long  ,  device=input_modal.device						)

    _lowerCAmelCase			=self.position_embeddings(lowercase_						)
    _lowerCAmelCase			=self.token_type_embeddings(lowercase_						)
    _lowerCAmelCase			=token_embeddings + position_embeddings + token_type_embeddings
    _lowerCAmelCase			=self.LayerNorm(lowercase_						)
    _lowerCAmelCase			=self.dropout(lowercase_						)
    return embeddings







__A 		= r'\n    MMBT model was proposed in [Supervised Multimodal Bitransformers for Classifying Images and\n    Text](https://github.com/facebookresearch/mmbt) by Douwe Kiela, Suvrat Bhooshan, Hamed Firooz, Davide Testuggine.\n    It\'s a supervised multimodal bitransformer model that fuses information from text and other image encoders, and\n    obtain state-of-the-art performance on various multimodal classification benchmark tasks.\n\n    This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the\n    library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads\n    etc.)\n\n    This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.\n    Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage\n    and behavior.\n\n    Parameters:\n        config ([`MMBTConfig`]): Model configuration class with all the parameters of the model.\n            Initializing with a config file does not load the weights associated with the model, only the\n            configuration.\n        transformer (`nn.Module`): A text transformer that is used by MMBT.\n            It should have embeddings, encoder, and pooler attributes.\n        encoder (`nn.Module`): Encoder for the second modality.\n            It should take in a batch of modal inputs and return k, n dimension embeddings.\n'

__A 		= r'\n    Args:\n        input_modal (`torch.FloatTensor` of shape `(batch_size, ***)`):\n            The other modality data. It will be the shape that the encoder for that type expects. e.g. With an Image\n            Encoder, the shape would be (batch_size, channels, height, width)\n        input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):\n            Indices of input sequence tokens in the vocabulary. It does not expect [CLS] token to be added as it\'s\n            appended to the end of other modality embeddings. Indices can be obtained using [`AutoTokenizer`]. See\n            [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details.\n\n            [What are input IDs?](../glossary#input-ids)\n        modal_start_tokens (`torch.LongTensor` of shape `(batch_size,)`, *optional*):\n            Optional start token to be added to Other Modality Embedding. [CLS] Most commonly used for classification\n            tasks.\n        modal_end_tokens (`torch.LongTensor` of shape `(batch_size,)`, *optional*):\n            Optional end token to be added to Other Modality Embedding. [SEP] Most commonly used.\n        attention_mask (*optional*) `torch.FloatTensor` of shape `(batch_size, sequence_length)`:\n            Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:\n\n            - 1 for tokens that are **not masked**,\n            - 0 for tokens that are **masked**.\n\n            [What are attention masks?](../glossary#attention-mask)\n        token_type_ids (*optional*) `torch.LongTensor` of shape `(batch_size, sequence_length)`:\n            Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,\n            1]`:\n\n            - 0 corresponds to a *sentence A* token,\n            - 1 corresponds to a *sentence B* token.\n\n            [What are token type IDs?](../glossary#token-type-ids)\n        modal_token_type_ids (*optional*) `torch.LongTensor` of shape `(batch_size, modal_sequence_length)`:\n            Segment token indices to indicate different portions of the non-text modality. The embeddings from these\n            tokens will be summed with the respective token embeddings for the non-text modality.\n        position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):\n            Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,\n            config.max_position_embeddings - 1]`.\n\n            [What are position IDs?](../glossary#position-ids)\n        modal_position_ids (`torch.LongTensor` of shape `(batch_size, modal_sequence_length)`, *optional*):\n            Indices of positions of each input sequence tokens in the position embeddings for the non-text modality.\n            Selected in the range `[0, config.max_position_embeddings - 1]`.\n\n            [What are position IDs?](../glossary#position-ids)\n        head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):\n            Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:\n\n            - 1 indicates the head is **not masked**,\n            - 0 indicates the head is **masked**.\n\n        inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, embedding_dim)`, *optional*):\n            Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This\n            is useful if you want more control over how to convert `input_ids` indices into associated vectors than the\n            model\'s internal embedding lookup matrix.\n        encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):\n            Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if\n            the model is configured as a decoder.\n        encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):\n            Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in\n            the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:\n\n            - 1 for tokens that are **not masked**,\n            - 0 for tokens that are **masked**.\n\n        output_attentions (`bool`, *optional*):\n            Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned\n            tensors for more detail.\n        output_hidden_states (`bool`, *optional*):\n            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for\n            more detail.\n        return_dict (`bool`, *optional*):\n            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.\n'







@add_start_docstrings(
    '''The bare MMBT Model outputting raw hidden-states without any specific head on top.'''				,			lowerCamelCase__				,			)
class 	lowerCamelCase__      (      nn.Module				,			lowerCamelCase__       ):





   '''simple docstring'''



   def __init__(							self  ,  __UpperCAmelCase  ,  __UpperCAmelCase  ,  __UpperCAmelCase						)				->  Union[str, Any]:
    super().__init__()
    _lowerCAmelCase			=config
    _lowerCAmelCase			=transformer
    _lowerCAmelCase			=ModalEmbeddings(lowercase_  ,  lowercase_  ,  transformer.embeddings						)



   @add_start_docstrings_to_model_forward(lowercase_						)
   @replace_return_docstrings(output_type=lowercase_  ,  config_class=_CONFIG_FOR_DOC						)
   def       _lowerCAmelCase	(							self  ,  __UpperCAmelCase  ,  __UpperCAmelCase=None  ,  __UpperCAmelCase=None  ,  __UpperCAmelCase=None  ,  __UpperCAmelCase=None  ,  __UpperCAmelCase=None  ,  __UpperCAmelCase=None  ,  __UpperCAmelCase=None  ,  __UpperCAmelCase=None  ,  __UpperCAmelCase=None  ,  __UpperCAmelCase=None  ,  __UpperCAmelCase=None  ,  __UpperCAmelCase=None  ,  __UpperCAmelCase=None  ,  __UpperCAmelCase=None  ,  __UpperCAmelCase=None  ,  )				->  str:
    _lowerCAmelCase			=output_attentions if output_attentions is not None else self.config.output_attentions
    _lowerCAmelCase			=(
        output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
    )
    _lowerCAmelCase			=return_dict if return_dict is not None else self.config.use_return_dict

    if input_ids is not None and inputs_embeds is not None:
     raise ValueError("""You cannot specify both input_ids and inputs_embeds at the same time"""						)
    elif input_ids is not None:
     _lowerCAmelCase			=input_ids.size()
    elif inputs_embeds is not None:
     _lowerCAmelCase			=inputs_embeds.size()[:-1]
    else:
     raise ValueError("""You have to specify either input_ids or inputs_embeds"""						)

    _lowerCAmelCase			=input_ids.device if input_ids is not None else inputs_embeds.device

    _lowerCAmelCase			=self.modal_encoder(
        lowercase_  ,  start_token=lowercase_  ,  end_token=lowercase_  ,  position_ids=lowercase_  ,  token_type_ids=lowercase_  ,  )

    _lowerCAmelCase			=modal_embeddings.size()[:-1]

    if token_type_ids is None:
     _lowerCAmelCase			=torch.ones(lowercase_  ,  dtype=torch.long  ,  device=lowercase_						)

    _lowerCAmelCase			=self.transformer.embeddings(
        input_ids=lowercase_  ,  position_ids=lowercase_  ,  token_type_ids=lowercase_  ,  inputs_embeds=lowercase_						)

    _lowerCAmelCase			=torch.cat([modal_embeddings, txt_embeddings]  ,  1						)

    _lowerCAmelCase			=embedding_output.size()[:-1]

    if attention_mask is None:
     _lowerCAmelCase			=torch.ones(lowercase_  ,  device=lowercase_						)
    else:
     _lowerCAmelCase			=torch.cat(
         [torch.ones(lowercase_  ,  device=lowercase_  ,  dtype=torch.long						), attention_mask]  ,  dim=1						)
    if encoder_attention_mask is None:
     _lowerCAmelCase			=torch.ones(lowercase_  ,  device=lowercase_						)
    else:
     _lowerCAmelCase			=torch.cat(
         [torch.ones(lowercase_  ,  device=lowercase_						), encoder_attention_mask]  ,  dim=1						)

    _lowerCAmelCase			=self.get_extended_attention_mask(lowercase_  ,  lowercase_						)
    _lowerCAmelCase			=self.invert_attention_mask(lowercase_						)
    _lowerCAmelCase			=self.get_head_mask(lowercase_  ,  self.config.num_hidden_layers						)

    _lowerCAmelCase			=self.transformer.encoder(
        lowercase_  ,  attention_mask=lowercase_  ,  head_mask=lowercase_  ,  encoder_hidden_states=lowercase_  ,  encoder_attention_mask=lowercase_  ,  output_attentions=lowercase_  ,  output_hidden_states=lowercase_  ,  return_dict=lowercase_  ,  )

    _lowerCAmelCase			=encoder_outputs[0]
    _lowerCAmelCase			=self.transformer.pooler(lowercase_						)

    if not return_dict:
     return (sequence_output, pooled_output) + encoder_outputs[1:]

    return BaseModelOutputWithPooling(
        last_hidden_state=lowercase_  ,  pooler_output=lowercase_  ,  hidden_states=encoder_outputs.hidden_states  ,  attentions=encoder_outputs.attentions  ,  )



   def       _lowerCAmelCase	(							self						)				->  Optional[Any]:
    return self.embeddings.word_embeddings



   def       _lowerCAmelCase	(							self  ,  __UpperCAmelCase						)				->  str:
    _lowerCAmelCase			=value







@add_start_docstrings(
    '''\n    MMBT Model with a sequence classification/regression head on top (a linear layer on top of the pooled output)\n    '''				,			lowerCamelCase__				,			lowerCamelCase__				,			)
class 	lowerCamelCase__      (      nn.Module       ):





   '''simple docstring'''



   def __init__(							self  ,  __UpperCAmelCase  ,  __UpperCAmelCase  ,  __UpperCAmelCase						)				->  int:
    super().__init__()
    _lowerCAmelCase			=config.num_labels

    _lowerCAmelCase			=MMBTModel(lowercase_  ,  lowercase_  ,  lowercase_						)
    _lowerCAmelCase			=nn.Dropout(config.hidden_dropout_prob						)
    _lowerCAmelCase			=nn.Linear(config.hidden_size  ,  config.num_labels						)



   def       _lowerCAmelCase	(							self  ,  __UpperCAmelCase  ,  __UpperCAmelCase=None  ,  __UpperCAmelCase=None  ,  __UpperCAmelCase=None  ,  __UpperCAmelCase=None  ,  __UpperCAmelCase=None  ,  __UpperCAmelCase=None  ,  __UpperCAmelCase=None  ,  __UpperCAmelCase=None  ,  __UpperCAmelCase=None  ,  __UpperCAmelCase=None  ,  __UpperCAmelCase=None  ,  __UpperCAmelCase=None  ,  )				->  int:
    _lowerCAmelCase			=return_dict if return_dict is not None else self.config.use_return_dict

    _lowerCAmelCase			=self.mmbt(
        input_modal=lowercase_  ,  input_ids=lowercase_  ,  modal_start_tokens=lowercase_  ,  modal_end_tokens=lowercase_  ,  attention_mask=lowercase_  ,  token_type_ids=lowercase_  ,  modal_token_type_ids=lowercase_  ,  position_ids=lowercase_  ,  modal_position_ids=lowercase_  ,  head_mask=lowercase_  ,  inputs_embeds=lowercase_  ,  return_dict=lowercase_  ,  )

    _lowerCAmelCase			=outputs[1]

    _lowerCAmelCase			=self.dropout(lowercase_						)
    _lowerCAmelCase			=self.classifier(lowercase_						)

    _lowerCAmelCase			=None
    if labels is not None:
     if self.num_labels == 1:
      #  We are doing regression
      _lowerCAmelCase			=MSELoss()
      _lowerCAmelCase			=loss_fct(logits.view(-1						)  ,  labels.view(-1						)						)
     else:
      _lowerCAmelCase			=CrossEntropyLoss()
      _lowerCAmelCase			=loss_fct(logits.view(-1  ,  self.num_labels						)  ,  labels.view(-1						)						)

    if not return_dict:
     _lowerCAmelCase			=(logits,) + outputs[2:]
     return ((loss,) + output) if loss is not None else output

    return SequenceClassifierOutput(
        loss=lowercase_  ,  logits=lowercase_  ,  hidden_states=outputs.hidden_states  ,  attentions=outputs.attentions  ,  )





"""simple docstring"""


import argparse
import json
import logging
import os
import sys
from unittest import skip
from unittest.mock import patch

import tensorflow as tf

from transformers.testing_utils import TestCasePlus, get_gpu_count, slow


__A 		= [
    os.path.join(os.path.dirname(__file__), dirname)
    for dirname in [
        'text-generation',
        'text-classification',
        'token-classification',
        'language-modeling',
        'multiple-choice',
        'question-answering',
        'summarization',
        'translation',
        'image-classification',
    ]
]
sys.path.extend(SRC_DIRS)


if SRC_DIRS is not None:
			import run_clm
			import run_image_classification
			import run_mlm
			import run_ner
			import run_qa as run_squad
			import run_summarization
			import run_swag
			import run_text_classification
			import run_translation


logging.basicConfig(level=logging.DEBUG)

__A 		= logging.getLogger()



def 					_lowerCamelCase()       ->				str:
	_lowerCAmelCase			=argparse.ArgumentParser()
	parser.add_argument("""-f""" )
	_lowerCAmelCase			=parser.parse_args()
	return args.f



def 					_lowerCamelCase(__UpperCamelCase )       ->				List[str]:
	_lowerCAmelCase			={}
	_lowerCAmelCase			=os.path.join(__UpperCamelCase					,				"""all_results.json""" )
	if os.path.exists(__UpperCamelCase ):
		with open(__UpperCamelCase					,				"""r""" ) as f:
			_lowerCAmelCase			=json.load(__UpperCamelCase )
	else:
		raise ValueError(F'''can\'t find {path}''' )
	return results



def 					_lowerCamelCase()       ->				List[Any]:
	return bool(tf.config.list_physical_devices("""GPU""" ) )


__A 		= logging.StreamHandler(sys.stdout)
logger.addHandler(stream_handler)







class 	lowerCamelCase__      (      __magic_name__       ):





			'''simple docstring'''



			@skip("""Skipping until shape inference for to_tf_dataset PR is merged."""						)
			def       _lowerCAmelCase	(							self						)				->  List[str]:
				_lowerCAmelCase			=self.get_auto_remove_tmp_dir()
				_lowerCAmelCase			=f'''
            run_text_classification.py
            --model_name_or_path distilbert-base-uncased
            --output_dir {tmp_dir}
            --overwrite_output_dir
            --train_file ./tests/fixtures/tests_samples/MRPC/train.csv
            --validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv
            --do_train
            --do_eval
            --per_device_train_batch_size=2
            --per_device_eval_batch_size=1
            --learning_rate=1e-4
            --max_steps=10
            --warmup_steps=2
            --seed=42
            --max_seq_length=128
            '''.split()

				if is_cuda_available():
					testargs.append("""--fp16"""						)

				with patch.object(__UpperCAmelCase  ,  """argv"""  ,  __UpperCAmelCase						):
					run_text_classification.main()
					# Reset the mixed precision policy so we don't break other tests
					tf.keras.mixed_precision.set_global_policy("""float32"""						)
					_lowerCAmelCase			=get_results(__UpperCAmelCase						)
					self.assertGreaterEqual(result["""eval_accuracy"""]  ,  0.7_5						)



			def       _lowerCAmelCase	(							self						)				->  int:
				_lowerCAmelCase			=self.get_auto_remove_tmp_dir()
				_lowerCAmelCase			=f'''
            run_clm.py
            --model_name_or_path distilgpt2
            --train_file ./tests/fixtures/sample_text.txt
            --validation_file ./tests/fixtures/sample_text.txt
            --do_train
            --do_eval
            --block_size 128
            --per_device_train_batch_size 2
            --per_device_eval_batch_size 1
            --num_train_epochs 2
            --output_dir {tmp_dir}
            --overwrite_output_dir
            '''.split()

				if len(tf.config.list_physical_devices("""GPU"""						)						) > 1:
					# Skipping because there are not enough batches to train the model + would need a drop_last to work.
					return

				with patch.object(__UpperCAmelCase  ,  """argv"""  ,  __UpperCAmelCase						):
					run_clm.main()
					_lowerCAmelCase			=get_results(__UpperCAmelCase						)
					self.assertLess(result["""eval_perplexity"""]  ,  1_00						)



			def       _lowerCAmelCase	(							self						)				->  str:
				_lowerCAmelCase			=self.get_auto_remove_tmp_dir()
				_lowerCAmelCase			=f'''
            run_mlm.py
            --model_name_or_path distilroberta-base
            --train_file ./tests/fixtures/sample_text.txt
            --validation_file ./tests/fixtures/sample_text.txt
            --max_seq_length 64
            --output_dir {tmp_dir}
            --overwrite_output_dir
            --do_train
            --do_eval
            --prediction_loss_only
            --num_train_epochs=1
            --learning_rate=1e-4
        '''.split()

				with patch.object(__UpperCAmelCase  ,  """argv"""  ,  __UpperCAmelCase						):
					run_mlm.main()
					_lowerCAmelCase			=get_results(__UpperCAmelCase						)
					self.assertLess(result["""eval_perplexity"""]  ,  42						)



			def       _lowerCAmelCase	(							self						)				->  Union[str, Any]:
				# with so little data distributed training needs more epochs to get the score on par with 0/1 gpu
				_lowerCAmelCase			=7 if get_gpu_count() > 1 else 2

				_lowerCAmelCase			=self.get_auto_remove_tmp_dir()
				_lowerCAmelCase			=f'''
            run_ner.py
            --model_name_or_path bert-base-uncased
            --train_file tests/fixtures/tests_samples/conll/sample.json
            --validation_file tests/fixtures/tests_samples/conll/sample.json
            --output_dir {tmp_dir}
            --overwrite_output_dir
            --do_train
            --do_eval
            --warmup_steps=2
            --learning_rate=2e-4
            --per_device_train_batch_size=2
            --per_device_eval_batch_size=2
            --num_train_epochs={epochs}
            --seed 7
        '''.split()

				with patch.object(__UpperCAmelCase  ,  """argv"""  ,  __UpperCAmelCase						):
					run_ner.main()
					_lowerCAmelCase			=get_results(__UpperCAmelCase						)
					self.assertGreaterEqual(result["""accuracy"""]  ,  0.7_5						)



			def       _lowerCAmelCase	(							self						)				->  str:
				_lowerCAmelCase			=self.get_auto_remove_tmp_dir()
				_lowerCAmelCase			=f'''
            run_qa.py
            --model_name_or_path bert-base-uncased
            --version_2_with_negative
            --train_file tests/fixtures/tests_samples/SQUAD/sample.json
            --validation_file tests/fixtures/tests_samples/SQUAD/sample.json
            --output_dir {tmp_dir}
            --overwrite_output_dir
            --max_steps=10
            --warmup_steps=2
            --do_train
            --do_eval
            --learning_rate=2e-4
            --per_device_train_batch_size=2
            --per_device_eval_batch_size=1
        '''.split()

				with patch.object(__UpperCAmelCase  ,  """argv"""  ,  __UpperCAmelCase						):
					run_squad.main()
					_lowerCAmelCase			=get_results(__UpperCAmelCase						)
					self.assertGreaterEqual(result["""f1"""]  ,  30						)
					self.assertGreaterEqual(result["""exact"""]  ,  30						)



			def       _lowerCAmelCase	(							self						)				->  int:
				_lowerCAmelCase			=self.get_auto_remove_tmp_dir()
				_lowerCAmelCase			=f'''
            run_swag.py
            --model_name_or_path bert-base-uncased
            --train_file tests/fixtures/tests_samples/swag/sample.json
            --validation_file tests/fixtures/tests_samples/swag/sample.json
            --output_dir {tmp_dir}
            --overwrite_output_dir
            --max_steps=20
            --warmup_steps=2
            --do_train
            --do_eval
            --learning_rate=2e-4
            --per_device_train_batch_size=2
            --per_device_eval_batch_size=1
        '''.split()

				with patch.object(__UpperCAmelCase  ,  """argv"""  ,  __UpperCAmelCase						):
					run_swag.main()
					_lowerCAmelCase			=get_results(__UpperCAmelCase						)
					self.assertGreaterEqual(result["""val_accuracy"""]  ,  0.8						)



			@slow
			def       _lowerCAmelCase	(							self						)				->  Tuple:
				_lowerCAmelCase			=self.get_auto_remove_tmp_dir()
				_lowerCAmelCase			=f'''
            run_summarization.py
            --model_name_or_path t5-small
            --train_file tests/fixtures/tests_samples/xsum/sample.json
            --validation_file tests/fixtures/tests_samples/xsum/sample.json
            --output_dir {tmp_dir}
            --overwrite_output_dir
            --max_steps=50
            --warmup_steps=8
            --do_train
            --do_eval
            --learning_rate=2e-4
            --per_device_train_batch_size=2
            --per_device_eval_batch_size=1
        '''.split()

				with patch.object(__UpperCAmelCase  ,  """argv"""  ,  __UpperCAmelCase						):
					run_summarization.main()
					_lowerCAmelCase			=get_results(__UpperCAmelCase						)
					self.assertGreaterEqual(result["""rouge1"""]  ,  10						)
					self.assertGreaterEqual(result["""rouge2"""]  ,  2						)
					self.assertGreaterEqual(result["""rougeL"""]  ,  7						)
					self.assertGreaterEqual(result["""rougeLsum"""]  ,  7						)



			@slow
			def       _lowerCAmelCase	(							self						)				->  Any:
				_lowerCAmelCase			=self.get_auto_remove_tmp_dir()
				_lowerCAmelCase			=f'''
            run_translation.py
            --model_name_or_path Rocketknight1/student_marian_en_ro_6_1
            --source_lang en
            --target_lang ro
            --train_file tests/fixtures/tests_samples/wmt16/sample.json
            --validation_file tests/fixtures/tests_samples/wmt16/sample.json
            --output_dir {tmp_dir}
            --overwrite_output_dir
            --warmup_steps=8
            --do_train
            --do_eval
            --learning_rate=3e-3
            --num_train_epochs 12
            --per_device_train_batch_size=2
            --per_device_eval_batch_size=1
            --source_lang en_XX
            --target_lang ro_RO
        '''.split()

				with patch.object(__UpperCAmelCase  ,  """argv"""  ,  __UpperCAmelCase						):
					run_translation.main()
					_lowerCAmelCase			=get_results(__UpperCAmelCase						)
					self.assertGreaterEqual(result["""bleu"""]  ,  30						)



			def       _lowerCAmelCase	(							self						)				->  Optional[int]:
				_lowerCAmelCase			=self.get_auto_remove_tmp_dir()
				_lowerCAmelCase			=f'''
            run_image_classification.py
            --dataset_name hf-internal-testing/cats_vs_dogs_sample
            --model_name_or_path microsoft/resnet-18
            --do_train
            --do_eval
            --learning_rate 1e-4
            --per_device_train_batch_size 2
            --per_device_eval_batch_size 1
            --output_dir {tmp_dir}
            --overwrite_output_dir
            --dataloader_num_workers 16
            --num_train_epochs 2
            --train_val_split 0.1
            --seed 42
            --ignore_mismatched_sizes True
            '''.split()

				with patch.object(__UpperCAmelCase  ,  """argv"""  ,  __UpperCAmelCase						):
					run_image_classification.main()
					_lowerCAmelCase			=get_results(__UpperCAmelCase						)
					self.assertGreaterEqual(result["""accuracy"""]  ,  0.7						)



