






import gc
import unittest

import torch
from parameterized import parameterized

from diffusers import AutoencoderKL
from diffusers.utils import floats_tensor, load_hf_numpy, require_torch_gpu, slow, torch_all_close, torch_device
from diffusers.utils.import_utils import is_xformers_available
from diffusers.utils.testing_utils import enable_full_determinism

from .test_modeling_common import ModelTesterMixin, UNetTesterMixin


enable_full_determinism()






class 		lowercase_					(	lowercase ,  lowercase ,  unittest.TestCase   ):






      '''simple docstring'''




      __snake_case       =  AutoencoderKL
      __snake_case       =  '''sample'''
      __snake_case       =  1e-2







      @property
      def       __lowerCAmelCase					(      self      :						Union[str, Any]  )    ->List[str]:




       """simple docstring"""


       a		  =      4
       a		  =      3
       a		  =      (32, 32)

       a		  =      floats_tensor((batch_size, num_channels) + sizes  ).to(__UpperCAmelCase  )

       return {"sample": image}







      @property
      def       __lowerCAmelCase					(      self      :						Union[str, Any]  )    ->Any:




       """simple docstring"""


       return (3, 32, 32)







      @property
      def       __lowerCAmelCase					(      self      :						int  )    ->List[Any]:




       """simple docstring"""


       return (3, 32, 32)







      def       __lowerCAmelCase					(      self      :						Union[str, Any]  )    ->List[str]:




       """simple docstring"""


       a		  =      {
           '''block_out_channels''': [32, 64],
           '''in_channels''': 3,
           '''out_channels''': 3,
           '''down_block_types''': ['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''],
           '''up_block_types''': ['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''],
           '''latent_channels''': 4,
       }
       a		  =      self.dummy_input
       return init_dict, inputs_dict







      def       __lowerCAmelCase					(      self      :						Dict  )    ->Optional[Any]:




       """simple docstring"""


       pass







      def       __lowerCAmelCase					(      self      :						List[Any]  )    ->Any:




       """simple docstring"""


       pass







      @unittest.skipIf(torch_device == '''mps''' ,					'''Gradient checkpointing skipped on MPS'''  )
      def       __lowerCAmelCase					(      self      :						Optional[Any]  )    ->Optional[int]:




       """simple docstring"""


       a  ,     a		  =      self.prepare_init_args_and_inputs_for_common()
       a		  =      self.model_class(**__UpperCAmelCase  )
       model.to(__UpperCAmelCase  )

       assert not model.is_gradient_checkpointing and model.training

       a		  =      model(**__UpperCAmelCase  ).sample
       # run the backwards pass on the model. For backwards pass, for simplicity purpose,
       # we won't calculate the loss and rather backprop on out.sum()
       model.zero_grad()

       a		  =      torch.randn_like(__UpperCAmelCase  )
       a		  =      (out - labels).mean()
       loss.backward()

       # re-instantiate the model now enabling gradient checkpointing
       a		  =      self.model_class(**__UpperCAmelCase  )
       # clone model
       model_a.load_state_dict(model.state_dict()  )
       model_a.to(__UpperCAmelCase  )
       model_a.enable_gradient_checkpointing()

       assert model_a.is_gradient_checkpointing and model_a.training

       a		  =      model_a(**__UpperCAmelCase  ).sample
       # run the backwards pass on the model. For backwards pass, for simplicity purpose,
       # we won't calculate the loss and rather backprop on out.sum()
       model_a.zero_grad()
       a		  =      (out_a - labels).mean()
       loss_a.backward()

       # compare the output and parameters gradients
       self.assertTrue((loss - loss_a).abs() < 1e-5  )
       a		  =      dict(model.named_parameters()  )
       a		  =      dict(model_a.named_parameters()  )
       for name, param in named_params.items():
        self.assertTrue(torch_all_close(param.grad.data ,					named_params_a[name].grad.data ,					atol=5e-5  )  )







      def       __lowerCAmelCase					(      self      :						Optional[int]  )    ->Optional[Any]:




       """simple docstring"""


       a  ,     a		  =      AutoencoderKL.from_pretrained('''fusing/autoencoder-kl-dummy''' ,					output_loading_info=__UpperCAmelCase  )
       self.assertIsNotNone(__UpperCAmelCase  )
       self.assertEqual(len(loading_info['''missing_keys''']  ) ,					0  )

       model.to(__UpperCAmelCase  )
       a		  =      model(**self.dummy_input  )

       assert image is not None, "Make sure output is not None"







      def       __lowerCAmelCase					(      self      :						Union[str, Any]  )    ->Union[str, Any]:




       """simple docstring"""


       a		  =      AutoencoderKL.from_pretrained('''fusing/autoencoder-kl-dummy'''  )
       a		  =      model.to(__UpperCAmelCase  )
       model.eval()

       if torch_device == "mps":
        a		  =      torch.manual_seed(0  )
       else:
        a		  =      torch.Generator(device=__UpperCAmelCase  ).manual_seed(0  )

       a		  =      torch.randn(
           1 ,					model.config.in_channels ,					model.config.sample_size ,					model.config.sample_size ,					generator=torch.manual_seed(0  ) ,					)
       a		  =      image.to(__UpperCAmelCase  )
       with torch.no_grad():
        a		  =      model(__UpperCAmelCase ,					sample_posterior=__UpperCAmelCase ,					generator=__UpperCAmelCase  ).sample

       a		  =      output[0, -1, -3:, -3:].flatten().cpu()

       # Since the VAE Gaussian prior's generator is seeded on the appropriate device,
       # the expected output slices are not the same for CPU and GPU.
       if torch_device == "mps":
        a		  =      torch.tensor(
            [
                -4.0_0_7_8e-0_1,
                -3.8_3_2_3e-0_4,
                -1.2_6_8_1e-0_1,
                -1.1_4_6_2e-0_1,
                2.0_0_9_5e-0_1,
                1.0_8_9_3e-0_1,
                -8.8_2_4_7e-0_2,
                -3.0_3_6_1e-0_1,
                -9.8_6_4_4e-0_3,
            ]  )
       elif torch_device == "cpu":
        a		  =      torch.tensor(
            [-0.1352, 0.0878, 0.0419, -0.0818, -0.1069, 0.0688, -0.1458, -0.4446, -0.0026]  )
       else:
        a		  =      torch.tensor(
            [-0.2421, 0.4642, 0.2507, -0.0438, 0.0682, 0.3160, -0.2018, -0.0727, 0.2485]  )

       self.assertTrue(torch_all_close(__UpperCAmelCase ,					__UpperCAmelCase ,					rtol=1e-2  )  )






@slow
class 		lowercase_					(	unittest.TestCase   ):






      '''simple docstring'''




      def       __lowerCAmelCase					(      self      :						Dict ,					__UpperCAmelCase      :						Union[str, Any] ,					__UpperCAmelCase      :						Tuple  )    ->str:




       """simple docstring"""


       return F"""gaussian_noise_s={seed}_shape={'_'.join([str(__UpperCAmelCase  ) for s in shape]  )}.npy"""







      def       __lowerCAmelCase					(      self      :						List[str]  )    ->int:




       """simple docstring"""


       super().tearDown()
       gc.collect()
       torch.cuda.empty_cache()







      def       __lowerCAmelCase					(      self      :						Union[str, Any] ,					__UpperCAmelCase      :						Tuple=0 ,					__UpperCAmelCase      :						Tuple=(4, 3, 512, 512) ,					__UpperCAmelCase      :						Optional[int]=False  )    ->Dict:




       """simple docstring"""


       a		  =      torch.floataa if fpaa else torch.floataa
       a		  =      torch.from_numpy(load_hf_numpy(self.get_file_format(__UpperCAmelCase ,					__UpperCAmelCase  )  )  ).to(__UpperCAmelCase  ).to(__UpperCAmelCase  )
       return image







      def       __lowerCAmelCase					(      self      :						Tuple ,					__UpperCAmelCase      :						List[Any]="CompVis/stable-diffusion-v1-4" ,					__UpperCAmelCase      :						Optional[Any]=False  )    ->Dict:




       """simple docstring"""


       a		  =      '''fp16''' if fpaa else None
       a		  =      torch.floataa if fpaa else torch.floataa

       a		  =      AutoencoderKL.from_pretrained(
           __UpperCAmelCase ,					subfolder='''vae''' ,					torch_dtype=__UpperCAmelCase ,					revision=__UpperCAmelCase ,					)
       model.to(__UpperCAmelCase  ).eval()

       return model







      def       __lowerCAmelCase					(      self      :						Union[str, Any] ,					__UpperCAmelCase      :						Tuple=0  )    ->int:




       """simple docstring"""


       if torch_device == "mps":
        return torch.manual_seed(__UpperCAmelCase  )
       return torch.Generator(device=__UpperCAmelCase  ).manual_seed(__UpperCAmelCase  )







      @parameterized.expand(
          [
              # fmt: off
              [33, [-0.1603, 0.9878, -0.0495, -0.0790, -0.2709, 0.8375, -0.2060, -0.0824], [-0.2395, 0.0098, 0.0102, -0.0709, -0.2840, -0.0274, -0.0718, -0.1824]],
              [47, [-0.2376, 0.1168, 0.1332, -0.4840, -0.2508, -0.0791, -0.0493, -0.4089], [0.0350, 0.0847, 0.0467, 0.0344, -0.0842, -0.0547, -0.0633, -0.1131]],
              # fmt: on
          ]  )
      def       __lowerCAmelCase					(      self      :						Tuple ,					__UpperCAmelCase      :						Tuple ,					__UpperCAmelCase      :						Dict ,					__UpperCAmelCase      :						List[str]  )    ->List[str]:




       """simple docstring"""


       a		  =      self.get_sd_vae_model()
       a		  =      self.get_sd_image(__UpperCAmelCase  )
       a		  =      self.get_generator(__UpperCAmelCase  )

       with torch.no_grad():
        a		  =      model(__UpperCAmelCase ,					generator=__UpperCAmelCase ,					sample_posterior=__UpperCAmelCase  ).sample

       assert sample.shape == image.shape

       a		  =      sample[-1, -2:, -2:, :2].flatten().float().cpu()
       a		  =      torch.tensor(expected_slice_mps if torch_device == '''mps''' else expected_slice  )

       assert torch_all_close(__UpperCAmelCase ,					__UpperCAmelCase ,					atol=3e-3  )







      @parameterized.expand(
          [
              # fmt: off
              [33, [-0.0513, 0.0289, 1.3799, 0.2166, -0.2573, -0.0871, 0.5103, -0.0999]],
              [47, [-0.4128, -0.1320, -0.3704, 0.1965, -0.4116, -0.2332, -0.3340, 0.2247]],
              # fmt: on
          ]  )
      @require_torch_gpu
      def       __lowerCAmelCase					(      self      :						Tuple ,					__UpperCAmelCase      :						Tuple ,					__UpperCAmelCase      :						Tuple  )    ->List[Any]:




       """simple docstring"""


       a		  =      self.get_sd_vae_model(fpaa=__UpperCAmelCase  )
       a		  =      self.get_sd_image(__UpperCAmelCase ,					fpaa=__UpperCAmelCase  )
       a		  =      self.get_generator(__UpperCAmelCase  )

       with torch.no_grad():
        a		  =      model(__UpperCAmelCase ,					generator=__UpperCAmelCase ,					sample_posterior=__UpperCAmelCase  ).sample

       assert sample.shape == image.shape

       a		  =      sample[-1, -2:, :2, -2:].flatten().float().cpu()
       a		  =      torch.tensor(__UpperCAmelCase  )

       assert torch_all_close(__UpperCAmelCase ,					__UpperCAmelCase ,					atol=1e-2  )







      @parameterized.expand(
          [
              # fmt: off
              [33, [-0.1609, 0.9866, -0.0487, -0.0777, -0.2716, 0.8368, -0.2055, -0.0814], [-0.2395, 0.0098, 0.0102, -0.0709, -0.2840, -0.0274, -0.0718, -0.1824]],
              [47, [-0.2377, 0.1147, 0.1333, -0.4841, -0.2506, -0.0805, -0.0491, -0.4085], [0.0350, 0.0847, 0.0467, 0.0344, -0.0842, -0.0547, -0.0633, -0.1131]],
              # fmt: on
          ]  )
      def       __lowerCAmelCase					(      self      :						str ,					__UpperCAmelCase      :						str ,					__UpperCAmelCase      :						int ,					__UpperCAmelCase      :						int  )    ->List[str]:




       """simple docstring"""


       a		  =      self.get_sd_vae_model()
       a		  =      self.get_sd_image(__UpperCAmelCase  )

       with torch.no_grad():
        a		  =      model(__UpperCAmelCase  ).sample

       assert sample.shape == image.shape

       a		  =      sample[-1, -2:, -2:, :2].flatten().float().cpu()
       a		  =      torch.tensor(expected_slice_mps if torch_device == '''mps''' else expected_slice  )

       assert torch_all_close(__UpperCAmelCase ,					__UpperCAmelCase ,					atol=3e-3  )







      @parameterized.expand(
          [
              # fmt: off
              [13, [-0.2051, -0.1803, -0.2311, -0.2114, -0.3292, -0.3574, -0.2953, -0.3323]],
              [37, [-0.2632, -0.2625, -0.2199, -0.2741, -0.4539, -0.4990, -0.3720, -0.4925]],
              # fmt: on
          ]  )
      @require_torch_gpu
      def       __lowerCAmelCase					(      self      :						List[str] ,					__UpperCAmelCase      :						Any ,					__UpperCAmelCase      :						List[Any]  )    ->Dict:




       """simple docstring"""


       a		  =      self.get_sd_vae_model()
       a		  =      self.get_sd_image(__UpperCAmelCase ,					shape=(3, 4, 64, 64)  )

       with torch.no_grad():
        a		  =      model.decode(__UpperCAmelCase  ).sample

       assert list(sample.shape  ) == [3, 3, 512, 512]

       a		  =      sample[-1, -2:, :2, -2:].flatten().cpu()
       a		  =      torch.tensor(__UpperCAmelCase  )

       assert torch_all_close(__UpperCAmelCase ,					__UpperCAmelCase ,					atol=1e-3  )







      @parameterized.expand(
          [
              # fmt: off
              [27, [-0.0369, 0.0207, -0.0776, -0.0682, -0.1747, -0.1930, -0.1465, -0.2039]],
              [16, [-0.1628, -0.2134, -0.2747, -0.2642, -0.3774, -0.4404, -0.3687, -0.4277]],
              # fmt: on
          ]  )
      @require_torch_gpu
      def       __lowerCAmelCase					(      self      :						Tuple ,					__UpperCAmelCase      :						Optional[Any] ,					__UpperCAmelCase      :						Any  )    ->int:




       """simple docstring"""


       a		  =      self.get_sd_vae_model(fpaa=__UpperCAmelCase  )
       a		  =      self.get_sd_image(__UpperCAmelCase ,					shape=(3, 4, 64, 64) ,					fpaa=__UpperCAmelCase  )

       with torch.no_grad():
        a		  =      model.decode(__UpperCAmelCase  ).sample

       assert list(sample.shape  ) == [3, 3, 512, 512]

       a		  =      sample[-1, -2:, :2, -2:].flatten().float().cpu()
       a		  =      torch.tensor(__UpperCAmelCase  )

       assert torch_all_close(__UpperCAmelCase ,					__UpperCAmelCase ,					atol=5e-3  )







      @parameterized.expand([(13,), (16,), (27,)]  )
      @require_torch_gpu
      @unittest.skipIf(not is_xformers_available() ,					reason='''xformers is not required when using PyTorch 2.0.'''  )
      def       __lowerCAmelCase					(      self      :						Dict ,					__UpperCAmelCase      :						int  )    ->List[str]:




       """simple docstring"""


       a		  =      self.get_sd_vae_model(fpaa=__UpperCAmelCase  )
       a		  =      self.get_sd_image(__UpperCAmelCase ,					shape=(3, 4, 64, 64) ,					fpaa=__UpperCAmelCase  )

       with torch.no_grad():
        a		  =      model.decode(__UpperCAmelCase  ).sample

       model.enable_xformers_memory_efficient_attention()
       with torch.no_grad():
        a		  =      model.decode(__UpperCAmelCase  ).sample

       assert list(sample.shape  ) == [3, 3, 512, 512]

       assert torch_all_close(__UpperCAmelCase ,					__UpperCAmelCase ,					atol=1e-1  )







      @parameterized.expand([(13,), (16,), (37,)]  )
      @require_torch_gpu
      @unittest.skipIf(not is_xformers_available() ,					reason='''xformers is not required when using PyTorch 2.0.'''  )
      def       __lowerCAmelCase					(      self      :						int ,					__UpperCAmelCase      :						str  )    ->Any:




       """simple docstring"""


       a		  =      self.get_sd_vae_model()
       a		  =      self.get_sd_image(__UpperCAmelCase ,					shape=(3, 4, 64, 64)  )

       with torch.no_grad():
        a		  =      model.decode(__UpperCAmelCase  ).sample

       model.enable_xformers_memory_efficient_attention()
       with torch.no_grad():
        a		  =      model.decode(__UpperCAmelCase  ).sample

       assert list(sample.shape  ) == [3, 3, 512, 512]

       assert torch_all_close(__UpperCAmelCase ,					__UpperCAmelCase ,					atol=1e-2  )







      @parameterized.expand(
          [
              # fmt: off
              [33, [-0.3001, 0.0918, -2.6984, -3.9720, -3.2099, -5.0353, 1.7338, -0.2065, 3.4267]],
              [47, [-1.5030, -4.3871, -6.0355, -9.1157, -1.6661, -2.7853, 2.1607, -5.0823, 2.5633]],
              # fmt: on
          ]  )
      def       __lowerCAmelCase					(      self      :						Optional[int] ,					__UpperCAmelCase      :						List[Any] ,					__UpperCAmelCase      :						Union[str, Any]  )    ->List[str]:




       """simple docstring"""


       a		  =      self.get_sd_vae_model()
       a		  =      self.get_sd_image(__UpperCAmelCase  )
       a		  =      self.get_generator(__UpperCAmelCase  )

       with torch.no_grad():
        a		  =      model.encode(__UpperCAmelCase  ).latent_dist
        a		  =      dist.sample(generator=__UpperCAmelCase  )

       assert list(sample.shape  ) == [image.shape[0], 4] + [i // 8 for i in image.shape[2:]]

       a		  =      sample[0, -1, -3:, -3:].flatten().cpu()
       a		  =      torch.tensor(__UpperCAmelCase  )

       a		  =      3e-3 if torch_device != '''mps''' else 1e-2
       assert torch_all_close(__UpperCAmelCase ,					__UpperCAmelCase ,					atol=__UpperCAmelCase  )










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    (      )							->			Optional[int]:
 a		  =      argparse.ArgumentParser()
 parser.add_argument('''-f''' )
 a		  =      parser.parse_args()
 return args.f
def 						_a    (      a :Any )							->			Tuple:
 a		  =      {}
 a		  =      os.path.join(a	,							'''all_results.json''' )
 if os.path.exists(a ):
  with open(a	,							'''r''' ) as f:
   a		  =      json.load(a )
 else:
  raise ValueError(F"""can't find {path}""" )
 return results
def 						_a    (      )							->			int:
 a		  =      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 		lowercase_					(	lowercase   ):






      '''simple docstring'''




      @classmethod
      def       __lowerCAmelCase					(      cls      :						str  )    ->Tuple:




       """simple docstring"""


       a		  =      tempfile.mkdtemp()
       a		  =      os.path.join(cls.tmpdir ,					'''default_config.yml'''  )
       write_basic_config(save_location=cls.configPath  )
       a		  =      ['''accelerate''', '''launch''', '''--config_file''', cls.configPath]







      @classmethod
      def       __lowerCAmelCase					(      cls      :						Optional[int]  )    ->Union[str, Any]:




       """simple docstring"""


       shutil.rmtree(cls.tmpdir  )







      @mock.patch.dict(os.environ ,					{'''WANDB_MODE''': '''offline'''}  )
      def       __lowerCAmelCase					(      self      :						List[Any]  )    ->List[str]:




       """simple docstring"""


       a		  =      self.get_auto_remove_tmp_dir()
       a		  =      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  )
       a		  =      get_results(__UpperCAmelCase  )
       self.assertGreaterEqual(result['''eval_accuracy'''] ,					0.75  )
       self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase ,					'''epoch_0'''  )  )  )
       self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase ,					'''glue_no_trainer'''  )  )  )







      @mock.patch.dict(os.environ ,					{'''WANDB_MODE''': '''offline'''}  )
      def       __lowerCAmelCase					(      self      :						Optional[Any]  )    ->Any:




       """simple docstring"""


       a		  =      self.get_auto_remove_tmp_dir()
       a		  =      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  )
       a		  =      get_results(__UpperCAmelCase  )
       self.assertLess(result['''perplexity'''] ,					100  )
       self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase ,					'''epoch_0'''  )  )  )
       self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase ,					'''clm_no_trainer'''  )  )  )







      @mock.patch.dict(os.environ ,					{'''WANDB_MODE''': '''offline'''}  )
      def       __lowerCAmelCase					(      self      :						Optional[int]  )    ->int:




       """simple docstring"""


       a		  =      self.get_auto_remove_tmp_dir()
       a		  =      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  )
       a		  =      get_results(__UpperCAmelCase  )
       self.assertLess(result['''perplexity'''] ,					42  )
       self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase ,					'''epoch_0'''  )  )  )
       self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase ,					'''mlm_no_trainer'''  )  )  )







      @mock.patch.dict(os.environ ,					{'''WANDB_MODE''': '''offline'''}  )
      def       __lowerCAmelCase					(      self      :						Optional[int]  )    ->str:




       """simple docstring"""


       a		  =      7 if get_gpu_count() > 1 else 2

       a		  =      self.get_auto_remove_tmp_dir()
       a		  =      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  )
       a		  =      get_results(__UpperCAmelCase  )
       self.assertGreaterEqual(result['''eval_accuracy'''] ,					0.75  )
       self.assertLess(result['''train_loss'''] ,					0.5  )
       self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase ,					'''epoch_0'''  )  )  )
       self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase ,					'''ner_no_trainer'''  )  )  )







      @unittest.skip(reason='''Fix me @muellerzr'''  )
      @mock.patch.dict(os.environ ,					{'''WANDB_MODE''': '''offline'''}  )
      def       __lowerCAmelCase					(      self      :						Any  )    ->int:




       """simple docstring"""


       a		  =      self.get_auto_remove_tmp_dir()
       a		  =      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  )
       a		  =      get_results(__UpperCAmelCase  )
       # 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(__UpperCAmelCase ,					'''epoch_0'''  )  )  )
       self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase ,					'''qa_no_trainer'''  )  )  )







      @mock.patch.dict(os.environ ,					{'''WANDB_MODE''': '''offline'''}  )
      def       __lowerCAmelCase					(      self      :						Optional[Any]  )    ->Any:




       """simple docstring"""


       a		  =      self.get_auto_remove_tmp_dir()
       a		  =      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  )
       a		  =      get_results(__UpperCAmelCase  )
       self.assertGreaterEqual(result['''eval_accuracy'''] ,					0.8  )
       self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase ,					'''swag_no_trainer'''  )  )  )







      @slow
      @mock.patch.dict(os.environ ,					{'''WANDB_MODE''': '''offline'''}  )
      def       __lowerCAmelCase					(      self      :						Union[str, Any]  )    ->Union[str, Any]:




       """simple docstring"""


       a		  =      self.get_auto_remove_tmp_dir()
       a		  =      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  )
       a		  =      get_results(__UpperCAmelCase  )
       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(__UpperCAmelCase ,					'''epoch_0'''  )  )  )
       self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase ,					'''summarization_no_trainer'''  )  )  )







      @slow
      @mock.patch.dict(os.environ ,					{'''WANDB_MODE''': '''offline'''}  )
      def       __lowerCAmelCase					(      self      :						Optional[int]  )    ->List[str]:




       """simple docstring"""


       a		  =      self.get_auto_remove_tmp_dir()
       a		  =      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  )
       a		  =      get_results(__UpperCAmelCase  )
       self.assertGreaterEqual(result['''eval_bleu'''] ,					30  )
       self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase ,					'''epoch_0'''  )  )  )
       self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase ,					'''translation_no_trainer'''  )  )  )







      @slow
      def       __lowerCAmelCase					(      self      :						List[str]  )    ->int:




       """simple docstring"""


       a		  =      logging.StreamHandler(sys.stdout  )
       logger.addHandler(__UpperCAmelCase  )

       a		  =      self.get_auto_remove_tmp_dir()
       a		  =      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  )
       a		  =      get_results(__UpperCAmelCase  )
       self.assertGreaterEqual(result['''eval_overall_accuracy'''] ,					0.10  )







      @mock.patch.dict(os.environ ,					{'''WANDB_MODE''': '''offline'''}  )
      def       __lowerCAmelCase					(      self      :						Optional[Any]  )    ->Tuple:




       """simple docstring"""


       a		  =      self.get_auto_remove_tmp_dir()
       a		  =      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  )
       a		  =      get_results(__UpperCAmelCase  )
       # The base model scores a 25%
       self.assertGreaterEqual(result['''eval_accuracy'''] ,					0.6  )
       self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase ,					'''step_1'''  )  )  )
       self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase ,					'''image_classification_no_trainer'''  )  )  )


