

'''simple docstring'''





import collections
import inspect
import unittest

from transformers import FocalNetConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_backbone_common import BackboneTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
						import torch
						from torch import nn

						from transformers import (
						    FocalNetBackbone,
						    FocalNetForImageClassification,
						    FocalNetForMaskedImageModeling,
						    FocalNetModel,
						)
						from transformers.models.focalnet.modeling_focalnet import FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST

if is_vision_available():
						from PIL import Image

						from transformers import AutoImageProcessor

class 						a   :




				def __init__(							self	:				Dict,    SCREAMING_SNAKE_CASE_	:				Optional[int],    SCREAMING_SNAKE_CASE_	:				List[str]=13,    SCREAMING_SNAKE_CASE_	:				Union[str, Any]=32,    SCREAMING_SNAKE_CASE_	:				List[str]=2,    SCREAMING_SNAKE_CASE_	:				int=3,    SCREAMING_SNAKE_CASE_	:				str=16,    SCREAMING_SNAKE_CASE_	:				List[Any]=[32, 64, 1_28],    SCREAMING_SNAKE_CASE_	:				Any=[1, 2, 1],    SCREAMING_SNAKE_CASE_	:				List[Any]=[2, 2, 4],    SCREAMING_SNAKE_CASE_	:				Optional[Any]=2,    SCREAMING_SNAKE_CASE_	:				Tuple=2.0,    SCREAMING_SNAKE_CASE_	:				List[str]=True,    SCREAMING_SNAKE_CASE_	:				int=0.0,    SCREAMING_SNAKE_CASE_	:				int=0.0,    SCREAMING_SNAKE_CASE_	:				str=0.1,    SCREAMING_SNAKE_CASE_	:				Optional[Any]="gelu",    SCREAMING_SNAKE_CASE_	:				Any=False,    SCREAMING_SNAKE_CASE_	:				Union[str, Any]=True,    SCREAMING_SNAKE_CASE_	:				Optional[Any]=0.02,    SCREAMING_SNAKE_CASE_	:				Optional[Any]=1e-5,    SCREAMING_SNAKE_CASE_	:				Optional[Any]=True,    SCREAMING_SNAKE_CASE_	:				int=None,    SCREAMING_SNAKE_CASE_	:				Dict=True,    SCREAMING_SNAKE_CASE_	:				List[Any]=10,    SCREAMING_SNAKE_CASE_	:				Dict=8,    SCREAMING_SNAKE_CASE_	:				List[Any]=["stage1", "stage2"],    SCREAMING_SNAKE_CASE_	:				Optional[int]=[1, 2],    ):
										snake_case       :     int =    parent
										snake_case       :     Dict =    batch_size
										snake_case       :     Tuple =    image_size
										snake_case       :     Optional[int] =    patch_size
										snake_case       :     Optional[Any] =    num_channels
										snake_case       :     str =    embed_dim
										snake_case       :     Union[str, Any] =    hidden_sizes
										snake_case       :     Optional[int] =    depths
										snake_case       :     Any =    num_heads
										snake_case       :     List[Any] =    window_size
										snake_case       :     Dict =    mlp_ratio
										snake_case       :     int =    qkv_bias
										snake_case       :     List[Any] =    hidden_dropout_prob
										snake_case       :     List[Any] =    attention_probs_dropout_prob
										snake_case       :     Tuple =    drop_path_rate
										snake_case       :     Optional[Any] =    hidden_act
										snake_case       :     Optional[int] =    use_absolute_embeddings
										snake_case       :     List[Any] =    patch_norm
										snake_case       :     Tuple =    layer_norm_eps
										snake_case       :     int =    initializer_range
										snake_case       :     Dict =    is_training
										snake_case       :     List[Any] =    scope
										snake_case       :     int =    use_labels
										snake_case       :     Tuple =    type_sequence_label_size
										snake_case       :     Optional[Any] =    encoder_stride
										snake_case       :     Dict =    out_features
										snake_case       :     Optional[Any] =    out_indices




				def 	__snake_case							(							self	:				Dict      ):
										snake_case       :     Any =    floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]      )

										snake_case       :     Union[str, Any] =    None
										if self.use_labels:
																snake_case       :     List[str] =    ids_tensor([self.batch_size],    self.type_sequence_label_size      )

										snake_case       :     Dict =    self.get_config()

										return config, pixel_values, labels




				def 	__snake_case							(							self	:				Any      ):
										return FocalNetConfig(
										    image_size=self.image_size,    patch_size=self.patch_size,    num_channels=self.num_channels,    embed_dim=self.embed_dim,    hidden_sizes=self.hidden_sizes,    depths=self.depths,    num_heads=self.num_heads,    window_size=self.window_size,    mlp_ratio=self.mlp_ratio,    qkv_bias=self.qkv_bias,    hidden_dropout_prob=self.hidden_dropout_prob,    attention_probs_dropout_prob=self.attention_probs_dropout_prob,    drop_path_rate=self.drop_path_rate,    hidden_act=self.hidden_act,    use_absolute_embeddings=self.use_absolute_embeddings,    path_norm=self.patch_norm,    layer_norm_eps=self.layer_norm_eps,    initializer_range=self.initializer_range,    encoder_stride=self.encoder_stride,    out_features=self.out_features,    out_indices=self.out_indices,    )




				def 	__snake_case							(							self	:				Dict,    SCREAMING_SNAKE_CASE_	:				Dict,    SCREAMING_SNAKE_CASE_	:				Optional[int],    SCREAMING_SNAKE_CASE_	:				List[Any]      ):
										snake_case       :     List[Any] =    FocalNetModel(config=SCREAMING_SNAKE_CASE_      )
										model.to(SCREAMING_SNAKE_CASE_      )
										model.eval()
										snake_case       :     List[Any] =    model(SCREAMING_SNAKE_CASE_      )

										snake_case       :     str =    ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths      ) - 1))
										snake_case       :     List[str] =    int(config.embed_dim * 2 ** (len(config.depths      ) - 1)      )

										self.parent.assertEqual(result.last_hidden_state.shape,    (self.batch_size, expected_seq_len, expected_dim)      )




				def 	__snake_case							(							self	:				int,    SCREAMING_SNAKE_CASE_	:				int,    SCREAMING_SNAKE_CASE_	:				Optional[Any],    SCREAMING_SNAKE_CASE_	:				List[Any]      ):
										snake_case       :     str =    FocalNetBackbone(config=SCREAMING_SNAKE_CASE_      )
										model.to(SCREAMING_SNAKE_CASE_      )
										model.eval()
										snake_case       :     str =    model(SCREAMING_SNAKE_CASE_      )

										# verify feature maps
										self.parent.assertEqual(len(result.feature_maps      ),    len(config.out_features      )      )
										self.parent.assertListEqual(list(result.feature_maps[0].shape      ),    [self.batch_size, self.image_size, 8, 8]      )

										# verify channels
										self.parent.assertEqual(len(model.channels      ),    len(config.out_features      )      )
										self.parent.assertListEqual(model.channels,    config.hidden_sizes[:-1]      )

										# verify backbone works with out_features=None
										snake_case       :     str =    None
										snake_case       :     int =    FocalNetBackbone(config=SCREAMING_SNAKE_CASE_      )
										model.to(SCREAMING_SNAKE_CASE_      )
										model.eval()
										snake_case       :     Optional[int] =    model(SCREAMING_SNAKE_CASE_      )

										# verify feature maps
										self.parent.assertEqual(len(result.feature_maps      ),    1      )
										self.parent.assertListEqual(list(result.feature_maps[0].shape      ),    [self.batch_size, self.image_size * 2, 4, 4]      )

										# verify channels
										self.parent.assertEqual(len(model.channels      ),    1      )
										self.parent.assertListEqual(model.channels,    [config.hidden_sizes[-1]]      )




				def 	__snake_case							(							self	:				Any,    SCREAMING_SNAKE_CASE_	:				Optional[Any],    SCREAMING_SNAKE_CASE_	:				Optional[Any],    SCREAMING_SNAKE_CASE_	:				Optional[Any]      ):
										snake_case       :     Optional[int] =    FocalNetForMaskedImageModeling(config=SCREAMING_SNAKE_CASE_      )
										model.to(SCREAMING_SNAKE_CASE_      )
										model.eval()
										snake_case       :     List[Any] =    model(SCREAMING_SNAKE_CASE_      )
										self.parent.assertEqual(
										    result.reconstruction.shape,    (self.batch_size, self.num_channels, self.image_size, self.image_size)      )

										# test greyscale images
										snake_case       :     Optional[int] =    1
										snake_case       :     int =    FocalNetForMaskedImageModeling(SCREAMING_SNAKE_CASE_      )
										model.to(SCREAMING_SNAKE_CASE_      )
										model.eval()

										snake_case       :     Any =    floats_tensor([self.batch_size, 1, self.image_size, self.image_size]      )
										snake_case       :     Any =    model(SCREAMING_SNAKE_CASE_      )
										self.parent.assertEqual(result.reconstruction.shape,    (self.batch_size, 1, self.image_size, self.image_size)      )




				def 	__snake_case							(							self	:				List[str],    SCREAMING_SNAKE_CASE_	:				List[Any],    SCREAMING_SNAKE_CASE_	:				Optional[int],    SCREAMING_SNAKE_CASE_	:				Dict      ):
										snake_case       :     Union[str, Any] =    self.type_sequence_label_size
										snake_case       :     str =    FocalNetForImageClassification(SCREAMING_SNAKE_CASE_      )
										model.to(SCREAMING_SNAKE_CASE_      )
										model.eval()
										snake_case       :     Optional[int] =    model(SCREAMING_SNAKE_CASE_,    labels=SCREAMING_SNAKE_CASE_      )
										self.parent.assertEqual(result.logits.shape,    (self.batch_size, self.type_sequence_label_size)      )

										# test greyscale images
										snake_case       :     Tuple =    1
										snake_case       :     Any =    FocalNetForImageClassification(SCREAMING_SNAKE_CASE_      )
										model.to(SCREAMING_SNAKE_CASE_      )
										model.eval()

										snake_case       :     Any =    floats_tensor([self.batch_size, 1, self.image_size, self.image_size]      )
										snake_case       :     Tuple =    model(SCREAMING_SNAKE_CASE_      )
										self.parent.assertEqual(result.logits.shape,    (self.batch_size, self.type_sequence_label_size)      )




				def 	__snake_case							(							self	:				Optional[Any]      ):
										snake_case       :     Optional[Any] =    self.prepare_config_and_inputs()

										snake_case       :     Tuple =    config_and_inputs
										snake_case       :     str =    {'''pixel_values''': pixel_values}
										return config, inputs_dict




@require_torch
class 						a   (				__magic_name__				,__magic_name__				,unittest.TestCase    ):
				_snake_case		    = (
				    (
				        FocalNetModel,
				        FocalNetForImageClassification,
				        FocalNetForMaskedImageModeling,
				        FocalNetBackbone,
				    )
				    if is_torch_available()
				    else ()
				)
				_snake_case		    = (
				    {'''feature-extraction''': FocalNetModel, '''image-classification''': FocalNetForImageClassification}
				    if is_torch_available()
				    else {}
				)
				_snake_case		    = False

				_snake_case		    = False
				_snake_case		    = False
				_snake_case		    = False
				_snake_case		    = False




				def 	__snake_case							(							self	:				Optional[Any]      ):
										snake_case       :     str =    FocalNetModelTester(self      )
										snake_case       :     Union[str, Any] =    ConfigTester(self,    config_class=SCREAMING_SNAKE_CASE_,    embed_dim=37,    has_text_modality=SCREAMING_SNAKE_CASE_      )




				def 	__snake_case							(							self	:				Union[str, Any]      ):
										self.create_and_test_config_common_properties()
										self.config_tester.create_and_test_config_to_json_string()
										self.config_tester.create_and_test_config_to_json_file()
										self.config_tester.create_and_test_config_from_and_save_pretrained()
										self.config_tester.create_and_test_config_with_num_labels()
										self.config_tester.check_config_can_be_init_without_params()
										self.config_tester.check_config_arguments_init()




				def 	__snake_case							(							self	:				Union[str, Any]      ):
										return




				def 	__snake_case							(							self	:				Optional[Any]      ):
										snake_case       :     Any =    self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_      )




				def 	__snake_case							(							self	:				Tuple      ):
										snake_case       :     Any =    self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_backbone(*SCREAMING_SNAKE_CASE_      )




				def 	__snake_case							(							self	:				List[str]      ):
										snake_case       :     int =    self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_masked_image_modeling(*SCREAMING_SNAKE_CASE_      )




				def 	__snake_case							(							self	:				Any      ):
										snake_case       :     List[str] =    self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_image_classification(*SCREAMING_SNAKE_CASE_      )




				@unittest.skip(reason='''FocalNet does not use inputs_embeds'''      )
				def 	__snake_case							(							self	:				int      ):
										pass




				@unittest.skip(reason='''FocalNet does not use feedforward chunking'''      )
				def 	__snake_case							(							self	:				Dict      ):
										pass




				def 	__snake_case							(							self	:				List[Any]      ):
										snake_case       :     Optional[Any] =    self.model_tester.prepare_config_and_inputs_for_common()

										for model_class in self.all_model_classes[:-1]:
																snake_case       :     List[Any] =    model_class(SCREAMING_SNAKE_CASE_      )
																self.assertIsInstance(model.get_input_embeddings(),    (nn.Module)      )
																snake_case       :     Tuple =    model.get_output_embeddings()
																self.assertTrue(x is None or isinstance(SCREAMING_SNAKE_CASE_,    nn.Linear      )      )




				def 	__snake_case							(							self	:				Any      ):
										snake_case       :     Tuple =    self.model_tester.prepare_config_and_inputs_for_common()

										for model_class in self.all_model_classes[:-1]:
																snake_case       :     Any =    model_class(SCREAMING_SNAKE_CASE_      )
																snake_case       :     Optional[Any] =    inspect.signature(model.forward      )
																# signature.parameters is an OrderedDict => so arg_names order is deterministic
																snake_case       :     Union[str, Any] =    [*signature.parameters.keys()]

																snake_case       :     Optional[Any] =    ['''pixel_values''']
																self.assertListEqual(arg_names[:1],    SCREAMING_SNAKE_CASE_      )




				def 	__snake_case							(							self	:				Union[str, Any],    SCREAMING_SNAKE_CASE_	:				Union[str, Any],    SCREAMING_SNAKE_CASE_	:				Optional[Any],    SCREAMING_SNAKE_CASE_	:				Any,    SCREAMING_SNAKE_CASE_	:				Dict      ):
										snake_case       :     Optional[Any] =    model_class(SCREAMING_SNAKE_CASE_      )
										model.to(SCREAMING_SNAKE_CASE_      )
										model.eval()

										with torch.no_grad():
																snake_case       :     Dict =    model(**self._prepare_for_class(SCREAMING_SNAKE_CASE_,    SCREAMING_SNAKE_CASE_      )      )

										snake_case       :     Dict =    outputs.hidden_states

										snake_case       :     Dict =    getattr(
										    self.model_tester,    '''expected_num_hidden_layers''',    len(self.model_tester.depths      ) + 1      )
										self.assertEqual(len(SCREAMING_SNAKE_CASE_      ),    SCREAMING_SNAKE_CASE_      )

										# FocalNet has a different seq_length
										snake_case       :     Optional[int] =    (
										    config.patch_size
										    if isinstance(config.patch_size,    collections.abc.Iterable      )
										    else (config.patch_size, config.patch_size)
										)

										snake_case       :     Tuple =    (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])

										self.assertListEqual(
										    list(hidden_states[0].shape[-2:]      ),    [num_patches, self.model_tester.embed_dim],    )

										snake_case       :     Tuple =    outputs.reshaped_hidden_states
										self.assertEqual(len(SCREAMING_SNAKE_CASE_      ),    SCREAMING_SNAKE_CASE_      )

										snake_case       :     List[Any] =    reshaped_hidden_states[0].shape
										snake_case       :     Union[str, Any] =    (
										    reshaped_hidden_states[0].view(SCREAMING_SNAKE_CASE_,    SCREAMING_SNAKE_CASE_,    height * width      ).permute(0,    2,    1      )
										)
										self.assertListEqual(
										    list(reshaped_hidden_states.shape[-2:]      ),    [num_patches, self.model_tester.embed_dim],    )




				def 	__snake_case							(							self	:				List[Any]      ):
										snake_case       :     Optional[Any] =    self.model_tester.prepare_config_and_inputs_for_common()

										snake_case       :     Tuple =    (
										    self.model_tester.image_size
										    if isinstance(self.model_tester.image_size,    collections.abc.Iterable      )
										    else (self.model_tester.image_size, self.model_tester.image_size)
										)

										for model_class in self.all_model_classes[:-1]:
																snake_case       :     Any =    True
																self.check_hidden_states_output(SCREAMING_SNAKE_CASE_,    SCREAMING_SNAKE_CASE_,    SCREAMING_SNAKE_CASE_,    SCREAMING_SNAKE_CASE_      )

																# check that output_hidden_states also work using config
																del inputs_dict["output_hidden_states"]
																snake_case       :     str =    True

																self.check_hidden_states_output(SCREAMING_SNAKE_CASE_,    SCREAMING_SNAKE_CASE_,    SCREAMING_SNAKE_CASE_,    SCREAMING_SNAKE_CASE_      )




				def 	__snake_case							(							self	:				str      ):
										snake_case       :     Tuple =    self.model_tester.prepare_config_and_inputs_for_common()
										snake_case       :     int =    3

										snake_case       :     Tuple =    (
										    self.model_tester.image_size
										    if isinstance(self.model_tester.image_size,    collections.abc.Iterable      )
										    else (self.model_tester.image_size, self.model_tester.image_size)
										)
										snake_case       :     List[Any] =    (
										    config.patch_size
										    if isinstance(config.patch_size,    collections.abc.Iterable      )
										    else (config.patch_size, config.patch_size)
										)

										snake_case       :     int =    image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
										snake_case       :     str =    image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])

										for model_class in self.all_model_classes[:-1]:
																snake_case       :     Optional[int] =    True
																self.check_hidden_states_output(SCREAMING_SNAKE_CASE_,    SCREAMING_SNAKE_CASE_,    SCREAMING_SNAKE_CASE_,    (padded_height, padded_width)      )

																# check that output_hidden_states also work using config
																del inputs_dict["output_hidden_states"]
																snake_case       :     Optional[Any] =    True
																self.check_hidden_states_output(SCREAMING_SNAKE_CASE_,    SCREAMING_SNAKE_CASE_,    SCREAMING_SNAKE_CASE_,    (padded_height, padded_width)      )




				@slow
				def 	__snake_case							(							self	:				Optional[Any]      ):
										for model_name in FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																snake_case       :     Any =    FocalNetModel.from_pretrained(SCREAMING_SNAKE_CASE_      )
																self.assertIsNotNone(SCREAMING_SNAKE_CASE_      )




				def 	__snake_case							(							self	:				Any      ):
										snake_case       :     str =    self.model_tester.prepare_config_and_inputs_for_common()

										snake_case       :     Tuple =    _config_zero_init(SCREAMING_SNAKE_CASE_      )
										for model_class in self.all_model_classes:
																snake_case       :     str =    model_class(config=SCREAMING_SNAKE_CASE_      )
																for name, param in model.named_parameters():
																						if "embeddings" not in name and param.requires_grad:
																												self.assertIn(
																												    ((param.data.mean() * 1e9).round() / 1e9).item(),    [0.0, 1.0],    msg=F"""Parameter {name} of model {model_class} seems not properly initialized""",    )




@require_vision
@require_torch
class 						a   (				unittest.TestCase    ):




				@cached_property
				def 	__snake_case							(							self	:				Optional[int]      ):
										# TODO update organization
										return AutoImageProcessor.from_pretrained('''microsoft/focalnet-tiny'''      ) if is_vision_available() else None




				@slow
				def 	__snake_case							(							self	:				List[str]      ):
										snake_case       :     Dict =    FocalNetForImageClassification.from_pretrained('''microsoft/focalnet-tiny'''      ).to(SCREAMING_SNAKE_CASE_      )
										snake_case       :     Union[str, Any] =    self.default_image_processor

										snake_case       :     Dict =    Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''      )
										snake_case       :     Tuple =    image_processor(images=SCREAMING_SNAKE_CASE_,    return_tensors='''pt'''      ).to(SCREAMING_SNAKE_CASE_      )

										# forward pass
										with torch.no_grad():
																snake_case       :     List[str] =    model(**SCREAMING_SNAKE_CASE_      )

										# verify the logits
										snake_case       :     str =    torch.Size((1, 10_00)      )
										self.assertEqual(outputs.logits.shape,    SCREAMING_SNAKE_CASE_      )
										snake_case       :     Any =    torch.tensor([0.2166, -0.4368, 0.2191]      ).to(SCREAMING_SNAKE_CASE_      )
										self.assertTrue(torch.allclose(outputs.logits[0, :3],    SCREAMING_SNAKE_CASE_,    atol=1e-4      )      )
										self.assertTrue(outputs.logits.argmax(dim=-1      ).item(),    2_81      )




@require_torch
class 						a   (				__magic_name__				,unittest.TestCase    ):
				_snake_case		    = (FocalNetBackbone,) if is_torch_available() else ()
				_snake_case		    = FocalNetConfig

				_snake_case		    = False




				def 	__snake_case							(							self	:				Dict      ):
										snake_case       :     Tuple =    FocalNetModelTester(self      )



'''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'''      )      )      )

