



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


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


set_seed(4_2)
a_						:     Any	     =		'sshleifer/student_marian_en_ro_6_1'
a_						:     Dict	     =		'sshleifer/tiny-mbart'





@require_torch
class    lowerCamelCase__  (						UpperCAmelCase_):
     """simple docstring"""



     def 						_a      (self				,			__a=False				,			__a=None				,			__a=True				,			__a=True				,			__a=True				,			__a=True				,			):






           '''simple docstring'''



           lowerCamelCase								=		self.run_trainer(
               eval_steps=1				,			max_len=12				,			model_name=__a				,			num_train_epochs=1				,			distributed=__a				,			extra_args_str=__a				,			predict_with_generate=__a				,			do_train=__a				,			do_eval=__a				,			do_predict=__a				,			)
           lowerCamelCase								=		TrainerState.load_from_json(os.path.join(__a				,			"trainer_state.json"    )    ).log_history

           if not do_eval:
                 return

           lowerCamelCase								=		[log for log in logs if "eval_loss" in log.keys()]

           lowerCamelCase								=		eval_metrics[0]
           if predict_with_generate:
                 assert "eval_bleu" in first_step_stats

                 lowerCamelCase								=		eval_metrics[-1]
                 assert isinstance(last_step_stats["eval_bleu"]				,			__a    )
                 assert not math.isnan(float(last_step_stats["eval_loss"]    )    ), "eval_loss must not be `nan`"







     @require_torch_non_multi_gpu
     def 						_a      (self    ):






           '''simple docstring'''



           self.run_seqaseq_quick()







     @require_torch_multi_gpu
     def 						_a      (self    ):






           '''simple docstring'''



           self.run_seqaseq_quick(distributed=__a    )







     @require_torch_multi_gpu
     def 						_a      (self    ):






           '''simple docstring'''



           self.run_seqaseq_quick(distributed=__a    )







     @unittest.skip("Requires an update of the env running those tests"    )
     @require_torch_multi_gpu
     @require_fairscale
     def 						_a      (self    ):






           '''simple docstring'''



           self.run_seqaseq_quick(distributed=__a				,			extra_args_str="--sharded_ddp simple"    )







     @unittest.skip("Requires an update of the env running those tests"    )
     @require_torch_multi_gpu
     @require_fairscale
     def 						_a      (self    ):






           '''simple docstring'''



           self.run_seqaseq_quick(distributed=__a				,			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 						_a      (self    ):






           '''simple docstring'''



           self.run_seqaseq_quick(distributed=__a				,			extra_args_str="--sharded_ddp zero_dp_2"				,			predict_with_generate=__a    )







     @unittest.skip("Requires an update of the env running those tests"    )
     @require_torch_multi_gpu
     @require_fairscale
     def 						_a      (self    ):






           '''simple docstring'''



           self.run_seqaseq_quick(
               distributed=__a				,			extra_args_str="--sharded_ddp zero_dp_2 --fp16"				,			predict_with_generate=__a    )







     @require_apex
     @require_torch_gpu
     def 						_a      (self    ):






           '''simple docstring'''



           self.run_seqaseq_quick(distributed=__a				,			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=__a				,			extra_args_str="--fp16 --fp16_backend=apex"    )







     @parameterized.expand(["base", "low", "high", "mixed"]    )
     @require_torch_multi_gpu
     def 						_a      (self				,			__a    ):






           '''simple docstring'''



           lowerCamelCase								=		{
               # 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},
           }

           lowerCamelCase								=		experiments[experiment_id]
           lowerCamelCase								=		{"distributed": True, "predict_with_generate": False, "do_eval": False, "do_predict": False}
           lowerCamelCase								=		"Running training"
           with CaptureStderr() as cl:
                 self.run_seqaseq_quick(**__a				,			extra_args_str=data["extra_args_str"]    )
           lowerCamelCase								=		len(re.findall(__a				,			cl.err    )    )
           self.assertEqual(__a				,			data["n_matches"]    )







     @slow
     def 						_a      (self    ):






           '''simple docstring'''



           lowerCamelCase								=		self.run_trainer(
               eval_steps=2				,			max_len=1_28				,			model_name=__a				,			learning_rate=3E-4				,			num_train_epochs=10				,			distributed=__a				,			)

           # Check metrics
           lowerCamelCase								=		TrainerState.load_from_json(os.path.join(__a				,			"trainer_state.json"    )    ).log_history
           lowerCamelCase								=		[log for log in logs if "eval_loss" in log.keys()]
           lowerCamelCase								=		eval_metrics[0]
           lowerCamelCase								=		eval_metrics[-1]

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

           # test if do_predict saves generations and metrics
           lowerCamelCase								=		os.listdir(__a    )
           lowerCamelCase								=		{os.path.basename(__a    ) for p in contents}
           assert "generated_predictions.txt" in contents
           assert "predict_results.json" in contents







     @slow
     @require_bitsandbytes
     def 						_a      (self    ):






           '''simple docstring'''



           from transformers.training_args import OptimizerNames

           def train_and_return_metrics(__a    ) -> Tuple[int, float]:
                 lowerCamelCase								=		"--skip_memory_metrics 0"

                 lowerCamelCase								=		self.run_trainer(
                     max_len=1_28				,			model_name=__a				,			learning_rate=3E-4				,			num_train_epochs=1				,			optim=__a				,			distributed=__a				,			extra_args_str=__a				,			do_eval=__a				,			do_predict=__a				,			n_gpus_to_use=1				,			)

                 # Check metrics
                 lowerCamelCase								=		TrainerState.load_from_json(Path(__a				,			"trainer_state.json"    )    ).log_history
                 lowerCamelCase								=		int(logs[0]["train_mem_gpu_peaked_delta"] / 2**20    )
                 lowerCamelCase								=		int(logs[0]["train_mem_gpu_alloc_delta"] / 2**20    )

                 lowerCamelCase								=		logs[0]["train_loss"]
                 return gpu_peak_mem_mb, gpu_alloc_mem_mb, loss

           lowerCamelCase			,							lowerCamelCase			,							lowerCamelCase								=		train_and_return_metrics(OptimizerNames.ADAMW_TORCH.value    )
           lowerCamelCase			,							lowerCamelCase			,							lowerCamelCase								=		train_and_return_metrics(OptimizerNames.ADAMW_BNB.value    )

           lowerCamelCase								=		gpu_alloc_mem_orig - gpu_alloc_mem_bnb

           lowerCamelCase								=		gpu_peak_mem_orig + gpu_alloc_mem_orig
           lowerCamelCase								=		gpu_peak_mem_bnb + gpu_alloc_mem_bnb
           lowerCamelCase								=		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
           lowerCamelCase								=		1_20

           # 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(
               __a				,			__a				,			"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(
               __a				,			__a				,			"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(
               __a				,			__a				,			F"""loss should be the same, but got loss_orig={loss_orig}, loss_bnb={loss_bnb}"""    )







     def 						_a      (self				,			__a				,			__a				,			__a				,			__a = 3E-3				,			__a = "adafactor"				,			__a = False				,			__a = None				,			__a = 0				,			__a = True				,			__a = True				,			__a = True				,			__a = True				,			__a = None				,			):






           '''simple docstring'''



           lowerCamelCase								=		self.test_file_dir / "../fixtures/tests_samples/wmt_en_ro"
           lowerCamelCase								=		self.get_auto_remove_tmp_dir()
           lowerCamelCase								=		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(__a    )}
            --per_device_train_batch_size 4
            --learning_rate {learning_rate}
            --warmup_steps 8
            --logging_steps 0
            --logging_strategy no
            --save_steps {str(__a    )}
            --group_by_length
            --label_smoothing_factor 0.1
            --target_lang ro_RO
            --source_lang en_XX
        """.split()

           lowerCamelCase								=		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(__a    )}
        """.split()

           lowerCamelCase								=		"\n            --do_predict\n        ".split()

           lowerCamelCase								=		[]
           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:
                       lowerCamelCase								=		get_gpu_count()
                 lowerCamelCase								=		get_torch_dist_unique_port()
                 lowerCamelCase								=		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()
                 lowerCamelCase								=		[sys.executable] + distributed_args + args
                 # keep for quick debug
                 # print(" ".join([f"\nPYTHONPATH={self.src_dir_str}"] +cmd)); die
                 execute_subprocess_async(__a				,			env=self.get_env()    )
           else:
                 lowerCamelCase								=		["run_translation.py"] + args
                 with patch.object(__a				,			"argv"				,			__a    ):
                       main()

           return output_dir




import argparse
import json
import os

import evaluate
import torch
from datasets import load_dataset
from torch.optim import AdamW
from torch.utils.data import DataLoader
from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed

from accelerate import Accelerator, DistributedType
from accelerate.utils.deepspeed import DummyOptim, DummyScheduler


a_						:     Any	     =		1_6
a_						:     Any	     =		3_2

def     __lowercase(	UpperCAmelCase__   ,   UpperCAmelCase__ = 16   ,   UpperCAmelCase__ = "bert-base-cased" ):


      """simple docstring"""



      lowerCamelCase								=		AutoTokenizer.from_pretrained(UpperCAmelCase__ )
      lowerCamelCase								=		load_dataset("glue"   ,   "mrpc" )

      def tokenize_function(UpperCAmelCase__ ):
            # max_length=None => use the model max length (it's actually the default)
            lowerCamelCase								=		tokenizer(examples["sentence1"]   ,   examples["sentence2"]   ,   truncation=UpperCAmelCase__   ,   max_length=UpperCAmelCase__ )
            return outputs

      # Apply the method we just defined to all the examples in all the splits of the dataset
      lowerCamelCase								=		datasets.map(
          UpperCAmelCase__   ,   batched=UpperCAmelCase__   ,   remove_columns=["idx", "sentence1", "sentence2"]   ,   load_from_cache_file=UpperCAmelCase__ )

      # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the
      # transformers library
      lowerCamelCase								=		tokenized_datasets.rename_column("label"   ,   "labels" )

      def collate_fn(UpperCAmelCase__ ):
            # On TPU it's best to pad everything to the same length or training will be very slow.
            if accelerator.distributed_type == DistributedType.TPU:
                  return tokenizer.pad(UpperCAmelCase__   ,   padding="max_length"   ,   max_length=128   ,   return_tensors="pt" )
            return tokenizer.pad(UpperCAmelCase__   ,   padding="longest"   ,   return_tensors="pt" )

      # Instantiate dataloaders.
      lowerCamelCase								=		DataLoader(
          tokenized_datasets["train"]   ,   shuffle=UpperCAmelCase__   ,   collate_fn=UpperCAmelCase__   ,   batch_size=UpperCAmelCase__ )
      lowerCamelCase								=		DataLoader(
          tokenized_datasets["validation"]   ,   shuffle=UpperCAmelCase__   ,   collate_fn=UpperCAmelCase__   ,   batch_size=UpperCAmelCase__ )

      return train_dataloader, eval_dataloader

def     __lowercase(	UpperCAmelCase__   ,   UpperCAmelCase__ ):


      """simple docstring"""



      lowerCamelCase								=		Accelerator()

      # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
      lowerCamelCase								=		config["lr"]
      lowerCamelCase								=		int(config["num_epochs"] )
      lowerCamelCase								=		int(config["seed"] )
      lowerCamelCase								=		int(config["batch_size"] )
      lowerCamelCase								=		args.model_name_or_path

      set_seed(UpperCAmelCase__ )
      lowerCamelCase			,							lowerCamelCase								=		get_dataloaders(UpperCAmelCase__   ,   UpperCAmelCase__   ,   UpperCAmelCase__ )

      # Instantiate the model (we build the model here so that the seed also control new weights initialization)
      lowerCamelCase								=		AutoModelForSequenceClassification.from_pretrained(UpperCAmelCase__   ,   return_dict=UpperCAmelCase__ )

      # Instantiate optimizer
      lowerCamelCase								=		(
          AdamW
          if accelerator.state.deepspeed_plugin is None
          or "optimizer" not in accelerator.state.deepspeed_plugin.deepspeed_config
          else DummyOptim
      )
      lowerCamelCase								=		optimizer_cls(params=model.parameters()   ,   lr=UpperCAmelCase__ )

      if accelerator.state.deepspeed_plugin is not None:
            lowerCamelCase								=		accelerator.state.deepspeed_plugin.deepspeed_config[
                "gradient_accumulation_steps"
            ]
      else:
            lowerCamelCase								=		1
      lowerCamelCase								=		(len(UpperCAmelCase__ ) * num_epochs) // gradient_accumulation_steps

      # Instantiate scheduler
      if (
          accelerator.state.deepspeed_plugin is None
          or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config
      ):
            lowerCamelCase								=		get_linear_schedule_with_warmup(
                optimizer=UpperCAmelCase__   ,   num_warmup_steps=0   ,   num_training_steps=UpperCAmelCase__   ,   )
      else:
            lowerCamelCase								=		DummyScheduler(UpperCAmelCase__   ,   total_num_steps=UpperCAmelCase__   ,   warmup_num_steps=0 )

      # Prepare everything
      # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
      # prepare method.
      lowerCamelCase			,							lowerCamelCase			,							lowerCamelCase			,							lowerCamelCase			,							lowerCamelCase								=		accelerator.prepare(
          UpperCAmelCase__   ,   UpperCAmelCase__   ,   UpperCAmelCase__   ,   UpperCAmelCase__   ,   UpperCAmelCase__ )

      # We need to keep track of how many total steps we have iterated over
      lowerCamelCase								=		0
      # We also need to keep track of the stating epoch so files are named properly
      lowerCamelCase								=		0

      # Now we train the model
      lowerCamelCase								=		evaluate.load("glue"   ,   "mrpc" )
      lowerCamelCase								=		0
      lowerCamelCase								=		{}
      for epoch in range(UpperCAmelCase__   ,   UpperCAmelCase__ ):
            model.train()
            for step, batch in enumerate(UpperCAmelCase__ ):
                  lowerCamelCase								=		model(**UpperCAmelCase__ )
                  lowerCamelCase								=		outputs.loss
                  lowerCamelCase								=		loss / gradient_accumulation_steps
                  accelerator.backward(UpperCAmelCase__ )
                  if step % gradient_accumulation_steps == 0:
                        optimizer.step()
                        lr_scheduler.step()
                        optimizer.zero_grad()

                  overall_step += 1

            model.eval()
            lowerCamelCase								=		0
            for step, batch in enumerate(UpperCAmelCase__ ):
                  # We could avoid this line since we set the accelerator with `device_placement=True`.
                  batch.to(accelerator.device )
                  with torch.no_grad():
                        lowerCamelCase								=		model(**UpperCAmelCase__ )
                  lowerCamelCase								=		outputs.logits.argmax(dim=-1 )
                  # It is slightly faster to call this once, than multiple times
                  lowerCamelCase			,							lowerCamelCase								=		accelerator.gather(
                      (predictions, batch["labels"]) )  # If we are in a multiprocess environment, the last batch has duplicates
                  if accelerator.use_distributed:
                        if step == len(UpperCAmelCase__ ) - 1:
                              lowerCamelCase								=		predictions[: len(eval_dataloader.dataset ) - samples_seen]
                              lowerCamelCase								=		references[: len(eval_dataloader.dataset ) - samples_seen]
                        else:
                              samples_seen += references.shape[0]
                  metric.add_batch(
                      predictions=UpperCAmelCase__   ,   references=UpperCAmelCase__   ,   )

            lowerCamelCase								=		metric.compute()
            # Use accelerator.print to print only on the main process.
            accelerator.print(F"""epoch {epoch}:"""   ,   UpperCAmelCase__ )
            lowerCamelCase								=		eval_metric["accuracy"]

            if best_performance < eval_metric["accuracy"]:
                  lowerCamelCase								=		eval_metric["accuracy"]

      if args.performance_lower_bound is not None:
            assert (
                args.performance_lower_bound <= best_performance
            ), F"""Best performance metric {best_performance} is lower than the lower bound {args.performance_lower_bound}"""

      accelerator.wait_for_everyone()
      if accelerator.is_main_process:
            with open(os.path.join(args.output_dir   ,   "all_results.json" )   ,   "w" ) as f:
                  json.dump(UpperCAmelCase__   ,   UpperCAmelCase__ )

def     __lowercase(	):


      """simple docstring"""



      lowerCamelCase								=		argparse.ArgumentParser(description="Simple example of training script tracking peak GPU memory usage." )
      parser.add_argument(
          "--model_name_or_path"   ,   type=UpperCAmelCase__   ,   default="bert-base-cased"   ,   help="Path to pretrained model or model identifier from huggingface.co/models."   ,   required=UpperCAmelCase__   ,   )
      parser.add_argument(
          "--output_dir"   ,   type=UpperCAmelCase__   ,   default="."   ,   help="Optional save directory where all checkpoint folders will be stored. Default is the current working directory."   ,   )
      parser.add_argument(
          "--performance_lower_bound"   ,   type=UpperCAmelCase__   ,   default=UpperCAmelCase__   ,   help="Optional lower bound for the performance metric. If set, the training will throw error when the performance metric drops below this value."   ,   )
      parser.add_argument(
          "--num_epochs"   ,   type=UpperCAmelCase__   ,   default=3   ,   help="Number of train epochs."   ,   )
      lowerCamelCase								=		parser.parse_args()
      lowerCamelCase								=		{"lr": 2E-5, "num_epochs": args.num_epochs, "seed": 42, "batch_size": 16}
      training_function(UpperCAmelCase__   ,   UpperCAmelCase__ )


if __name__ == "__main__":
     main()