

'''simple docstring'''

import math
import os
import re
import sys
import unittest
from pathlib import Path
from typing import Tuple
from unittest.mock import patch

from parameterized import parameterized

from transformers.testing_utils import (
    CaptureStderr,
    ExtendSysPath,
    TestCasePlus,
    execute_subprocess_async,
    get_gpu_count,
    get_torch_dist_unique_port,
    require_apex,
    require_bitsandbytes,
    require_fairscale,
    require_torch,
    require_torch_gpu,
    require_torch_multi_gpu,
    require_torch_non_multi_gpu,
    slow,
)
from transformers.trainer_callback import TrainerState
from transformers.trainer_utils import set_seed


lowercase__			    =			os.path.abspath(os.path.dirname(__file__))
with ExtendSysPath(f'''{bindir}/../../examples/pytorch/translation'''):
 from run_translation import main  # noqa


set_seed(42)
lowercase__			    =			'''sshleifer/student_marian_en_ro_6_1'''
lowercase__			    =			'''sshleifer/tiny-mbart'''




@require_torch
class        A_ (				_snake_case							):






     '''simple docstring'''



     def    UpperCAmelCase_       (		self :     str     ,			lowercase_ :     Optional[int]=False     ,			lowercase_ :     Union[str, Any]=None     ,			lowercase_ :     Optional[int]=True     ,			lowercase_ :     List[str]=True     ,			lowercase_ :     Tuple=True     ,			lowercase_ :     List[str]=True     ,			)						->	List[str]:
      UpperCAmelCase       :	Optional[Any]											= self.run_trainer(
          eval_steps=1     ,			max_len=12     ,			model_name=lowercase_     ,			num_train_epochs=1     ,			distributed=lowercase_     ,			extra_args_str=lowercase_     ,			predict_with_generate=lowercase_     ,			do_train=lowercase_     ,			do_eval=lowercase_     ,			do_predict=lowercase_     ,			)
      UpperCAmelCase       :	Dict											= TrainerState.load_from_json(os.path.join(lowercase_     ,			'trainer_state.json'       )       ).log_history

      if not do_eval:
       return

      UpperCAmelCase       :	Union[str, Any]											= [log for log in logs if 'eval_loss' in log.keys()]

      UpperCAmelCase       :	Optional[Any]											= eval_metrics[0]
      if predict_with_generate:
       assert "eval_bleu" in first_step_stats

       UpperCAmelCase       :	Tuple											= eval_metrics[-1]
       assert isinstance(last_step_stats['eval_bleu']     ,			lowercase_       )
       assert not math.isnan(float(last_step_stats['eval_loss']       )       ), "eval_loss must not be `nan`"


     @require_torch_non_multi_gpu
     def    UpperCAmelCase_       (		self :     Any       )						->	Optional[int]:
      self.run_seqaseq_quick()


     @require_torch_multi_gpu
     def    UpperCAmelCase_       (		self :     List[str]       )						->	Optional[int]:
      self.run_seqaseq_quick(distributed=lowercase_       )


     @require_torch_multi_gpu
     def    UpperCAmelCase_       (		self :     Any       )						->	int:
      self.run_seqaseq_quick(distributed=lowercase_       )


     @unittest.skip('Requires an update of the env running those tests'       )
     @require_torch_multi_gpu
     @require_fairscale
     def    UpperCAmelCase_       (		self :     Dict       )						->	Any:
      self.run_seqaseq_quick(distributed=lowercase_     ,			extra_args_str='--sharded_ddp simple'       )


     @unittest.skip('Requires an update of the env running those tests'       )
     @require_torch_multi_gpu
     @require_fairscale
     def    UpperCAmelCase_       (		self :     Optional[int]       )						->	Optional[int]:
      self.run_seqaseq_quick(distributed=lowercase_     ,			extra_args_str='--sharded_ddp simple --fp16'       )


     @unittest.skip('Requires an update of the env running those tests'       )
     @require_torch_multi_gpu
     @require_fairscale
     def    UpperCAmelCase_       (		self :     List[str]       )						->	List[str]:
      self.run_seqaseq_quick(distributed=lowercase_     ,			extra_args_str='--sharded_ddp zero_dp_2'     ,			predict_with_generate=lowercase_       )


     @unittest.skip('Requires an update of the env running those tests'       )
     @require_torch_multi_gpu
     @require_fairscale
     def    UpperCAmelCase_       (		self :     int       )						->	Dict:
      self.run_seqaseq_quick(
          distributed=lowercase_     ,			extra_args_str='--sharded_ddp zero_dp_2 --fp16'     ,			predict_with_generate=lowercase_       )


     @require_apex
     @require_torch_gpu
     def    UpperCAmelCase_       (		self :     Any       )						->	Any:
      self.run_seqaseq_quick(distributed=lowercase_     ,			extra_args_str='--fp16 --fp16_backend=apex'       )
      # test 2nd time - was getting eval_loss': nan'
      # to reproduce the problem set distributed=False
      self.run_seqaseq_quick(distributed=lowercase_     ,			extra_args_str='--fp16 --fp16_backend=apex'       )


     @parameterized.expand(['base', 'low', 'high', 'mixed']       )
     @require_torch_multi_gpu
     def    UpperCAmelCase_       (		self :     Tuple     ,			lowercase_ :     Any       )						->	Union[str, Any]:
      UpperCAmelCase       :	Optional[int]											= {
          # test with the default log_level - should be info and thus log info once
          'base': {'extra_args_str': '', 'n_matches': 1},
          # test with low log_level and log_level_replica - should be noisy on all processes
          # now the info string should appear twice on 2 processes
          'low': {'extra_args_str': '--log_level debug --log_level_replica debug', 'n_matches': 2},
          # test with high log_level and low log_level_replica
          # now the info string should appear once only on the replica
          'high': {'extra_args_str': '--log_level error --log_level_replica debug', 'n_matches': 1},
          # test with high log_level and log_level_replica - should be quiet on all processes
          'mixed': {'extra_args_str': '--log_level error --log_level_replica error', 'n_matches': 0},
      }

      UpperCAmelCase       :	List[str]											= experiments[experiment_id]
      UpperCAmelCase       :	List[Any]											= {'distributed': True, 'predict_with_generate': False, 'do_eval': False, 'do_predict': False}
      UpperCAmelCase       :	str											= 'Running training'
      with CaptureStderr() as cl:
       self.run_seqaseq_quick(**lowercase_     ,			extra_args_str=data['extra_args_str']       )
      UpperCAmelCase       :	List[Any]											= len(re.findall(lowercase_     ,			cl.err       )       )
      self.assertEqual(lowercase_     ,			data['n_matches']       )


     @slow
     def    UpperCAmelCase_       (		self :     List[Any]       )						->	Optional[int]:
      UpperCAmelCase       :	List[Any]											= self.run_trainer(
          eval_steps=2     ,			max_len=128     ,			model_name=lowercase_     ,			learning_rate=3E-4     ,			num_train_epochs=10     ,			distributed=lowercase_     ,			)

      # Check metrics
      UpperCAmelCase       :	Union[str, Any]											= TrainerState.load_from_json(os.path.join(lowercase_     ,			'trainer_state.json'       )       ).log_history
      UpperCAmelCase       :	Optional[Any]											= [log for log in logs if 'eval_loss' in log.keys()]
      UpperCAmelCase       :	Any											= eval_metrics[0]
      UpperCAmelCase       :	List[str]											= eval_metrics[-1]

      assert first_step_stats["eval_loss"] > last_step_stats["eval_loss"], "model learned nothing"
      assert isinstance(last_step_stats['eval_bleu']     ,			lowercase_       )

      # test if do_predict saves generations and metrics
      UpperCAmelCase       :	List[str]											= os.listdir(lowercase_       )
      UpperCAmelCase       :	List[str]											= {os.path.basename(lowercase_       ) for p in contents}
      assert "generated_predictions.txt" in contents
      assert "predict_results.json" in contents


     @slow
     @require_bitsandbytes
     def    UpperCAmelCase_       (		self :     Tuple       )						->	int:
      from transformers.training_args import OptimizerNames

      def train_and_return_metrics(lowercase_ :     str       ) -> Tuple[int, float]:
       UpperCAmelCase       :	Optional[Any]											= '--skip_memory_metrics 0'

       UpperCAmelCase       :	Tuple											= self.run_trainer(
           max_len=128     ,			model_name=lowercase_     ,			learning_rate=3E-4     ,			num_train_epochs=1     ,			optim=lowercase_     ,			distributed=lowercase_     ,			extra_args_str=lowercase_     ,			do_eval=lowercase_     ,			do_predict=lowercase_     ,			n_gpus_to_use=1     ,			)

       # Check metrics
       UpperCAmelCase       :	int											= TrainerState.load_from_json(Path(lowercase_     ,			'trainer_state.json'       )       ).log_history
       UpperCAmelCase       :	Tuple											= int(logs[0]['train_mem_gpu_peaked_delta'] / 2**20       )
       UpperCAmelCase       :	Union[str, Any]											= int(logs[0]['train_mem_gpu_alloc_delta'] / 2**20       )

       UpperCAmelCase       :	int											= logs[0]['train_loss']
       return gpu_peak_mem_mb, gpu_alloc_mem_mb, loss

      UpperCAmelCase					, UpperCAmelCase					, UpperCAmelCase       :	Optional[Any]											= train_and_return_metrics(OptimizerNames.ADAMW_TORCH.value       )
      UpperCAmelCase					, UpperCAmelCase					, UpperCAmelCase       :	Dict											= train_and_return_metrics(OptimizerNames.ADAMW_BNB.value       )

      UpperCAmelCase       :	List[Any]											= gpu_alloc_mem_orig - gpu_alloc_mem_bnb

      UpperCAmelCase       :	Optional[Any]											= gpu_peak_mem_orig + gpu_alloc_mem_orig
      UpperCAmelCase       :	Optional[int]											= gpu_peak_mem_bnb + gpu_alloc_mem_bnb
      UpperCAmelCase       :	Dict											= gpu_total_mem_orig - gpu_total_mem_bnb

      # sshleifer/student_marian_en_ro_6_1 has 54M parameter, 29M of which is `nn.Embedding` which
      # doesn't get quantized and remains in fp32. Therefore we only have 25M parameters quantized
      # in 2 bytes and the diff in optim memory usage is derived as so:
      #
      # - normal 25*8=~200MB (8 bytes per param)
      # - bnb    25*2= ~50MB (2 bytes per param)
      #
      # Thus we should expect ~150MB total memory saved.
      #
      # Peak memory should be the same - the total should be different by about that same margin
      #
      # After leaving a small margin to accommodate for differences between gpus let's check
      # that we have at least 120MB in savings
      UpperCAmelCase       :	Tuple											= 120

      # uncomment the following if this test starts failing - requires py38 for a new print feature
      # gpu_peak_mem_diff = gpu_peak_mem_orig - gpu_peak_mem_bnb
      # print(f"{gpu_alloc_mem_orig=}MB {gpu_peak_mem_orig=}MB {gpu_alloc_mem_orig+gpu_peak_mem_orig=}MB")
      # print(f" {gpu_alloc_mem_bnb=}MB  {gpu_peak_mem_bnb=}MB  {gpu_alloc_mem_bnb+gpu_peak_mem_bnb=}MB")
      # print(f"{gpu_alloc_mem_diff=}MB")
      # print(f"{gpu_peak_mem_diff=}MB")
      # print(f"{gpu_total_mem_orig=}MB, {gpu_total_mem_bnb=}MB")
      # print(f"{gpu_total_mem_diff=}MB, {gpu_total_mem_diff=}MB")

      self.assertGreater(
          lowercase_     ,			lowercase_     ,			'should use ~150MB less alloc gpu memory with BNB, compared to without it for this model but got'
          f""" a difference of {gpu_alloc_mem_diff}MB, with gpu_alloc_mem_orig={gpu_alloc_mem_orig}MB and"""
          f""" gpu_alloc_mem_bnb={gpu_alloc_mem_bnb}MB"""     ,			)

      self.assertGreater(
          lowercase_     ,			lowercase_     ,			'should use ~150MB less total gpu memory with BNB, compared to without it for this model but got'
          f""" a difference of {gpu_total_mem_diff}MB, with gpu_total_mem_orig={gpu_total_mem_orig}MB and"""
          f""" gpu_total_mem_bnb={gpu_total_mem_bnb}MB"""     ,			)

      self.assertEqual(
          lowercase_     ,			lowercase_     ,			f"""loss should be the same, but got loss_orig={loss_orig}, loss_bnb={loss_bnb}"""       )




     def    UpperCAmelCase_       (		self :     Optional[Any]     ,			lowercase_ :     int     ,			lowercase_ :     str     ,			lowercase_ :     int     ,			lowercase_ :     float = 3E-3     ,			lowercase_ :     str = "adafactor"     ,			lowercase_ :     bool = False     ,			lowercase_ :     str = None     ,			lowercase_ :     int = 0     ,			lowercase_ :     bool = True     ,			lowercase_ :     bool = True     ,			lowercase_ :     bool = True     ,			lowercase_ :     bool = True     ,			lowercase_ :     int = None     ,			)						->	Tuple:
      UpperCAmelCase       :	Tuple											= self.test_file_dir / '../fixtures/tests_samples/wmt_en_ro'
      UpperCAmelCase       :	str											= self.get_auto_remove_tmp_dir()
      UpperCAmelCase       :	Optional[int]											= f"""
            --model_name_or_path {model_name}
            --train_file {data_dir}/train.json
            --validation_file {data_dir}/val.json
            --test_file {data_dir}/test.json
            --output_dir {output_dir}
            --overwrite_output_dir
            --max_train_samples 8
            --max_source_length {max_len}
            --max_target_length {max_len}
            --do_train
            --num_train_epochs {str(lowercase_       )}
            --per_device_train_batch_size 4
            --learning_rate {learning_rate}
            --warmup_steps 8
            --logging_steps 0
            --logging_strategy no
            --save_steps {str(lowercase_       )}
            --group_by_length
            --label_smoothing_factor 0.1
            --target_lang ro_RO
            --source_lang en_XX
        """.split()

      UpperCAmelCase       :	Union[str, Any]											= f"""
            --do_eval
            --per_device_eval_batch_size 4
            --max_eval_samples 8
            --val_max_target_length {max_len}
            --evaluation_strategy steps
            --eval_steps {str(lowercase_       )}
        """.split()

      UpperCAmelCase       :	int											= '\n            --do_predict\n        '.split()

      UpperCAmelCase       :	Optional[int]											= []
      if do_train:
       args += args_train

      if do_eval:
       args += args_eval

      if do_predict:
       args += args_predict

      if predict_with_generate:
       args += "--predict_with_generate".split()

      if do_train:
       if optim == "adafactor":
        args += "--adafactor".split()
       else:
        args += f"""--optim {optim}""".split()

      if extra_args_str is not None:
       args += extra_args_str.split()

      if distributed:
       if n_gpus_to_use is None:
        UpperCAmelCase       :	Any											= get_gpu_count()
       UpperCAmelCase       :	Any											= get_torch_dist_unique_port()
       UpperCAmelCase       :	Union[str, Any]											= f"""
                -m torch.distributed.run
                --nproc_per_node={n_gpus_to_use}
                --master_port={master_port}
                {self.examples_dir_str}/pytorch/translation/run_translation.py
            """.split()
       UpperCAmelCase       :	Union[str, Any]											= [sys.executable] + distributed_args + args
       # keep for quick debug
       # print(" ".join([f"\nPYTHONPATH={self.src_dir_str}"] +cmd)); die
       execute_subprocess_async(lowercase_     ,			env=self.get_env()       )
      else:
       UpperCAmelCase       :	int											= ['run_translation.py'] + args
       with patch.object(lowercase_     ,			'argv'     ,			lowercase_       ):
        main()

      return output_dir






import unittest
from typing import Tuple

import torch

from diffusers.utils import floats_tensor, randn_tensor, torch_all_close, torch_device
from diffusers.utils.testing_utils import require_torch




@require_torch
class    SCREAMING_SNAKE_CASE__     :





	'''simple docstring'''



	@property
	def  A							(  self	:    List[str]	):


				'''simple docstring'''


				return self.get_dummy_input()



	@property
	def  A							(  self	:    Any	):


				'''simple docstring'''


				if self.block_type == "down":
							return (4, 32, 16, 16)
				elif self.block_type == "mid":
							return (4, 32, 32, 32)
				elif self.block_type == "up":
							return (4, 32, 64, 64)

				raise ValueError(f'''\'{self.block_type}\' is not a supported block_type. Set it to \'up\', \'mid\', or \'down\'.'''	)



	def  A							(  self	:    Union[str, Any]			,  lowercase	:    Any=True			,  lowercase	:    List[Any]=False			,  lowercase	:    List[str]=False			,  lowercase	:    Dict=False			,  ):


				'''simple docstring'''


				_snake_case		=			4
				_snake_case		=			32
				_snake_case		=			(32, 32)

				_snake_case		=			torch.manual_seed(0	)
				_snake_case		=			torch.device(lowercase	)
				_snake_case		=			(batch_size, num_channels) + sizes
				_snake_case		=			randn_tensor(lowercase			,  generator=lowercase			,  device=lowercase	)
				_snake_case		=			{'hidden_states': hidden_states}

				if include_temb:
							_snake_case		=			128
							_snake_case		=			randn_tensor((batch_size, temb_channels)			,  generator=lowercase			,  device=lowercase	)

				if include_res_hidden_states_tuple:
							_snake_case		=			torch.manual_seed(1	)
							_snake_case		=			(randn_tensor(lowercase			,  generator=lowercase			,  device=lowercase	),)

				if include_encoder_hidden_states:
							_snake_case		=			floats_tensor((batch_size, 32, 32)	).to(lowercase	)

				if include_skip_sample:
							_snake_case		=			randn_tensor(((batch_size, 3) + sizes)			,  generator=lowercase			,  device=lowercase	)

				return dummy_input



	def  A							(  self	:    Any	):


				'''simple docstring'''


				_snake_case		=			{
				    'in_channels': 32,
				    'out_channels': 32,
				    'temb_channels': 128,
				}
				if self.block_type == "up":
							_snake_case		=			32

				if self.block_type == "mid":
							init_dict.pop('out_channels'	)

				_snake_case		=			self.dummy_input
				return init_dict, inputs_dict



	def  A							(  self	:    Dict			,  lowercase	:    Optional[int]	):


				'''simple docstring'''


				_snake_case	,					_snake_case		=			self.prepare_init_args_and_inputs_for_common()
				_snake_case		=			self.block_class(**lowercase	)
				unet_block.to(lowercase	)
				unet_block.eval()

				with torch.no_grad():
							_snake_case		=			unet_block(**lowercase	)

				if isinstance(lowercase			,  lowercase	):
							_snake_case		=			output[0]

				self.assertEqual(output.shape			,  self.output_shape	)

				_snake_case		=			output[0, -1, -3:, -3:]
				_snake_case		=			torch.tensor(lowercase	).to(lowercase	)
				assert torch_all_close(output_slice.flatten()			,  lowercase			,  atol=5E-3	)





	@unittest.skipIf(torch_device == 'mps'			,  'Training is not supported in mps'	)
	def  A							(  self	:    Dict	):


				'''simple docstring'''


				_snake_case	,					_snake_case		=			self.prepare_init_args_and_inputs_for_common()
				_snake_case		=			self.block_class(**lowercase	)
				model.to(lowercase	)
				model.train()
				_snake_case		=			model(**lowercase	)

				if isinstance(lowercase			,  lowercase	):
							_snake_case		=			output[0]

				_snake_case		=			torch.device(lowercase	)
				_snake_case		=			randn_tensor(output.shape			,  device=lowercase	)
				_snake_case		=			torch.nn.functional.mse_loss(lowercase			,  lowercase	)
				loss.backward()