


'''simple docstring'''


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

####################################################################################################

#
# Note: If when running this conversion script you're getting an exception:
#     ModuleNotFoundError: No module named 'megatron.model.enums'
# you need to tell python where to find the clone of Megatron-LM, e.g.:
#
# cd /tmp
# git clone https://github.com/NVIDIA/Megatron-LM
# PYTHONPATH=/tmp/Megatron-LM python src/transformers/models/megatron_bert/convert_megatron_bert_checkpoint.py ...
#
# if you already have it cloned elsewhere, simply adjust the path to the existing path
#
# If the training was done using a Megatron-LM fork, e.g.,
# https://github.com/microsoft/Megatron-DeepSpeed/ then chances are that you need to have that one
# in your path, i.e., /path/to/Megatron-DeepSpeed/
#

import argparse
import os
import re
import zipfile

import torch

from transformers import MegatronBertConfig






def 			__lowerCAmelCase			(__lowerCAmelCase   ,			__lowerCAmelCase   ,			__lowerCAmelCase=0 ):





		if name is None:
				_UpperCAmelCase		:							Optional[int]             =   None
		else:
				_UpperCAmelCase		:							Dict             =   '.' * max(0   ,			spaces - 2 ) + '# {:' + str(50 - spaces ) + 's}'
				_UpperCAmelCase		:							List[str]             =   fmt.format(__lowerCAmelCase )

		# Print and recurse (if needed).
		if isinstance(__lowerCAmelCase   ,			__lowerCAmelCase ):
				if msg is not None:
						print(__lowerCAmelCase )
				for k in val.keys():
						recursive_print(__lowerCAmelCase   ,			val[k]   ,			spaces + 2 )
		elif isinstance(__lowerCAmelCase   ,			torch.Tensor ):
				print(__lowerCAmelCase   ,			":"   ,			val.size() )
		else:
				print(__lowerCAmelCase   ,			":"   ,			__lowerCAmelCase )






def 			__lowerCAmelCase			(__lowerCAmelCase   ,			__lowerCAmelCase   ,			__lowerCAmelCase   ,			__lowerCAmelCase   ,			__lowerCAmelCase ):
		_UpperCAmelCase		:							Optional[int]             =   param.size()
		if checkpoint_version == 1.0:
				# version 1.0 stores [num_heads * hidden_size * num_splits, :]
				_UpperCAmelCase		:							Optional[int]             =   (num_heads, hidden_size, num_splits) + input_shape[1:]
				_UpperCAmelCase		:							Any             =   param.view(*__lowerCAmelCase )
				_UpperCAmelCase		:							Tuple             =   param.transpose(0   ,			2 )
				_UpperCAmelCase		:							List[str]             =   param.transpose(1   ,			2 ).contiguous()
		elif checkpoint_version >= 2.0:
				# other versions store [num_heads * num_splits * hidden_size, :]
				_UpperCAmelCase		:							Union[str, Any]             =   (num_heads, num_splits, hidden_size) + input_shape[1:]
				_UpperCAmelCase		:							Any             =   param.view(*__lowerCAmelCase )
				_UpperCAmelCase		:							List[str]             =   param.transpose(0   ,			1 ).contiguous()
		_UpperCAmelCase		:							Optional[int]             =   param.view(*__lowerCAmelCase )
		return param






def 			__lowerCAmelCase			(__lowerCAmelCase   ,			__lowerCAmelCase   ,			__lowerCAmelCase ):
		_UpperCAmelCase		:							Dict             =   {}

		# old versions did not store training args
		_UpperCAmelCase		:							Optional[int]             =   input_state_dict.get("args"   ,			__lowerCAmelCase )
		if ds_args is not None:
				# do not make the user write a config file when the exact dimensions/sizes are already in the checkpoint
				# from pprint import pprint
				# pprint(vars(ds_args))

				_UpperCAmelCase		:							Tuple             =   ds_args.tokenizer_type
				_UpperCAmelCase		:							Any             =   ds_args.padded_vocab_size
				_UpperCAmelCase		:							Any             =   ds_args.max_position_embeddings
				_UpperCAmelCase		:							Optional[int]             =   ds_args.hidden_size
				_UpperCAmelCase		:							Union[str, Any]             =   ds_args.num_layers
				_UpperCAmelCase		:							Union[str, Any]             =   ds_args.num_attention_heads
				_UpperCAmelCase		:							Optional[int]             =   ds_args.ffn_hidden_size if 'ffn_hidden_size' in ds_args else 4 * ds_args.hidden_size
				# pprint(config)

		# The number of heads.
		_UpperCAmelCase		:							Union[str, Any]             =   config.num_attention_heads
		# The hidden_size per head.
		_UpperCAmelCase		:							Tuple             =   config.hidden_size // heads
		# Megatron-LM checkpoint version
		if "checkpoint_version" in input_state_dict.keys():
				_UpperCAmelCase		:							Dict             =   input_state_dict['checkpoint_version']
		else:
				_UpperCAmelCase		:							str             =   0.0

		# The model.
		_UpperCAmelCase		:							Dict             =   input_state_dict['model']
		# The language model.
		_UpperCAmelCase		:							List[Any]             =   model['language_model']
		# The embeddings.
		_UpperCAmelCase		:							Optional[Any]             =   lm['embedding']

		# The word embeddings.
		_UpperCAmelCase		:							Any             =   embeddings['word_embeddings']['weight']
		# Truncate the embedding table to vocab_size rows.
		_UpperCAmelCase		:							Dict             =   word_embeddings[: config.vocab_size, :]
		# Store the word embeddings.
		_UpperCAmelCase		:							Union[str, Any]             =   word_embeddings

		# The position embeddings.
		_UpperCAmelCase		:							List[str]             =   embeddings['position_embeddings']['weight']
		assert pos_embeddings.size(0 ) == config.max_position_embeddings and pos_embeddings.size(1 ) == config.hidden_size
		# Store the position embeddings.
		_UpperCAmelCase		:							List[str]             =   pos_embeddings

		# The token-type embeddings.
		_UpperCAmelCase		:							Tuple             =   embeddings['tokentype_embeddings']['weight']
		# Store the position embeddings.
		_UpperCAmelCase		:							str             =   tokentype_embeddings

		# The transformer.
		_UpperCAmelCase		:							Union[str, Any]             =   lm['transformer'] if 'transformer' in lm.keys() else lm['encoder']

		# The regex to extract layer names.
		_UpperCAmelCase		:							Dict             =   re.compile(R"layers\.(\d+)\.([a-z0-9_.]+)\.([a-z]+)" )

		# The simple map of names for "automated" rules.
		_UpperCAmelCase		:							Optional[int]             =   {
		    'attention.dense': '.attention.output.dense.',
		    'self_attention.dense': '.attention.output.dense.',
		    'mlp.dense_h_to_4h': '.intermediate.dense.',
		    'mlp.dense_4h_to_h': '.output.dense.',
		}

		# Keep track of the attention/query/value tensor.
		_UpperCAmelCase		:							str             =   None

		# Extract the layers.
		for key, val in transformer.items():
				# Match the name.
				_UpperCAmelCase		:							List[str]             =   layer_re.match(__lowerCAmelCase )

				# Stop if that's not a layer
				if m is None:
						break

				# The index of the layer.
				_UpperCAmelCase		:							Union[str, Any]             =   int(m.group(1 ) )
				# The name of the operation.
				_UpperCAmelCase		:							List[str]             =   m.group(2 )
				# Is it a weight or a bias?
				_UpperCAmelCase		:							List[Any]             =   m.group(3 )

				# The name of the layer.
				_UpperCAmelCase		:							Any             =   F"""bert.encoder.layer.{layer_idx}"""

				# For layernorm(s), simply store the layer norm.
				if op_name.endswith("layernorm" ):
						_UpperCAmelCase		:							Tuple             =   'attention.ln' if op_name.startswith("input" ) else 'ln'
						_UpperCAmelCase		:							Dict             =   val

				# Transpose the QKV matrix.
				elif (
				    op_name == "attention.query_key_value" or op_name == "self_attention.query_key_value"
				) and weight_or_bias == "weight":
						# Make sure the QKV pointer is nil.
						assert attention_qkv_weight is None, ""

						_UpperCAmelCase		:							List[Any]             =   fix_query_key_value_ordering(__lowerCAmelCase   ,			__lowerCAmelCase   ,			3   ,			__lowerCAmelCase   ,			__lowerCAmelCase )
						# Store the tensor as we need the bias as well to interleave QKV and biases.
						_UpperCAmelCase		:							List[Any]             =   out_val

				# Transpose the bias.
				elif (
				    op_name == "attention.query_key_value" or op_name == "self_attention.query_key_value"
				) and weight_or_bias == "bias":
						# Make sure we read the weight tensor.
						assert attention_qkv_weight is not None, ""

						# Split the QKV matrix into Q, K and V. Megatron stores Q,K,V interleaved.
						_UpperCAmelCase		:							Union[str, Any]             =   attention_qkv_weight[0 * config.hidden_size : 1 * config.hidden_size, :]
						_UpperCAmelCase		:							Union[str, Any]             =   attention_qkv_weight[1 * config.hidden_size : 2 * config.hidden_size, :]
						_UpperCAmelCase		:							str             =   attention_qkv_weight[2 * config.hidden_size : 3 * config.hidden_size, :]

						_UpperCAmelCase		:							List[Any]             =   fix_query_key_value_ordering(__lowerCAmelCase   ,			__lowerCAmelCase   ,			3   ,			__lowerCAmelCase   ,			__lowerCAmelCase )
						# Split the bias.
						_UpperCAmelCase		:							Optional[Any]             =   out_val[0 * config.hidden_size : 1 * config.hidden_size]
						_UpperCAmelCase		:							str             =   out_val[1 * config.hidden_size : 2 * config.hidden_size]
						_UpperCAmelCase		:							Optional[int]             =   out_val[2 * config.hidden_size : 3 * config.hidden_size]

						# Store.
						_UpperCAmelCase		:							Tuple             =   q
						_UpperCAmelCase		:							Tuple             =   q_bias
						_UpperCAmelCase		:							Tuple             =   k
						_UpperCAmelCase		:							Optional[int]             =   k_bias
						_UpperCAmelCase		:							List[Any]             =   v
						_UpperCAmelCase		:							Any             =   v_bias

						# Clear the stored tensor.
						_UpperCAmelCase		:							int             =   None

				# Copy weights and biases as is.
				elif weight_or_bias in ["weight", "bias"]:
						_UpperCAmelCase		:							Any             =   megatron_to_transformers[op_name]
						_UpperCAmelCase		:							Any             =   val

				# The final layernorm.
		_UpperCAmelCase		:							Dict             =   transformer['final_layernorm.weight']
		_UpperCAmelCase		:							int             =   transformer['final_layernorm.bias']

		# The pooler.
		_UpperCAmelCase		:							int             =   lm['pooler']

		# Store the matrix and the bias.
		_UpperCAmelCase		:							int             =   pooler['dense.weight']
		_UpperCAmelCase		:							Optional[Any]             =   pooler['dense.bias']

		# The LM head from Megatron (for RACE).
		_UpperCAmelCase		:							int             =   model['lm_head']

		# The transform matrix.
		_UpperCAmelCase		:							Optional[Any]             =   lm_head['dense.weight']
		_UpperCAmelCase		:							List[str]             =   lm_head['dense.bias']

		# The transform LN.
		_UpperCAmelCase		:							Optional[int]             =   lm_head['layernorm.weight']
		_UpperCAmelCase		:							int             =   lm_head['layernorm.bias']

		# For the decoder, we replicate the weights.
		_UpperCAmelCase		:							Optional[int]             =   word_embeddings
		_UpperCAmelCase		:							List[str]             =   lm_head['bias']

		# The classifier from Megatron (for MLNI).
		_UpperCAmelCase		:							Optional[int]             =   model['binary_head']

		# Store the classifier.
		_UpperCAmelCase		:							Dict             =   binary_head['weight']
		_UpperCAmelCase		:							List[str]             =   binary_head['bias']

		# It should be done!
		return output_state_dict






def 			__lowerCAmelCase			():
		_UpperCAmelCase		:							Optional[Any]             =   argparse.ArgumentParser()
		parser.add_argument("--print-checkpoint-structure"   ,			action="store_true" )
		parser.add_argument("path_to_checkpoint"   ,			type=__lowerCAmelCase   ,			help="Path to the ZIP file containing the checkpoint" )
		parser.add_argument(
		    "--config_file"   ,			default=""   ,			type=__lowerCAmelCase   ,			help="An optional config json file describing the pre-trained model."   ,			)
		_UpperCAmelCase		:							Dict             =   parser.parse_args()

		# Extract the basename.
		_UpperCAmelCase		:							List[Any]             =   os.path.dirname(args.path_to_checkpoint )

		# Load the model.
		# the .zip is very optional, let's keep it for backward compatibility
		print(F"""Extracting PyTorch state dictionary from \"{args.path_to_checkpoint}\"""" )
		if args.path_to_checkpoint.endswith(".zip" ):
				with zipfile.ZipFile(args.path_to_checkpoint   ,			"r" ) as checkpoint:
						with checkpoint.open("release/mp_rank_00/model_optim_rng.pt" ) as pytorch_dict:
								_UpperCAmelCase		:							int             =   torch.load(__lowerCAmelCase   ,			map_location="cpu" )
		else:
				_UpperCAmelCase		:							Tuple             =   torch.load(args.path_to_checkpoint   ,			map_location="cpu" )

		if args.config_file == "":
				# Default config of megatron-bert 345m
				_UpperCAmelCase		:							List[Any]             =   MegatronBertConfig()

				# different megatron-bert-*-345m models have different vocab sizes, so override the default
				# config (which is for megatron-bert-cased-345m) with the actual vocab dimension
				_UpperCAmelCase		:							Tuple             =   input_state_dict['model']['lm_head']['bias'].numel()
		else:
				_UpperCAmelCase		:							Tuple             =   MegatronBertConfig.from_json_file(args.config_file )

		# Convert.
		print("Converting" )
		_UpperCAmelCase		:							Dict             =   convert_megatron_checkpoint(__lowerCAmelCase   ,			__lowerCAmelCase   ,			__lowerCAmelCase )

		# Print the structure of converted state dict.
		if args.print_checkpoint_structure:
				recursive_print(__lowerCAmelCase   ,			__lowerCAmelCase )

		# Store the config to file.
		print("Saving config" )
		config.save_pretrained(__lowerCAmelCase )

		# Store the state_dict to file.
		_UpperCAmelCase		:							Union[str, Any]             =   os.path.join(__lowerCAmelCase   ,			"pytorch_model.bin" )
		print(F"""Saving checkpoint to \"{output_checkpoint_file}\"""" )
		torch.save(__lowerCAmelCase   ,			__lowerCAmelCase )


####################################################################################################

if __name__ == "__main__":
						main()

####################################################################################################









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


UpperCAmelCase__    :							Any       		=     [
    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)

UpperCAmelCase__    :							Union[str, Any]       		=     logging.getLogger()


def 		_lowerCamelCase					(       )      ->		str:





  """simple docstring"""





  _lowercase:			int      =     argparse.ArgumentParser()
  parser.add_argument('-f'				)
  _lowercase:			Optional[Any]      =     parser.parse_args()
  return args.f


def 		_lowerCamelCase					(       UpperCamelCase				)      ->		Dict:





  """simple docstring"""





  _lowercase:			str      =     {}
  _lowercase:			Union[str, Any]      =     os.path.join(UpperCamelCase       ,  'all_results.json'				)
  if os.path.exists(UpperCamelCase				):
    with open(UpperCamelCase       ,  'r'				) as f:
      _lowercase:			Dict      =     json.load(UpperCamelCase				)
  else:
    raise ValueError(F'can\'t find {path}'				)
  return results


def 		_lowerCamelCase					(       )      ->		Any:





  """simple docstring"""





  return bool(tf.config.list_physical_devices('GPU'				)				)


UpperCAmelCase__    :							List[Any]       		=     logging.StreamHandler(sys.stdout)
logger.addHandler(stream_handler)





class   UpperCAmelCase    (      A ):






   @skip('Skipping until shape inference for to_tf_dataset PR is merged.'  )
   def 			_a    (						self :							Union[str, Any]  )->      Optional[Any]:
     _lowercase:			List[str]      =     self.get_auto_remove_tmp_dir()
     _lowercase:			List[str]      =     f'\n            run_text_classification.py\n            --model_name_or_path distilbert-base-uncased\n            --output_dir {tmp_dir}\n            --overwrite_output_dir\n            --train_file ./tests/fixtures/tests_samples/MRPC/train.csv\n            --validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv\n            --do_train\n            --do_eval\n            --per_device_train_batch_size=2\n            --per_device_eval_batch_size=1\n            --learning_rate=1e-4\n            --max_steps=10\n            --warmup_steps=2\n            --seed=42\n            --max_seq_length=128\n            '.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'  )
       _lowercase:			List[str]      =     get_results(UpperCamelCase_  )
       self.assertGreaterEqual(result['eval_accuracy']    ,       0.75  )






   def 			_a    (						self :							Optional[Any]  )->      int:
     _lowercase:			Dict      =     self.get_auto_remove_tmp_dir()
     _lowercase:			str      =     f'\n            run_clm.py\n            --model_name_or_path distilgpt2\n            --train_file ./tests/fixtures/sample_text.txt\n            --validation_file ./tests/fixtures/sample_text.txt\n            --do_train\n            --do_eval\n            --block_size 128\n            --per_device_train_batch_size 2\n            --per_device_eval_batch_size 1\n            --num_train_epochs 2\n            --output_dir {tmp_dir}\n            --overwrite_output_dir\n            '.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()
       _lowercase:			str      =     get_results(UpperCamelCase_  )
       self.assertLess(result['eval_perplexity']    ,       1_00  )






   def 			_a    (						self :							Union[str, Any]  )->      Optional[int]:
     _lowercase:			int      =     self.get_auto_remove_tmp_dir()
     _lowercase:			int      =     f'\n            run_mlm.py\n            --model_name_or_path distilroberta-base\n            --train_file ./tests/fixtures/sample_text.txt\n            --validation_file ./tests/fixtures/sample_text.txt\n            --max_seq_length 64\n            --output_dir {tmp_dir}\n            --overwrite_output_dir\n            --do_train\n            --do_eval\n            --prediction_loss_only\n            --num_train_epochs=1\n            --learning_rate=1e-4\n        '.split()

     with patch.object(UpperCamelCase_    ,       'argv'    ,       UpperCamelCase_  ):
       run_mlm.main()
       _lowercase:			str      =     get_results(UpperCamelCase_  )
       self.assertLess(result['eval_perplexity']    ,       42  )






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

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

     with patch.object(UpperCamelCase_    ,       'argv'    ,       UpperCamelCase_  ):
       run_ner.main()
       _lowercase:			Optional[Any]      =     get_results(UpperCamelCase_  )
       self.assertGreaterEqual(result['accuracy']    ,       0.75  )






   def 			_a    (						self :							Tuple  )->      Optional[int]:
     _lowercase:			List[Any]      =     self.get_auto_remove_tmp_dir()
     _lowercase:			int      =     f'\n            run_qa.py\n            --model_name_or_path bert-base-uncased\n            --version_2_with_negative\n            --train_file tests/fixtures/tests_samples/SQUAD/sample.json\n            --validation_file tests/fixtures/tests_samples/SQUAD/sample.json\n            --output_dir {tmp_dir}\n            --overwrite_output_dir\n            --max_steps=10\n            --warmup_steps=2\n            --do_train\n            --do_eval\n            --learning_rate=2e-4\n            --per_device_train_batch_size=2\n            --per_device_eval_batch_size=1\n        '.split()

     with patch.object(UpperCamelCase_    ,       'argv'    ,       UpperCamelCase_  ):
       run_squad.main()
       _lowercase:			Union[str, Any]      =     get_results(UpperCamelCase_  )
       self.assertGreaterEqual(result['f1']    ,       30  )
       self.assertGreaterEqual(result['exact']    ,       30  )






   def 			_a    (						self :							List[str]  )->      Tuple:
     _lowercase:			str      =     self.get_auto_remove_tmp_dir()
     _lowercase:			Any      =     f'\n            run_swag.py\n            --model_name_or_path bert-base-uncased\n            --train_file tests/fixtures/tests_samples/swag/sample.json\n            --validation_file tests/fixtures/tests_samples/swag/sample.json\n            --output_dir {tmp_dir}\n            --overwrite_output_dir\n            --max_steps=20\n            --warmup_steps=2\n            --do_train\n            --do_eval\n            --learning_rate=2e-4\n            --per_device_train_batch_size=2\n            --per_device_eval_batch_size=1\n        '.split()

     with patch.object(UpperCamelCase_    ,       'argv'    ,       UpperCamelCase_  ):
       run_swag.main()
       _lowercase:			List[str]      =     get_results(UpperCamelCase_  )
       self.assertGreaterEqual(result['val_accuracy']    ,       0.8  )






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

     with patch.object(UpperCamelCase_    ,       'argv'    ,       UpperCamelCase_  ):
       run_summarization.main()
       _lowercase:			List[str]      =     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 			_a    (						self :							Tuple  )->      str:
     _lowercase:			List[Any]      =     self.get_auto_remove_tmp_dir()
     _lowercase:			List[str]      =     f'\n            run_translation.py\n            --model_name_or_path Rocketknight1/student_marian_en_ro_6_1\n            --source_lang en\n            --target_lang ro\n            --train_file tests/fixtures/tests_samples/wmt16/sample.json\n            --validation_file tests/fixtures/tests_samples/wmt16/sample.json\n            --output_dir {tmp_dir}\n            --overwrite_output_dir\n            --warmup_steps=8\n            --do_train\n            --do_eval\n            --learning_rate=3e-3\n            --num_train_epochs 12\n            --per_device_train_batch_size=2\n            --per_device_eval_batch_size=1\n            --source_lang en_XX\n            --target_lang ro_RO\n        '.split()

     with patch.object(UpperCamelCase_    ,       'argv'    ,       UpperCamelCase_  ):
       run_translation.main()
       _lowercase:			Optional[int]      =     get_results(UpperCamelCase_  )
       self.assertGreaterEqual(result['bleu']    ,       30  )






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

     with patch.object(UpperCamelCase_    ,       'argv'    ,       UpperCamelCase_  ):
       run_image_classification.main()
       _lowercase:			Union[str, Any]      =     get_results(UpperCamelCase_  )
       self.assertGreaterEqual(result['accuracy']    ,       0.7  )
