






import doctest
import glob
import importlib
import inspect
import os
import re
from contextlib import contextmanager
from functools import wraps
from unittest.mock import patch

import numpy as np
import pytest
from absl.testing import parameterized

import datasets
from datasets import load_metric

from .utils import for_all_test_methods, local, slow


# mark all tests as integration
A_						:						Union[str, Any]						      =					pytest.mark.integration


A_						:						Any						      =					{'comet'}
A_						:						Tuple						      =					importlib.util.find_spec('fairseq') is not None

A_						:						List[Any]						      =					{'code_eval'}
A_						:						Union[str, Any]						      =					os.name == 'nt'

A_						:						Union[str, Any]						      =					{'bertscore', 'frugalscore', 'perplexity'}
A_						:						List[str]						      =					importlib.util.find_spec('transformers') is not None

def     snake_case   (UpperCAmelCase__    )			->							Tuple:
  @wraps(UpperCAmelCase__    )
  def wrapper(self      ,       UpperCAmelCase__    ):
    if not _has_fairseq and metric_name in REQUIRE_FAIRSEQ:
      self.skipTest('"test requires Fairseq"'    )
    else:
      test_case(self      ,       UpperCAmelCase__    )

  return wrapper

def     snake_case   (UpperCAmelCase__    )			->							Any:
  @wraps(UpperCAmelCase__    )
  def wrapper(self      ,       UpperCAmelCase__    ):
    if not _has_transformers and metric_name in REQUIRE_TRANSFORMERS:
      self.skipTest('"test requires transformers"'    )
    else:
      test_case(self      ,       UpperCAmelCase__    )

  return wrapper

def     snake_case   (UpperCAmelCase__    )			->							Optional[int]:
  @wraps(UpperCAmelCase__    )
  def wrapper(self      ,       UpperCAmelCase__    ):
    if _on_windows and metric_name in UNSUPPORTED_ON_WINDOWS:
      self.skipTest('"test not supported on Windows"'    )
    else:
      test_case(self      ,       UpperCAmelCase__    )

  return wrapper

def     snake_case   ()			->							List[Any]:
  UpperCamelCase_:   Optional[int]        =							[metric_dir.split(os.sep    )[-2] for metric_dir in glob.glob('./metrics/*/'    )]
  return [{"testcase_name": x, "metric_name": x} for x in metrics if x != "gleu"]  # gleu is unfinished




@parameterized.named_parameters(get_local_metric_names()   )
@for_all_test_methods(
    UpperCAmelCase_				,      UpperCAmelCase_				,      UpperCAmelCase_   )
@local
class 							_lowerCAmelCase(			parameterized.TestCase   ):





       """simple docstring"""







       a							:						Tuple										={}
       a							:						str										=None





       @pytest.mark.filterwarnings('ignore:metric_module_factory is deprecated:FutureWarning'				)
       @pytest.mark.filterwarnings('ignore:load_metric is deprecated:FutureWarning'				)
       def      _a       (   self    ,     _lowerCamelCase				):
         UpperCamelCase_:   Any        =							'[...]'
         UpperCamelCase_:   int        =							importlib.import_module(
             datasets.load.metric_module_factory(os.path.join('metrics'    ,     _lowerCamelCase				)				).module_path				)
         UpperCamelCase_:   List[Any]        =							datasets.load.import_main_class(metric_module.__name__    ,     dataset=_lowerCamelCase				)
         # check parameters
         UpperCamelCase_:   Optional[Any]        =							inspect.signature(metric._compute				).parameters
         self.assertTrue(all(p.kind != p.VAR_KEYWORD for p in parameters.values()				)				)  # no **kwargs
         # run doctest
         with self.patch_intensive_calls(_lowerCamelCase    ,     metric_module.__name__				):
           with self.use_local_metrics():
             try:
               UpperCamelCase_:   Union[str, Any]        =							doctest.testmod(_lowerCamelCase    ,     verbose=_lowerCamelCase    ,     raise_on_error=_lowerCamelCase				)
             except doctest.UnexpectedException as e:
               raise e.exc_info[1]  # raise the exception that doctest caught
         self.assertEqual(results.failed    ,     0				)
         self.assertGreater(results.attempted    ,     1				)





       @slow
       def      _a       (   self    ,     _lowerCamelCase				):
         UpperCamelCase_:   Optional[Any]        =							'[...]'
         UpperCamelCase_:   Optional[int]        =							importlib.import_module(
             datasets.load.metric_module_factory(os.path.join('metrics'    ,     _lowerCamelCase				)				).module_path				)
         # run doctest
         with self.use_local_metrics():
           UpperCamelCase_:   Union[str, Any]        =							doctest.testmod(_lowerCamelCase    ,     verbose=_lowerCamelCase    ,     raise_on_error=_lowerCamelCase				)
         self.assertEqual(results.failed    ,     0				)
         self.assertGreater(results.attempted    ,     1				)





       @contextmanager
       def      _a       (   self    ,     _lowerCamelCase    ,     _lowerCamelCase				):
         if metric_name in self.INTENSIVE_CALLS_PATCHER:
           with self.INTENSIVE_CALLS_PATCHER[metric_name](_lowerCamelCase				):
             yield
         else:
           yield





       @contextmanager
       def      _a       (   self				):
         def load_local_metric(_lowerCamelCase    ,     *_lowerCamelCase    ,     **_lowerCamelCase				):
           return load_metric(os.path.join('metrics'    ,     _lowerCamelCase				)    ,     *_lowerCamelCase    ,     **_lowerCamelCase				)

         with patch('datasets.load_metric'				) as mock_load_metric:
           UpperCamelCase_:   List[Any]        =							load_local_metric
           yield





       @classmethod
       def      _a       (   cls    ,     _lowerCamelCase				):
         def wrapper(_lowerCamelCase				):
           UpperCamelCase_:   Optional[Any]        =							contextmanager(_lowerCamelCase				)
           UpperCamelCase_:   int        =							patcher
           return patcher

         return wrapper







@LocalMetricTest.register_intensive_calls_patcher('bleurt'    )
def     snake_case   (UpperCAmelCase__    )			->							Dict:
  import tensorflow.compat.va as tf
  from bleurt.score import Predictor

  tf.flags.DEFINE_string('sv'      ,       ''      ,       ''    )  # handle pytest cli flags




  class 							_lowerCAmelCase(			UpperCAmelCase_   ):





         """simple docstring"""







         def      _a       (   self    ,     _lowerCamelCase				):
           assert len(input_dict['input_ids']				) == 2
           return np.array([1.0_3, 1.0_4]				)

    # mock predict_fn which is supposed to do a forward pass with a bleurt model
  with patch('bleurt.score._create_predictor'    ) as mock_create_predictor:
    UpperCamelCase_:   Dict        =							MockedPredictor()
    yield

@LocalMetricTest.register_intensive_calls_patcher('bertscore'    )
def     snake_case   (UpperCAmelCase__    )			->							Optional[Any]:
  import torch

  def bert_cos_score_idf(UpperCAmelCase__      ,       UpperCAmelCase__      ,       *UpperCAmelCase__      ,       **UpperCAmelCase__    ):
    return torch.tensor([[1.0, 1.0, 1.0]] * len(UpperCAmelCase__    )    )

  # mock get_model which is supposed to do download a bert model
  # mock bert_cos_score_idf which is supposed to do a forward pass with a bert model
  with patch('bert_score.scorer.get_model'    ), patch(
      'bert_score.scorer.bert_cos_score_idf'    ) as mock_bert_cos_score_idf:
    UpperCamelCase_:   Dict        =							bert_cos_score_idf
    yield

@LocalMetricTest.register_intensive_calls_patcher('comet'    )
def     snake_case   (UpperCAmelCase__    )			->							List[str]:
  def load_from_checkpoint(UpperCAmelCase__    ):




    class 							_lowerCAmelCase:





           """simple docstring"""







           def      _a       (   self    ,     _lowerCamelCase    ,     *_lowerCamelCase    ,     **_lowerCamelCase				):
             assert len(_lowerCamelCase				) == 2
             UpperCamelCase_:   List[Any]        =							[0.1_9, 0.9_2]
             return scores, sum(_lowerCamelCase				) / len(_lowerCamelCase				)







    return Model()

  # mock load_from_checkpoint which is supposed to do download a bert model
  # mock load_from_checkpoint which is supposed to do download a bert model
  with patch('comet.download_model'    ) as mock_download_model:
    UpperCamelCase_:   Union[str, Any]        =							None
    with patch('comet.load_from_checkpoint'    ) as mock_load_from_checkpoint:
      UpperCamelCase_:   int        =							load_from_checkpoint
      yield

def     snake_case   ()			->							str:
  UpperCamelCase_:   Union[str, Any]        =							load_metric(os.path.join('metrics'      ,       'seqeval'    )    )
  UpperCamelCase_:   Any        =							'ERROR'
  UpperCamelCase_:   List[Any]        =							F'''Scheme should be one of [IOB1, IOB2, IOE1, IOE2, IOBES, BILOU], got {wrong_scheme}'''
  with pytest.raises(UpperCAmelCase__      ,       match=re.escape(UpperCAmelCase__    )    ):
    metric.compute(predictions=[]      ,       references=[]      ,       scheme=UpperCAmelCase__    )





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


lowercase__							:	Dict											=		16
lowercase__							:	str											=		32


def 		lowerCamelCase__       (						_A	,      _A = 16	,      _A = "bert-base-cased"				):







	'''simple docstring'''





	snake_case_						       =	AutoTokenizer.from_pretrained(_A				)
	snake_case_						       =	load_dataset("glue"	,      "mrpc"				)

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

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

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

	def collate_fn(_A				):
		# 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(_A	,      padding="max_length"	,      max_length=128	,      return_tensors="pt"				)
		return tokenizer.pad(_A	,      padding="longest"	,      return_tensors="pt"				)

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

	return train_dataloader, eval_dataloader


def 		lowerCamelCase__       (						_A	,      _A				):







	'''simple docstring'''





	snake_case_						       =	Accelerator()

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

	set_seed(_A				)
	snake_case_       , snake_case_						       =	get_dataloaders(_A	,      _A	,      _A				)

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

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

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

	# Instantiate scheduler
	if (
	    accelerator.state.deepspeed_plugin is None
	    or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config
	):
		snake_case_						       =	get_linear_schedule_with_warmup(
		    optimizer=_A	,      num_warmup_steps=0	,      num_training_steps=_A	,      )
	else:
		snake_case_						       =	DummyScheduler(_A	,      total_num_steps=_A	,      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.
	snake_case_       , snake_case_       , snake_case_       , snake_case_       , snake_case_						       =	accelerator.prepare(
	    _A	,      _A	,      _A	,      _A	,      _A				)

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

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

			overall_step += 1

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

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

		if best_performance < eval_metric["accuracy"]:
			snake_case_						       =	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(_A	,      _A				)


def 		lowerCamelCase__       (						):







	'''simple docstring'''





	snake_case_						       =	argparse.ArgumentParser(description="Simple example of training script tracking peak GPU memory usage."				)
	parser.add_argument(
	    "--model_name_or_path"	,      type=_A	,      default="bert-base-cased"	,      help="Path to pretrained model or model identifier from huggingface.co/models."	,      required=_A	,      )
	parser.add_argument(
	    "--output_dir"	,      type=_A	,      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=_A	,      default=_A	,      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=_A	,      default=3	,      help="Number of train epochs."	,      )
	snake_case_						       =	parser.parse_args()
	snake_case_						       =	{"lr": 2E-5, "num_epochs": args.num_epochs, "seed": 42, "batch_size": 16}
	training_function(_A	,      _A				)


if __name__ == "__main__":
		main()
