





"""simple docstring"""

import shutil
import tempfile
import unittest
from unittest.mock import patch

from transformers import (
    DefaultFlowCallback,
    IntervalStrategy,
    PrinterCallback,
    ProgressCallback,
    Trainer,
    TrainerCallback,
    TrainingArguments,
    is_torch_available,
)
from transformers.testing_utils import require_torch


if is_torch_available():
 from transformers.trainer import DEFAULT_CALLBACKS

 from .test_trainer import RegressionDataset, RegressionModelConfig, RegressionPreTrainedModel


class       lowerCAmelCase__				(   __A  ):







 def __init__(   self					):

    '''simple docstring'''


    A__											=					[]







 def  lowercase_       (   self		,	UpperCamelCase__		,	UpperCamelCase__		,	UpperCamelCase__		,	**UpperCamelCase__					):

    '''simple docstring'''


    self.events.append("on_init_end"					)







 def  lowercase_       (   self		,	UpperCamelCase__		,	UpperCamelCase__		,	UpperCamelCase__		,	**UpperCamelCase__					):

    '''simple docstring'''


    self.events.append("on_train_begin"					)







 def  lowercase_       (   self		,	UpperCamelCase__		,	UpperCamelCase__		,	UpperCamelCase__		,	**UpperCamelCase__					):

    '''simple docstring'''


    self.events.append("on_train_end"					)







 def  lowercase_       (   self		,	UpperCamelCase__		,	UpperCamelCase__		,	UpperCamelCase__		,	**UpperCamelCase__					):

    '''simple docstring'''


    self.events.append("on_epoch_begin"					)







 def  lowercase_       (   self		,	UpperCamelCase__		,	UpperCamelCase__		,	UpperCamelCase__		,	**UpperCamelCase__					):

    '''simple docstring'''


    self.events.append("on_epoch_end"					)







 def  lowercase_       (   self		,	UpperCamelCase__		,	UpperCamelCase__		,	UpperCamelCase__		,	**UpperCamelCase__					):

    '''simple docstring'''


    self.events.append("on_step_begin"					)







 def  lowercase_       (   self		,	UpperCamelCase__		,	UpperCamelCase__		,	UpperCamelCase__		,	**UpperCamelCase__					):

    '''simple docstring'''


    self.events.append("on_step_end"					)







 def  lowercase_       (   self		,	UpperCamelCase__		,	UpperCamelCase__		,	UpperCamelCase__		,	**UpperCamelCase__					):

    '''simple docstring'''


    self.events.append("on_evaluate"					)







 def  lowercase_       (   self		,	UpperCamelCase__		,	UpperCamelCase__		,	UpperCamelCase__		,	**UpperCamelCase__					):

    '''simple docstring'''


    self.events.append("on_predict"					)







 def  lowercase_       (   self		,	UpperCamelCase__		,	UpperCamelCase__		,	UpperCamelCase__		,	**UpperCamelCase__					):

    '''simple docstring'''


    self.events.append("on_save"					)







 def  lowercase_       (   self		,	UpperCamelCase__		,	UpperCamelCase__		,	UpperCamelCase__		,	**UpperCamelCase__					):

    '''simple docstring'''


    self.events.append("on_log"					)







 def  lowercase_       (   self		,	UpperCamelCase__		,	UpperCamelCase__		,	UpperCamelCase__		,	**UpperCamelCase__					):

    '''simple docstring'''


    self.events.append("on_prediction_step"					)





@require_torch
class       lowerCAmelCase__				(   unittest.TestCase  ):







 def  lowercase_       (   self					):

    '''simple docstring'''


    A__											=					tempfile.mkdtemp()







 def  lowercase_       (   self					):

    '''simple docstring'''


    shutil.rmtree(self.output_dir					)







 def  lowercase_       (   self		,	UpperCamelCase__=0		,	UpperCamelCase__=0		,	UpperCamelCase__=64		,	UpperCamelCase__=64		,	UpperCamelCase__=None		,	UpperCamelCase__=False		,	**UpperCamelCase__					):

    '''simple docstring'''


    A__											=					RegressionDataset(length=UpperCamelCase__					)
    A__											=					RegressionDataset(length=UpperCamelCase__					)
    A__											=					RegressionModelConfig(a=UpperCamelCase__		,	b=UpperCamelCase__					)
    A__											=					RegressionPreTrainedModel(UpperCamelCase__					)

    A__											=					TrainingArguments(self.output_dir		,	disable_tqdm=UpperCamelCase__		,	report_to=[]		,	**UpperCamelCase__					)
    return Trainer(
        UpperCamelCase__		,	UpperCamelCase__		,	train_dataset=UpperCamelCase__		,	eval_dataset=UpperCamelCase__		,	callbacks=UpperCamelCase__		,	)







 def  lowercase_       (   self		,	UpperCamelCase__		,	UpperCamelCase__					):

    '''simple docstring'''


    self.assertEqual(len(UpperCamelCase__					)		,	len(UpperCamelCase__					)					)

    # Order doesn't matter
    A__											=					sorted(UpperCamelCase__		,	key=lambda UpperCamelCase__					: cb.__name__ if isinstance(UpperCamelCase__		,	UpperCamelCase__					) else cb.__class__.__name__					)
    A__											=					sorted(UpperCamelCase__		,	key=lambda UpperCamelCase__					: cb.__name__ if isinstance(UpperCamelCase__		,	UpperCamelCase__					) else cb.__class__.__name__					)

    for cba, cba in zip(UpperCamelCase__		,	UpperCamelCase__					):
       if isinstance(UpperCamelCase__		,	UpperCamelCase__					) and isinstance(UpperCamelCase__		,	UpperCamelCase__					):
          self.assertEqual(UpperCamelCase__		,	UpperCamelCase__					)
       elif isinstance(UpperCamelCase__		,	UpperCamelCase__					) and not isinstance(UpperCamelCase__		,	UpperCamelCase__					):
          self.assertEqual(UpperCamelCase__		,	cba.__class__					)
       elif not isinstance(UpperCamelCase__		,	UpperCamelCase__					) and isinstance(UpperCamelCase__		,	UpperCamelCase__					):
          self.assertEqual(cba.__class__		,	UpperCamelCase__					)
       else:
          self.assertEqual(UpperCamelCase__		,	UpperCamelCase__					)







 def  lowercase_       (   self		,	UpperCamelCase__					):

    '''simple docstring'''


    A__											=					['''on_init_end''', '''on_train_begin''']
    A__											=					0
    A__											=					len(trainer.get_eval_dataloader()					)
    A__											=					['''on_prediction_step'''] * len(trainer.get_eval_dataloader()					) + ['''on_log''', '''on_evaluate''']
    for _ in range(trainer.state.num_train_epochs					):
       expected_events.append("on_epoch_begin"					)
       for _ in range(UpperCamelCase__					):
          step += 1
          expected_events += ["on_step_begin", "on_step_end"]
          if step % trainer.args.logging_steps == 0:
             expected_events.append("on_log"					)
          if trainer.args.evaluation_strategy == IntervalStrategy.STEPS and step % trainer.args.eval_steps == 0:
             expected_events += evaluation_events.copy()
          if step % trainer.args.save_steps == 0:
             expected_events.append("on_save"					)
       expected_events.append("on_epoch_end"					)
       if trainer.args.evaluation_strategy == IntervalStrategy.EPOCH:
          expected_events += evaluation_events.copy()
    expected_events += ["on_log", "on_train_end"]
    return expected_events







 def  lowercase_       (   self					):

    '''simple docstring'''


    A__											=					self.get_trainer()
    A__											=					DEFAULT_CALLBACKS.copy() + [ProgressCallback]
    self.check_callbacks_equality(trainer.callback_handler.callbacks		,	UpperCamelCase__					)

    # Callbacks passed at init are added to the default callbacks
    A__											=					self.get_trainer(callbacks=[MyTestTrainerCallback]					)
    expected_callbacks.append(UpperCamelCase__					)
    self.check_callbacks_equality(trainer.callback_handler.callbacks		,	UpperCamelCase__					)

    # TrainingArguments.disable_tqdm controls if use ProgressCallback or PrinterCallback
    A__											=					self.get_trainer(disable_tqdm=UpperCamelCase__					)
    A__											=					DEFAULT_CALLBACKS.copy() + [PrinterCallback]
    self.check_callbacks_equality(trainer.callback_handler.callbacks		,	UpperCamelCase__					)







 def  lowercase_       (   self					):

    '''simple docstring'''


    A__											=					DEFAULT_CALLBACKS.copy() + [ProgressCallback]
    A__											=					self.get_trainer()

    # We can add, pop, or remove by class name
    trainer.remove_callback(UpperCamelCase__					)
    expected_callbacks.remove(UpperCamelCase__					)
    self.check_callbacks_equality(trainer.callback_handler.callbacks		,	UpperCamelCase__					)

    A__											=					self.get_trainer()
    A__											=					trainer.pop_callback(UpperCamelCase__					)
    self.assertEqual(cb.__class__		,	UpperCamelCase__					)
    self.check_callbacks_equality(trainer.callback_handler.callbacks		,	UpperCamelCase__					)

    trainer.add_callback(UpperCamelCase__					)
    expected_callbacks.insert(0		,	UpperCamelCase__					)
    self.check_callbacks_equality(trainer.callback_handler.callbacks		,	UpperCamelCase__					)

    # We can also add, pop, or remove by instance
    A__											=					self.get_trainer()
    A__											=					trainer.callback_handler.callbacks[0]
    trainer.remove_callback(UpperCamelCase__					)
    expected_callbacks.remove(UpperCamelCase__					)
    self.check_callbacks_equality(trainer.callback_handler.callbacks		,	UpperCamelCase__					)

    A__											=					self.get_trainer()
    A__											=					trainer.callback_handler.callbacks[0]
    A__											=					trainer.pop_callback(UpperCamelCase__					)
    self.assertEqual(UpperCamelCase__		,	UpperCamelCase__					)
    self.check_callbacks_equality(trainer.callback_handler.callbacks		,	UpperCamelCase__					)

    trainer.add_callback(UpperCamelCase__					)
    expected_callbacks.insert(0		,	UpperCamelCase__					)
    self.check_callbacks_equality(trainer.callback_handler.callbacks		,	UpperCamelCase__					)







 def  lowercase_       (   self					):

    '''simple docstring'''


    import warnings

    # XXX: for now ignore scatter_gather warnings in this test since it's not relevant to what's being tested
    warnings.simplefilter(action="ignore"		,	category=UpperCamelCase__					)

    A__											=					self.get_trainer(callbacks=[MyTestTrainerCallback]					)
    trainer.train()
    A__											=					trainer.callback_handler.callbacks[-2].events
    self.assertEqual(UpperCamelCase__		,	self.get_expected_events(UpperCamelCase__					)					)

    # Independent log/save/eval
    A__											=					self.get_trainer(callbacks=[MyTestTrainerCallback]		,	logging_steps=5					)
    trainer.train()
    A__											=					trainer.callback_handler.callbacks[-2].events
    self.assertEqual(UpperCamelCase__		,	self.get_expected_events(UpperCamelCase__					)					)

    A__											=					self.get_trainer(callbacks=[MyTestTrainerCallback]		,	save_steps=5					)
    trainer.train()
    A__											=					trainer.callback_handler.callbacks[-2].events
    self.assertEqual(UpperCamelCase__		,	self.get_expected_events(UpperCamelCase__					)					)

    A__											=					self.get_trainer(callbacks=[MyTestTrainerCallback]		,	eval_steps=5		,	evaluation_strategy="steps"					)
    trainer.train()
    A__											=					trainer.callback_handler.callbacks[-2].events
    self.assertEqual(UpperCamelCase__		,	self.get_expected_events(UpperCamelCase__					)					)

    A__											=					self.get_trainer(callbacks=[MyTestTrainerCallback]		,	evaluation_strategy="epoch"					)
    trainer.train()
    A__											=					trainer.callback_handler.callbacks[-2].events
    self.assertEqual(UpperCamelCase__		,	self.get_expected_events(UpperCamelCase__					)					)

    # A bit of everything
    A__											=					self.get_trainer(
        callbacks=[MyTestTrainerCallback]		,	logging_steps=3		,	save_steps=10		,	eval_steps=5		,	evaluation_strategy="steps"		,	)
    trainer.train()
    A__											=					trainer.callback_handler.callbacks[-2].events
    self.assertEqual(UpperCamelCase__		,	self.get_expected_events(UpperCamelCase__					)					)

    # warning should be emitted for duplicated callbacks
    with patch("transformers.trainer_callback.logger.warning"					) as warn_mock:
       A__											=					self.get_trainer(
           callbacks=[MyTestTrainerCallback, MyTestTrainerCallback]		,	)
       assert str(UpperCamelCase__					) in warn_mock.call_args[0][0]







'''simple docstring'''



import warnings

from transformers import AutoTokenizer
from transformers.utils import is_torch_available
from transformers.utils.generic import ExplicitEnum

from ...processing_utils import ProcessorMixin


if is_torch_available():
      import torch
class UpperCAmelCase_       (     __A					):




      """simple docstring"""




      UpperCamelCase_             =      '''char'''
      UpperCamelCase_             =      '''bpe'''
      UpperCamelCase_             =      '''wp'''





SCREAMING_SNAKE_CASE							=						(DecodeType.CHARACTER, DecodeType.BPE, DecodeType.WORDPIECE)
class UpperCAmelCase_       (     __A					):




      """simple docstring"""




      UpperCamelCase_             =      ['''image_processor''', '''char_tokenizer''']
      UpperCamelCase_             =      '''ViTImageProcessor'''
      UpperCamelCase_             =      '''MgpstrTokenizer'''






      def __init__(			self      :		int  ,   UpperCAmelCase      :		Tuple=None  ,   UpperCAmelCase      :		Dict=None  ,   **UpperCAmelCase      :		Any		)	->	List[str]:


       '''simple docstring'''

       lowercase       : str						=None
       if "feature_extractor" in kwargs:
        warnings.warn(
            '''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`'''
            ''' instead.'''  ,   UpperCAmelCase  ,   )
        lowercase       : int						=kwargs.pop('''feature_extractor'''		)

       lowercase       : Optional[Any]						=image_processor if image_processor is not None else feature_extractor
       if image_processor is None:
        raise ValueError('''You need to specify an `image_processor`.'''		)
       if tokenizer is None:
        raise ValueError('''You need to specify a `tokenizer`.'''		)

       lowercase       : Any						=tokenizer
       lowercase       : Dict						=AutoTokenizer.from_pretrained('''gpt2'''		)
       lowercase       : Optional[int]						=AutoTokenizer.from_pretrained('''bert-base-uncased'''		)

       super().__init__(UpperCAmelCase  ,   UpperCAmelCase		)






      def __call__(			self      :		List[Any]  ,   UpperCAmelCase      :		Union[str, Any]=None  ,   UpperCAmelCase      :		List[str]=None  ,   UpperCAmelCase      :		Dict=None  ,   **UpperCAmelCase      :		Union[str, Any]		)	->	int:


       '''simple docstring'''

       if images is None and text is None:
        raise ValueError('''You need to specify either an `images` or `text` input to process.'''		)

       if images is not None:
        lowercase       : str						=self.image_processor(UpperCAmelCase  ,   return_tensors=UpperCAmelCase  ,   **UpperCAmelCase		)
       if text is not None:
        lowercase       : Any						=self.char_tokenizer(UpperCAmelCase  ,   return_tensors=UpperCAmelCase  ,   **UpperCAmelCase		)

       if text is None:
        return inputs
       elif images is None:
        return encodings
       else:
        lowercase       : List[str]						=encodings['''input_ids''']
        return inputs






      def 					A__   (			self      :		List[Any]  ,   UpperCAmelCase      :		Optional[Any]		)	->	Optional[Any]:


       '''simple docstring'''

       lowercase	,		lowercase	,		lowercase       : Union[str, Any]						=sequences
       lowercase       : Dict						=char_preds.size(0		)

       lowercase	,		lowercase       : Any						=self._decode_helper(UpperCAmelCase  ,   '''char'''		)
       lowercase	,		lowercase       : int						=self._decode_helper(UpperCAmelCase  ,   '''bpe'''		)
       lowercase	,		lowercase       : Optional[Any]						=self._decode_helper(UpperCAmelCase  ,   '''wp'''		)

       lowercase       : Dict						=[]
       lowercase       : List[Any]						=[]
       for i in range(UpperCAmelCase		):
        lowercase       : List[str]						=[char_scores[i], bpe_scores[i], wp_scores[i]]
        lowercase       : Union[str, Any]						=[char_strs[i], bpe_strs[i], wp_strs[i]]
        lowercase       : List[str]						=scores.index(max(UpperCAmelCase		)		)
        final_strs.append(strs[max_score_index]		)
        final_scores.append(scores[max_score_index]		)

       lowercase       : List[Any]						={}
       lowercase       : Optional[Any]						=final_strs
       lowercase       : Optional[Any]						=final_scores
       lowercase       : str						=char_strs
       lowercase       : Tuple						=bpe_strs
       lowercase       : List[str]						=wp_strs
       return out






      def 					A__   (			self      :		str  ,   UpperCAmelCase      :		Dict  ,   UpperCAmelCase      :		Union[str, Any]		)	->	Optional[int]:


       '''simple docstring'''

       if format == DecodeType.CHARACTER:
        lowercase       : Union[str, Any]						=self.char_decode
        lowercase       : List[str]						=1
        lowercase       : Tuple						='''[s]'''
       elif format == DecodeType.BPE:
        lowercase       : Union[str, Any]						=self.bpe_decode
        lowercase       : Optional[int]						=2
        lowercase       : Optional[Any]						='''#'''
       elif format == DecodeType.WORDPIECE:
        lowercase       : List[str]						=self.wp_decode
        lowercase       : Union[str, Any]						=102
        lowercase       : int						='''[SEP]'''
       else:
        raise ValueError(f'Format {format} is not supported.'		)

       lowercase	,		lowercase       : Union[str, Any]						=[], []
       lowercase       : Optional[int]						=pred_logits.size(0		)
       lowercase       : List[str]						=pred_logits.size(1		)
       lowercase	,		lowercase       : Optional[int]						=pred_logits.topk(1  ,   dim=-1  ,   largest=UpperCAmelCase  ,   sorted=UpperCAmelCase		)
       lowercase       : Tuple						=preds_index.view(-1  ,   UpperCAmelCase		)[:, 1:]
       lowercase       : Any						=decoder(UpperCAmelCase		)
       lowercase	,		lowercase       : List[str]						=torch.nn.functional.softmax(UpperCAmelCase  ,   dim=2		).max(dim=2		)
       lowercase       : List[Any]						=preds_max_prob[:, 1:]

       for index in range(UpperCAmelCase		):
        lowercase       : List[Any]						=preds_str[index].find(UpperCAmelCase		)
        lowercase       : Any						=preds_str[index][:pred_eos]
        lowercase       : Any						=preds_index[index].cpu().tolist()
        lowercase       : Optional[int]						=pred_index.index(UpperCAmelCase		) if eos_token in pred_index else -1
        lowercase       : int						=preds_max_prob[index][: pred_eos_index + 1]
        lowercase       : Tuple						=pred_max_prob.cumprod(dim=0		)[-1] if pred_max_prob.nelement() != 0 else 0.0
        dec_strs.append(UpperCAmelCase		)
        conf_scores.append(UpperCAmelCase		)

       return dec_strs, conf_scores






      def 					A__   (			self      :		List[str]  ,   UpperCAmelCase      :		Optional[int]		)	->	Dict:


       '''simple docstring'''

       lowercase       : Union[str, Any]						=[seq.replace(''' '''  ,   ''''''		) for seq in self.char_tokenizer.batch_decode(UpperCAmelCase		)]
       return decode_strs






      def 					A__   (			self      :		Optional[int]  ,   UpperCAmelCase      :		Optional[Any]		)	->	str:


       '''simple docstring'''

       return self.bpe_tokenizer.batch_decode(UpperCAmelCase		)






      def 					A__   (			self      :		Tuple  ,   UpperCAmelCase      :		Dict		)	->	List[str]:


       '''simple docstring'''

       lowercase       : str						=[seq.replace(''' '''  ,   ''''''		) for seq in self.wp_tokenizer.batch_decode(UpperCAmelCase		)]
       return decode_strs



