

'''simple docstring'''





import os
import re
import warnings
from shutil import copyfile
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple

import sentencepiece as spm

from ...tokenization_utils import PreTrainedTokenizer


if TYPE_CHECKING:
						from ...tokenization_utils_base import TextInput
from ...utils import logging


UpperCAmelCase    					=   logging.get_logger(__name__)

UpperCAmelCase    					=   {'''vocab_file''': '''spiece.model'''}

UpperCAmelCase    					=   {
    '''vocab_file''': {
        '''t5-small''': '''https://huggingface.co/t5-small/resolve/main/spiece.model''',
        '''t5-base''': '''https://huggingface.co/t5-base/resolve/main/spiece.model''',
        '''t5-large''': '''https://huggingface.co/t5-large/resolve/main/spiece.model''',
        '''t5-3b''': '''https://huggingface.co/t5-3b/resolve/main/spiece.model''',
        '''t5-11b''': '''https://huggingface.co/t5-11b/resolve/main/spiece.model''',
    }
}


# TODO(PVP) - this should be removed in Transformers v5
UpperCAmelCase    					=   {
    '''t5-small''': 512,
    '''t5-base''': 512,
    '''t5-large''': 512,
    '''t5-3b''': 512,
    '''t5-11b''': 512,
}

UpperCAmelCase    					=   '''▁'''

class 						a   (				UpperCAmelCase__    ):
				_snake_case		    = VOCAB_FILES_NAMES
				_snake_case		    = PRETRAINED_VOCAB_FILES_MAP
				_snake_case		    = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
				_snake_case		    = ['''input_ids''', '''attention_mask''']




				def __init__(							self	:				Any,    SCREAMING_SNAKE_CASE_	:				Optional[Any],    SCREAMING_SNAKE_CASE_	:				List[Any]="</s>",    SCREAMING_SNAKE_CASE_	:				Any="<unk>",    SCREAMING_SNAKE_CASE_	:				Dict="<pad>",    SCREAMING_SNAKE_CASE_	:				int=1_00,    SCREAMING_SNAKE_CASE_	:				Optional[Any]=None,    SCREAMING_SNAKE_CASE_	:				Optional[Dict[str, Any]] = None,    SCREAMING_SNAKE_CASE_	:				Tuple=True,    **SCREAMING_SNAKE_CASE_	:				Tuple,    ):






										if extra_ids > 0 and additional_special_tokens is None:
																snake_case       :     str =    [F"""<extra_id_{i}>""" for i in range(__lowerCAmelCase      )]
										elif extra_ids > 0 and additional_special_tokens is not None:
																# Check that we have the right number of extra_id special tokens
																snake_case       :     List[str] =    len(set(filter(lambda SCREAMING_SNAKE_CASE_      : bool('''extra_id''' in str(__lowerCAmelCase      )      ),    __lowerCAmelCase      )      )      )
																if extra_tokens != extra_ids:
																						raise ValueError(
																						    F"""Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are"""
																						    ''' provided to T5Tokenizer. In this case the additional_special_tokens must include the extra_ids'''
																						    ''' tokens'''      )
										if legacy:
																logger.warning_once(
																    F"""You are using the legacy behaviour of the {self.__class__}. This means that tokens that come after special tokens will not be properly handled. We recommend you to"""
																    ''' read the related pull request available at https://github.com/huggingface/transformers/pull/24565'''      )

										snake_case       :     Optional[int] =    legacy
										snake_case       :     Optional[Any] =    {} if sp_model_kwargs is None else sp_model_kwargs

										super().__init__(
										    eos_token=__lowerCAmelCase,    unk_token=__lowerCAmelCase,    pad_token=__lowerCAmelCase,    extra_ids=__lowerCAmelCase,    additional_special_tokens=__lowerCAmelCase,    sp_model_kwargs=self.sp_model_kwargs,    legacy=__lowerCAmelCase,    **__lowerCAmelCase,    )

										snake_case       :     int =    vocab_file
										snake_case       :     Optional[Any] =    extra_ids

										snake_case       :     Any =    spm.SentencePieceProcessor(**self.sp_model_kwargs      )
										self.sp_model.Load(__lowerCAmelCase      )




				@staticmethod
				def 	__snake_case							(							SCREAMING_SNAKE_CASE_	:				str,    SCREAMING_SNAKE_CASE_	:				List[str],    SCREAMING_SNAKE_CASE_	:				Optional[int]      ):






										if pretrained_model_name_or_path in TaTokenizer.max_model_input_sizes:
																snake_case       :     List[str] =    TaTokenizer.max_model_input_sizes[pretrained_model_name_or_path]
																if init_max_model_length is not None and init_max_model_length != max_model_length:
																						return init_max_model_length
																elif init_max_model_length is None:
																						warnings.warn(
																						    '''This tokenizer was incorrectly instantiated with a model max length of'''
																						    F""" {deprecated_max_model_length} which will be corrected in Transformers v5.\nFor now, this"""
																						    ''' behavior is kept to avoid breaking backwards compatibility when padding/encoding with'''
																						    ''' `truncation is True`.\n- Be aware that you SHOULD NOT rely on'''
																						    F""" {pretrained_model_name_or_path} automatically truncating your input to"""
																						    F""" {deprecated_max_model_length} when padding/encoding.\n- If you want to encode/pad to sequences"""
																						    F""" longer than {deprecated_max_model_length} you can either instantiate this tokenizer with"""
																						    ''' `model_max_length` or pass `max_length` when encoding/padding.\n- To avoid this warning, please'''
																						    ''' instantiate this tokenizer with `model_max_length` set to your preferred value.''',    __lowerCAmelCase,    )

										return max_model_length




				@property
				def 	__snake_case							(							self	:				int      ):
										return self.sp_model.get_piece_size() + self._extra_ids




				def 	__snake_case							(							self	:				Optional[Any]      ):
										snake_case       :     Union[str, Any] =    {self.convert_ids_to_tokens(__lowerCAmelCase      ): i for i in range(self.vocab_size      )}
										vocab.update(self.added_tokens_encoder      )
										return vocab




				def 	__snake_case							(							self	:				Tuple,    SCREAMING_SNAKE_CASE_	:				List[int],    SCREAMING_SNAKE_CASE_	:				Optional[List[int]] = None,    SCREAMING_SNAKE_CASE_	:				bool = False      ):






										if already_has_special_tokens:
																return super().get_special_tokens_mask(
																    token_ids_a=__lowerCAmelCase,    token_ids_a=__lowerCAmelCase,    already_has_special_tokens=__lowerCAmelCase      )

										# normal case: some special tokens
										if token_ids_a is None:
																return ([0] * len(__lowerCAmelCase      )) + [1]
										return ([0] * len(__lowerCAmelCase      )) + [1] + ([0] * len(__lowerCAmelCase      )) + [1]




				def 	__snake_case							(							self	:				Dict      ):
										return list(
										    set(filter(lambda SCREAMING_SNAKE_CASE_      : bool(re.search(R'''<extra_id_\d+>''',    __lowerCAmelCase      )      ) is not None,    self.additional_special_tokens      )      )      )




				def 	__snake_case							(							self	:				str      ):
										return [self._convert_token_to_id(__lowerCAmelCase      ) for token in self.get_sentinel_tokens()]




				def 	__snake_case							(							self	:				Union[str, Any],    SCREAMING_SNAKE_CASE_	:				List[int]      ):






										if len(__lowerCAmelCase      ) > 0 and token_ids[-1] == self.eos_token_id:
																warnings.warn(
																    F"""This sequence already has {self.eos_token}. In future versions this behavior may lead to duplicated"""
																    ''' eos tokens being added.'''      )
																return token_ids
										else:
																return token_ids + [self.eos_token_id]




				def 	__snake_case							(							self	:				Dict,    SCREAMING_SNAKE_CASE_	:				List[int],    SCREAMING_SNAKE_CASE_	:				Optional[List[int]] = None      ):
										snake_case       :     List[Any] =    [self.eos_token_id]

										if token_ids_a is None:
																return len(token_ids_a + eos      ) * [0]
										return len(token_ids_a + eos + token_ids_a + eos      ) * [0]




				def 	__snake_case							(							self	:				List[str],    SCREAMING_SNAKE_CASE_	:				List[int],    SCREAMING_SNAKE_CASE_	:				Optional[List[int]] = None      ):
										snake_case       :     List[str] =    self._add_eos_if_not_present(__lowerCAmelCase      )
										if token_ids_a is None:
																return token_ids_a
										else:
																snake_case       :     Dict =    self._add_eos_if_not_present(__lowerCAmelCase      )
																return token_ids_a + token_ids_a




				def __getstate__(							self	:				List[Any]      ):
										snake_case       :     int =    self.__dict__.copy()
										snake_case       :     str =    None
										return state




				def __setstate__(							self	:				str,    SCREAMING_SNAKE_CASE_	:				List[Any]      ):
										snake_case       :     Optional[Any] =    d

										# for backward compatibility
										if not hasattr(self,    '''sp_model_kwargs'''      ):
																snake_case       :     str =    {}

										snake_case       :     str =    spm.SentencePieceProcessor(**self.sp_model_kwargs      )
										self.sp_model.Load(self.vocab_file      )




				def 	__snake_case							(							self	:				Any,    SCREAMING_SNAKE_CASE_	:				"TextInput",    **SCREAMING_SNAKE_CASE_	:				Dict      ):






										if not self.legacy:
																snake_case       :     str =    SPIECE_UNDERLINE + text.replace(__lowerCAmelCase,    ''' '''      )
										return super().tokenize(__lowerCAmelCase,    **__lowerCAmelCase      )




				def 	__snake_case							(							self	:				List[Any],    SCREAMING_SNAKE_CASE_	:				Tuple,    **SCREAMING_SNAKE_CASE_	:				Dict      ):






										if not self.legacy:
																snake_case       :     List[str] =    text.startswith(__lowerCAmelCase      )
																if is_first:
																						snake_case       :     Optional[int] =    text[1:]

										snake_case       :     Tuple =    self.sp_model.encode(__lowerCAmelCase,    out_type=__lowerCAmelCase      )

										if not self.legacy and not is_first and not text.startswith(''' '''      ) and tokens[0].startswith(__lowerCAmelCase      ):
																snake_case       :     Tuple =    ([tokens[0][1:]] if len(tokens[0]      ) > 1 else []) + tokens[1:]
										return tokens




				def 	__snake_case							(							self	:				List[str],    SCREAMING_SNAKE_CASE_	:				List[str]      ):






										if token.startswith('''<extra_id_'''      ):
																snake_case       :     Union[str, Any] =    re.match(R'''<extra_id_(\d+)>''',    __lowerCAmelCase      )
																snake_case       :     Any =    int(match.group(1      )      )
																return self.vocab_size - num - 1
										return self.sp_model.piece_to_id(__lowerCAmelCase      )




				def 	__snake_case							(							self	:				List[Any],    SCREAMING_SNAKE_CASE_	:				Optional[Any]      ):






										if index < self.sp_model.get_piece_size():
																snake_case       :     Any =    self.sp_model.IdToPiece(__lowerCAmelCase      )
										else:
																snake_case       :     Optional[Any] =    F"""<extra_id_{self.vocab_size - 1 - index}>"""
										return token




				def 	__snake_case							(							self	:				Dict,    SCREAMING_SNAKE_CASE_	:				str      ):
										snake_case       :     Tuple =    []
										snake_case       :     List[str] =    ''''''
										snake_case       :     Tuple =    False
										for token in tokens:
																# make sure that special tokens are not decoded using sentencepiece model
																if token in self.all_special_tokens:
																						if not prev_is_special:
																												out_string += " "
																						out_string += self.sp_model.decode(__lowerCAmelCase      ) + token
																						snake_case       :     str =    True
																						snake_case       :     str =    []
																else:
																						current_sub_tokens.append(__lowerCAmelCase      )
																						snake_case       :     List[str] =    False
										out_string += self.sp_model.decode(__lowerCAmelCase      )
										return out_string.strip()




				def 	__snake_case							(							self	:				Dict,    SCREAMING_SNAKE_CASE_	:				str,    SCREAMING_SNAKE_CASE_	:				Optional[str] = None      ):






										if not os.path.isdir(__lowerCAmelCase      ):
																logger.error(F"""Vocabulary path ({save_directory}) should be a directory"""      )
																return
										snake_case       :     Union[str, Any] =    os.path.join(
										    __lowerCAmelCase,    (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file''']      )

										if os.path.abspath(self.vocab_file      ) != os.path.abspath(__lowerCAmelCase      ) and os.path.isfile(self.vocab_file      ):
																copyfile(self.vocab_file,    __lowerCAmelCase      )
										elif not os.path.isfile(self.vocab_file      ):
																with open(__lowerCAmelCase,    '''wb'''      ) as fi:
																						snake_case       :     Optional[int] =    self.sp_model.serialized_model_proto()
																						fi.write(__lowerCAmelCase      )

										return (out_vocab_file,)



'''simple docstring'''





import argparse
import json
import logging
import os
import shutil
import sys
import tempfile
import unittest
from unittest import mock

import torch
from accelerate.utils import write_basic_config

from transformers.testing_utils import TestCasePlus, get_gpu_count, run_command, slow, torch_device
from transformers.utils import is_apex_available


logging.basicConfig(level=logging.DEBUG)

UpperCAmelCase    					=   logging.getLogger()

def      A (       ):
						snake_case       :     Dict =    argparse.ArgumentParser()
						parser.add_argument('''-f'''       )
						snake_case       :     Any =    parser.parse_args()
						return args.f

def      A (       A_							:					str       ):
						snake_case       :     str =    {}
						snake_case       :     Union[str, Any] =    os.path.join(A_    ,							'''all_results.json'''       )
						if os.path.exists(A_       ):
												with open(A_    ,							'''r'''       ) as f:
																		snake_case       :     List[str] =    json.load(A_       )
						else:
												raise ValueError(F"""can't find {path}"""       )
						return results

def      A (       ):
						snake_case       :     Any =    torch.cuda.is_available() and torch_device == '''cuda'''
						return is_using_cuda and is_apex_available()


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





class 						a   (				__magic_name__    ):




				@classmethod
				def 	__snake_case							(							cls	:				Tuple      ):
										# Write Accelerate config, will pick up on CPU, GPU, and multi-GPU
										snake_case       :     int =    tempfile.mkdtemp()
										snake_case       :     Optional[Any] =    os.path.join(cls.tmpdir,    '''default_config.yml'''      )
										write_basic_config(save_location=cls.configPath      )
										snake_case       :     Tuple =    ['''accelerate''', '''launch''', '''--config_file''', cls.configPath]




				@classmethod
				def 	__snake_case							(							cls	:				Optional[int]      ):
										shutil.rmtree(cls.tmpdir      )




				@mock.patch.dict(os.environ,    {'''WANDB_MODE''': '''offline'''}      )
				def 	__snake_case							(							self	:				Any      ):
										snake_case       :     Any =    self.get_auto_remove_tmp_dir()
										snake_case       :     Optional[Any] =    F"""
            {self.examples_dir}/pytorch/text-classification/run_glue_no_trainer.py
            --model_name_or_path distilbert-base-uncased
            --output_dir {tmp_dir}
            --train_file ./tests/fixtures/tests_samples/MRPC/train.csv
            --validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv
            --per_device_train_batch_size=2
            --per_device_eval_batch_size=1
            --learning_rate=1e-4
            --seed=42
            --checkpointing_steps epoch
            --with_tracking
        """.split()

										if is_cuda_and_apex_available():
																testargs.append('''--fp16'''      )

										run_command(self._launch_args + testargs      )
										snake_case       :     int =    get_results(SCREAMING_SNAKE_CASE_      )
										self.assertGreaterEqual(result['''eval_accuracy'''],    0.75      )
										self.assertTrue(os.path.exists(os.path.join(SCREAMING_SNAKE_CASE_,    '''epoch_0'''      )      )      )
										self.assertTrue(os.path.exists(os.path.join(SCREAMING_SNAKE_CASE_,    '''glue_no_trainer'''      )      )      )




				@mock.patch.dict(os.environ,    {'''WANDB_MODE''': '''offline'''}      )
				def 	__snake_case							(							self	:				Tuple      ):
										snake_case       :     int =    self.get_auto_remove_tmp_dir()
										snake_case       :     str =    F"""
            {self.examples_dir}/pytorch/language-modeling/run_clm_no_trainer.py
            --model_name_or_path distilgpt2
            --train_file ./tests/fixtures/sample_text.txt
            --validation_file ./tests/fixtures/sample_text.txt
            --block_size 128
            --per_device_train_batch_size 5
            --per_device_eval_batch_size 5
            --num_train_epochs 2
            --output_dir {tmp_dir}
            --checkpointing_steps epoch
            --with_tracking
        """.split()

										if torch.cuda.device_count() > 1:
																# Skipping because there are not enough batches to train the model + would need a drop_last to work.
																return

										run_command(self._launch_args + testargs      )
										snake_case       :     List[str] =    get_results(SCREAMING_SNAKE_CASE_      )
										self.assertLess(result['''perplexity'''],    1_00      )
										self.assertTrue(os.path.exists(os.path.join(SCREAMING_SNAKE_CASE_,    '''epoch_0'''      )      )      )
										self.assertTrue(os.path.exists(os.path.join(SCREAMING_SNAKE_CASE_,    '''clm_no_trainer'''      )      )      )




				@mock.patch.dict(os.environ,    {'''WANDB_MODE''': '''offline'''}      )
				def 	__snake_case							(							self	:				List[Any]      ):
										snake_case       :     Union[str, Any] =    self.get_auto_remove_tmp_dir()
										snake_case       :     int =    F"""
            {self.examples_dir}/pytorch/language-modeling/run_mlm_no_trainer.py
            --model_name_or_path distilroberta-base
            --train_file ./tests/fixtures/sample_text.txt
            --validation_file ./tests/fixtures/sample_text.txt
            --output_dir {tmp_dir}
            --num_train_epochs=1
            --checkpointing_steps epoch
            --with_tracking
        """.split()

										run_command(self._launch_args + testargs      )
										snake_case       :     List[Any] =    get_results(SCREAMING_SNAKE_CASE_      )
										self.assertLess(result['''perplexity'''],    42      )
										self.assertTrue(os.path.exists(os.path.join(SCREAMING_SNAKE_CASE_,    '''epoch_0'''      )      )      )
										self.assertTrue(os.path.exists(os.path.join(SCREAMING_SNAKE_CASE_,    '''mlm_no_trainer'''      )      )      )




				@mock.patch.dict(os.environ,    {'''WANDB_MODE''': '''offline'''}      )
				def 	__snake_case							(							self	:				Dict      ):
										# with so little data distributed training needs more epochs to get the score on par with 0/1 gpu
										snake_case       :     Any =    7 if get_gpu_count() > 1 else 2

										snake_case       :     Optional[int] =    self.get_auto_remove_tmp_dir()
										snake_case       :     str =    F"""
            {self.examples_dir}/pytorch/token-classification/run_ner_no_trainer.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}
            --learning_rate=2e-4
            --per_device_train_batch_size=2
            --per_device_eval_batch_size=2
            --num_train_epochs={epochs}
            --seed 7
            --checkpointing_steps epoch
            --with_tracking
        """.split()

										run_command(self._launch_args + testargs      )
										snake_case       :     Optional[int] =    get_results(SCREAMING_SNAKE_CASE_      )
										self.assertGreaterEqual(result['''eval_accuracy'''],    0.75      )
										self.assertLess(result['''train_loss'''],    0.5      )
										self.assertTrue(os.path.exists(os.path.join(SCREAMING_SNAKE_CASE_,    '''epoch_0'''      )      )      )
										self.assertTrue(os.path.exists(os.path.join(SCREAMING_SNAKE_CASE_,    '''ner_no_trainer'''      )      )      )




				@unittest.skip(reason='''Fix me @muellerzr'''      )
				@mock.patch.dict(os.environ,    {'''WANDB_MODE''': '''offline'''}      )
				def 	__snake_case							(							self	:				Tuple      ):
										snake_case       :     Tuple =    self.get_auto_remove_tmp_dir()
										snake_case       :     Optional[int] =    F"""
            {self.examples_dir}/pytorch/question-answering/run_qa_no_trainer.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}
            --seed=42
            --max_train_steps=10
            --num_warmup_steps=2
            --learning_rate=2e-4
            --per_device_train_batch_size=2
            --per_device_eval_batch_size=1
            --checkpointing_steps epoch
            --with_tracking
        """.split()

										run_command(self._launch_args + testargs      )
										snake_case       :     str =    get_results(SCREAMING_SNAKE_CASE_      )
										# Because we use --version_2_with_negative the testing script uses SQuAD v2 metrics.
										self.assertGreaterEqual(result['''eval_f1'''],    28      )
										self.assertGreaterEqual(result['''eval_exact'''],    28      )
										self.assertTrue(os.path.exists(os.path.join(SCREAMING_SNAKE_CASE_,    '''epoch_0'''      )      )      )
										self.assertTrue(os.path.exists(os.path.join(SCREAMING_SNAKE_CASE_,    '''qa_no_trainer'''      )      )      )




				@mock.patch.dict(os.environ,    {'''WANDB_MODE''': '''offline'''}      )
				def 	__snake_case							(							self	:				Optional[int]      ):
										snake_case       :     Any =    self.get_auto_remove_tmp_dir()
										snake_case       :     List[Any] =    F"""
            {self.examples_dir}/pytorch/multiple-choice/run_swag_no_trainer.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}
            --max_train_steps=20
            --num_warmup_steps=2
            --learning_rate=2e-4
            --per_device_train_batch_size=2
            --per_device_eval_batch_size=1
            --with_tracking
        """.split()

										run_command(self._launch_args + testargs      )
										snake_case       :     Union[str, Any] =    get_results(SCREAMING_SNAKE_CASE_      )
										self.assertGreaterEqual(result['''eval_accuracy'''],    0.8      )
										self.assertTrue(os.path.exists(os.path.join(SCREAMING_SNAKE_CASE_,    '''swag_no_trainer'''      )      )      )




				@slow
				@mock.patch.dict(os.environ,    {'''WANDB_MODE''': '''offline'''}      )
				def 	__snake_case							(							self	:				str      ):
										snake_case       :     str =    self.get_auto_remove_tmp_dir()
										snake_case       :     Any =    F"""
            {self.examples_dir}/pytorch/summarization/run_summarization_no_trainer.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}
            --max_train_steps=50
            --num_warmup_steps=8
            --learning_rate=2e-4
            --per_device_train_batch_size=2
            --per_device_eval_batch_size=1
            --checkpointing_steps epoch
            --with_tracking
        """.split()

										run_command(self._launch_args + testargs      )
										snake_case       :     str =    get_results(SCREAMING_SNAKE_CASE_      )
										self.assertGreaterEqual(result['''eval_rouge1'''],    10      )
										self.assertGreaterEqual(result['''eval_rouge2'''],    2      )
										self.assertGreaterEqual(result['''eval_rougeL'''],    7      )
										self.assertGreaterEqual(result['''eval_rougeLsum'''],    7      )
										self.assertTrue(os.path.exists(os.path.join(SCREAMING_SNAKE_CASE_,    '''epoch_0'''      )      )      )
										self.assertTrue(os.path.exists(os.path.join(SCREAMING_SNAKE_CASE_,    '''summarization_no_trainer'''      )      )      )




				@slow
				@mock.patch.dict(os.environ,    {'''WANDB_MODE''': '''offline'''}      )
				def 	__snake_case							(							self	:				int      ):
										snake_case       :     Any =    self.get_auto_remove_tmp_dir()
										snake_case       :     Optional[int] =    F"""
            {self.examples_dir}/pytorch/translation/run_translation_no_trainer.py
            --model_name_or_path sshleifer/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}
            --max_train_steps=50
            --num_warmup_steps=8
            --num_beams=6
            --learning_rate=3e-3
            --per_device_train_batch_size=2
            --per_device_eval_batch_size=1
            --source_lang en_XX
            --target_lang ro_RO
            --checkpointing_steps epoch
            --with_tracking
        """.split()

										run_command(self._launch_args + testargs      )
										snake_case       :     Optional[int] =    get_results(SCREAMING_SNAKE_CASE_      )
										self.assertGreaterEqual(result['''eval_bleu'''],    30      )
										self.assertTrue(os.path.exists(os.path.join(SCREAMING_SNAKE_CASE_,    '''epoch_0'''      )      )      )
										self.assertTrue(os.path.exists(os.path.join(SCREAMING_SNAKE_CASE_,    '''translation_no_trainer'''      )      )      )




				@slow
				def 	__snake_case							(							self	:				Union[str, Any]      ):
										snake_case       :     Any =    logging.StreamHandler(sys.stdout      )
										logger.addHandler(SCREAMING_SNAKE_CASE_      )

										snake_case       :     Union[str, Any] =    self.get_auto_remove_tmp_dir()
										snake_case       :     Dict =    F"""
            {self.examples_dir}/pytorch/semantic-segmentation/run_semantic_segmentation_no_trainer.py
            --dataset_name huggingface/semantic-segmentation-test-sample
            --output_dir {tmp_dir}
            --max_train_steps=10
            --num_warmup_steps=2
            --learning_rate=2e-4
            --per_device_train_batch_size=2
            --per_device_eval_batch_size=1
            --checkpointing_steps epoch
        """.split()

										run_command(self._launch_args + testargs      )
										snake_case       :     List[Any] =    get_results(SCREAMING_SNAKE_CASE_      )
										self.assertGreaterEqual(result['''eval_overall_accuracy'''],    0.10      )




				@mock.patch.dict(os.environ,    {'''WANDB_MODE''': '''offline'''}      )
				def 	__snake_case							(							self	:				Union[str, Any]      ):
										snake_case       :     str =    self.get_auto_remove_tmp_dir()
										snake_case       :     Optional[Any] =    F"""
            {self.examples_dir}/pytorch/image-classification/run_image_classification_no_trainer.py
            --model_name_or_path google/vit-base-patch16-224-in21k
            --dataset_name hf-internal-testing/cats_vs_dogs_sample
            --learning_rate 1e-4
            --per_device_train_batch_size 2
            --per_device_eval_batch_size 1
            --max_train_steps 2
            --train_val_split 0.1
            --seed 42
            --output_dir {tmp_dir}
            --with_tracking
            --checkpointing_steps 1
        """.split()

										if is_cuda_and_apex_available():
																testargs.append('''--fp16'''      )

										run_command(self._launch_args + testargs      )
										snake_case       :     Tuple =    get_results(SCREAMING_SNAKE_CASE_      )
										# The base model scores a 25%
										self.assertGreaterEqual(result['''eval_accuracy'''],    0.6      )
										self.assertTrue(os.path.exists(os.path.join(SCREAMING_SNAKE_CASE_,    '''step_1'''      )      )      )
										self.assertTrue(os.path.exists(os.path.join(SCREAMING_SNAKE_CASE_,    '''image_classification_no_trainer'''      )      )      )

