



"""simple docstring"""
import collections

from .utils import ExplicitEnum, is_torch_available, logging


if is_torch_available():
   import torch


_UpperCAmelCase       =     logging.get_logger(__name__)
class    a		:



  def __init__(  self	:   Tuple    ,						lowerCAmelCase	:   List[Any]    ,						lowerCAmelCase	:   List[Any]=21    ,						lowerCAmelCase	:   Union[str, Any]=[]    ,						lowerCAmelCase	:   str=None						)       ->   Any:


     '''simple docstring'''




     SCREAMING_SNAKE_CASE_:	Tuple            =model
     SCREAMING_SNAKE_CASE_:	Union[str, Any]            =trace_batch_nums
     SCREAMING_SNAKE_CASE_:	Any            =abort_after_batch_num

     # keep a LIFO buffer of frames to dump as soon as inf/nan is encountered to give context to the problem emergence
     SCREAMING_SNAKE_CASE_:	Optional[int]            =collections.deque([]    ,						lowerCAmelCase						)
     SCREAMING_SNAKE_CASE_:	Union[str, Any]            =[]
     SCREAMING_SNAKE_CASE_:	Optional[int]            =0
     SCREAMING_SNAKE_CASE_:	List[str]            =0
     SCREAMING_SNAKE_CASE_:	Any            =False
     SCREAMING_SNAKE_CASE_:	Dict            ="""                 """

     self.analyse_model()

     self.register_forward_hook()



  def 		lowerCamelCase__    (  self	:   Optional[Any]    ,						lowerCAmelCase	:   List[Any]=None						)       ->   Dict:


     '''simple docstring'''




     if frame is not None:
        self.expand_frame(lowerCAmelCase						)
     self.frames.append("""\n""".join(self.frame						)						)
     SCREAMING_SNAKE_CASE_:	Dict            =[]  # start a new frame



  def 		lowerCamelCase__    (  self	:   Optional[Any]    ,						lowerCAmelCase	:   List[str]						)       ->   Any:


     '''simple docstring'''




     self.frame.append(lowerCAmelCase						)



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


     '''simple docstring'''




     print("""\n""".join(self.frames						)						)
     SCREAMING_SNAKE_CASE_:	str            =[]



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


     '''simple docstring'''




     SCREAMING_SNAKE_CASE_:	Dict            =[]



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


     '''simple docstring'''




     print(f'''\nDetected inf/nan during batch_number={self.batch_number}'''						)
     print(f'''Last {len(self.frames						)} forward frames:'''						)
     print(f'''{"abs min":8} {"abs max":8} metadata'''						)
     print("""\n""".join(self.frames						)						)
     print("""\n\n"""						)
     SCREAMING_SNAKE_CASE_:	int            =[]



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


     '''simple docstring'''




     SCREAMING_SNAKE_CASE_:	Tuple            ={m: name for name, m in self.model.named_modules()}
     # self.longest_module_name = max(len(v) for v in self.module_names.values())



  def 		lowerCamelCase__    (  self	:   Optional[int]    ,						lowerCAmelCase	:   Any    ,						lowerCAmelCase	:   int						)       ->   Union[str, Any]:


     '''simple docstring'''




     if torch.is_tensor(lowerCAmelCase						):
        self.expand_frame(get_abs_min_max(lowerCAmelCase    ,						lowerCAmelCase						)						)
        if detect_overflow(lowerCAmelCase    ,						lowerCAmelCase						):
           SCREAMING_SNAKE_CASE_:	Dict            =True
     elif var is None:
        self.expand_frame(f'''{"None":>17} {ctx}'''						)
     else:
        self.expand_frame(f'''{"not a tensor":>17} {ctx}'''						)



  def 		lowerCamelCase__    (  self	:   List[str]						)       ->   Dict:


     '''simple docstring'''




     self.expand_frame(f'''\n\n{self.prefix} *** Starting batch number={self.batch_number} ***'''						)
     self.expand_frame(f'''{"abs min":8} {"abs max":8} metadata'''						)



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


     '''simple docstring'''




     self.expand_frame(f'''{self.prefix} *** Finished batch number={self.batch_number-1} ***\n\n'''						)



  def 		lowerCamelCase__    (  self	:   str    ,						lowerCAmelCase	:   Tuple    ,						lowerCAmelCase	:   Optional[int]    ,						lowerCAmelCase	:   Optional[Any]						)       ->   List[Any]:


     '''simple docstring'''




     self.expand_frame(f'''{self.prefix} {self.module_names[module]} {module.__class__.__name__}'''						)

     # params
     for name, p in module.named_parameters(recurse=lowerCAmelCase						):
        self.analyse_variable(lowerCAmelCase    ,						lowerCAmelCase						)

     # inputs
     if isinstance(lowerCAmelCase    ,						lowerCAmelCase						):
        for i, x in enumerate(lowerCAmelCase						):
           self.analyse_variable(lowerCAmelCase    ,						f'''input[{i}]'''						)
     else:
        self.analyse_variable(lowerCAmelCase    ,						"""input"""						)

     # outputs
     if isinstance(lowerCAmelCase    ,						lowerCAmelCase						):
        for i, x in enumerate(lowerCAmelCase						):
           # possibly a tuple of tuples
           if isinstance(lowerCAmelCase    ,						lowerCAmelCase						):
              for j, y in enumerate(lowerCAmelCase						):
                 self.analyse_variable(lowerCAmelCase    ,						f'''output[{i}][{j}]'''						)
           else:
              self.analyse_variable(lowerCAmelCase    ,						f'''output[{i}]'''						)
     else:
        self.analyse_variable(lowerCAmelCase    ,						"""output"""						)

     self.save_frame()



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


     '''simple docstring'''




     self.model.apply(self._register_forward_hook						)



  def 		lowerCamelCase__    (  self	:   List[str]    ,						lowerCAmelCase	:   str						)       ->   str:


     '''simple docstring'''




     module.register_forward_hook(self.forward_hook						)





  def 		lowerCamelCase__    (  self	:   List[str]    ,						lowerCAmelCase	:   Optional[int]    ,						lowerCAmelCase	:   Optional[Any]    ,						lowerCAmelCase	:   Dict						)       ->   str:


     '''simple docstring'''




     SCREAMING_SNAKE_CASE_:	Any            =False

     SCREAMING_SNAKE_CASE_:	List[Any]            =True if self.batch_number in self.trace_batch_nums else False
     if trace_mode:
        self.reset_saved_frames()

     if self.total_calls == 0:
        self.batch_start_frame()
     self.total_calls += 1

     # count batch numbers - the very first forward hook of the batch will be called when the
     # batch completes - i.e. it gets called very last - we know this batch has finished
     if module == self.model:
        self.batch_number += 1
        SCREAMING_SNAKE_CASE_:	Union[str, Any]            =True

     self.create_frame(lowerCAmelCase    ,						lowerCAmelCase    ,						lowerCAmelCase						)

     # if last_frame_of_batch:
     #     self.batch_end_frame()

     if trace_mode:
        self.trace_frames()

     if last_frame_of_batch:
        self.batch_start_frame()

     if self.detected_overflow and not trace_mode:
        self.dump_saved_frames()

        # now we can abort, as it's pointless to continue running
        raise ValueError(
            """DebugUnderflowOverflow: inf/nan detected, aborting as there is no point running further. """
            """Please scroll up above this traceback to see the activation values prior to this event."""						)

     # abort after certain batch if requested to do so
     if self.abort_after_batch_num is not None and self.batch_number > self.abort_after_batch_num:
        raise ValueError(
            f'''DebugUnderflowOverflow: aborting after {self.batch_number} batches due to'''
            f''' `abort_after_batch_num={self.abort_after_batch_num}` arg'''						)







def        __magic_name__			(							lowercase							,     lowercase	):
   SCREAMING_SNAKE_CASE_:	int            =var.abs()
   return f'''{abs_var.min():8.2e} {abs_var.max():8.2e} {ctx}'''





def        __magic_name__			(							lowercase							,     lowercase	):
   SCREAMING_SNAKE_CASE_:	Tuple            =False
   if torch.isnan(lowercase	).any().item():
      SCREAMING_SNAKE_CASE_:	int            =True
      print(f'''{ctx} has nans'''	)
   if torch.isinf(lowercase	).any().item():
      SCREAMING_SNAKE_CASE_:	str            =True
      print(f'''{ctx} has infs'''	)

   # if needed to monitor large elements can enable the following
   if 0:  # and detected:
      SCREAMING_SNAKE_CASE_:	Optional[Any]            =var[torch.ge(var.abs()							,     100	)]
      if naaa.numel() > 0:
         print(f'''{ctx}:  n100={naaa.numel()}'''	)
      SCREAMING_SNAKE_CASE_:	Optional[int]            =var[torch.ge(var.abs()							,     1000	)]
      if naaaa.numel() > 0:
         print(f'''{ctx}: n1000={naaaa.numel()}'''	)
      SCREAMING_SNAKE_CASE_:	Union[str, Any]            =var[torch.ge(var.abs()							,     1_0000	)]
      if naaaaa.numel() > 0:
         print(f'''{ctx}: n10000={naaaaa.numel()}'''	)

   if 0:
      print(f'''min={var.min():9.2e} max={var.max():9.2e}'''	)

   if 0:
      print(f'''min={var.min():9.2e} max={var.max():9.2e} var={var.var():9.2e} mean={var.mean():9.2e} ({ctx})'''	)

   return detected
class    a		(					UpperCAmelCase__    ):
  UpperCamelCase		:			Dict         =   'underflow_overflow'
  UpperCamelCase		:			List[str]         =   'tpu_metrics_debug'








"""simple docstring"""
import shutil
import tempfile
import unittest

import pytest

from transformers import WhisperTokenizer, is_speech_available
from transformers.testing_utils import require_sentencepiece, require_torch, require_torchaudio

from .test_feature_extraction_whisper import floats_list


if is_speech_available():
   from transformers import WhisperFeatureExtractor, WhisperProcessor


_UpperCAmelCase       =     5_0_3_5_8
_UpperCAmelCase       =     5_0_3_6_2
@require_torch
@require_torchaudio
@require_sentencepiece
class    a		(					unittest.TestCase    ):



  def 		lowerCamelCase__    (  self	:   Dict						)       ->   Tuple:


     '''simple docstring'''




     SCREAMING_SNAKE_CASE_:	List[Any]            ="""openai/whisper-small.en"""
     SCREAMING_SNAKE_CASE_:	Union[str, Any]            =tempfile.mkdtemp()



  def 		lowerCamelCase__    (  self	:   Any    ,						**lowerCAmelCase	:   str						)       ->   str:


     '''simple docstring'''




     return WhisperTokenizer.from_pretrained(self.checkpoint    ,						**lowerCAmelCase						)



  def 		lowerCamelCase__    (  self	:   str    ,						**lowerCAmelCase	:   Optional[Any]						)       ->   Optional[Any]:


     '''simple docstring'''




     return WhisperFeatureExtractor.from_pretrained(self.checkpoint    ,						**lowerCAmelCase						)



  def 		lowerCamelCase__    (  self	:   Tuple						)       ->   Optional[Any]:


     '''simple docstring'''




     shutil.rmtree(self.tmpdirname						)



  def 		lowerCamelCase__    (  self	:   int						)       ->   str:


     '''simple docstring'''




     SCREAMING_SNAKE_CASE_:	Optional[int]            =self.get_tokenizer()
     SCREAMING_SNAKE_CASE_:	Optional[int]            =self.get_feature_extractor()

     SCREAMING_SNAKE_CASE_:	Optional[Any]            =WhisperProcessor(tokenizer=lowerCAmelCase    ,						feature_extractor=lowerCAmelCase						)

     processor.save_pretrained(self.tmpdirname						)
     SCREAMING_SNAKE_CASE_:	Dict            =WhisperProcessor.from_pretrained(self.tmpdirname						)

     self.assertEqual(processor.tokenizer.get_vocab()    ,						tokenizer.get_vocab()						)
     self.assertIsInstance(processor.tokenizer    ,						lowerCAmelCase						)

     self.assertEqual(processor.feature_extractor.to_json_string()    ,						feature_extractor.to_json_string()						)
     self.assertIsInstance(processor.feature_extractor    ,						lowerCAmelCase						)



  def 		lowerCamelCase__    (  self	:   str						)       ->   Optional[Any]:


     '''simple docstring'''




     SCREAMING_SNAKE_CASE_:	Union[str, Any]            =WhisperProcessor(tokenizer=self.get_tokenizer()    ,						feature_extractor=self.get_feature_extractor()						)
     processor.save_pretrained(self.tmpdirname						)

     SCREAMING_SNAKE_CASE_:	int            =self.get_tokenizer(bos_token="""(BOS)"""    ,						eos_token="""(EOS)"""						)
     SCREAMING_SNAKE_CASE_:	Dict            =self.get_feature_extractor(do_normalize=lowerCAmelCase    ,						padding_value=1.0						)

     SCREAMING_SNAKE_CASE_:	Optional[int]            =WhisperProcessor.from_pretrained(
         self.tmpdirname    ,						bos_token="""(BOS)"""    ,						eos_token="""(EOS)"""    ,						do_normalize=lowerCAmelCase    ,						padding_value=1.0						)

     self.assertEqual(processor.tokenizer.get_vocab()    ,						tokenizer_add_kwargs.get_vocab()						)
     self.assertIsInstance(processor.tokenizer    ,						lowerCAmelCase						)

     self.assertEqual(processor.feature_extractor.to_json_string()    ,						feature_extractor_add_kwargs.to_json_string()						)
     self.assertIsInstance(processor.feature_extractor    ,						lowerCAmelCase						)



  def 		lowerCamelCase__    (  self	:   Tuple						)       ->   Optional[int]:


     '''simple docstring'''




     SCREAMING_SNAKE_CASE_:	Tuple            =self.get_feature_extractor()
     SCREAMING_SNAKE_CASE_:	Union[str, Any]            =self.get_tokenizer()

     SCREAMING_SNAKE_CASE_:	Dict            =WhisperProcessor(tokenizer=lowerCAmelCase    ,						feature_extractor=lowerCAmelCase						)

     SCREAMING_SNAKE_CASE_:	Dict            =floats_list((3, 1000)						)

     SCREAMING_SNAKE_CASE_:	Optional[Any]            =feature_extractor(lowerCAmelCase    ,						return_tensors="""np"""						)
     SCREAMING_SNAKE_CASE_:	str            =processor(lowerCAmelCase    ,						return_tensors="""np"""						)

     for key in input_feat_extract.keys():
        self.assertAlmostEqual(input_feat_extract[key].sum()    ,						input_processor[key].sum()    ,						delta=1E-2						)



  def 		lowerCamelCase__    (  self	:   Tuple						)       ->   Any:


     '''simple docstring'''




     SCREAMING_SNAKE_CASE_:	List[str]            =self.get_feature_extractor()
     SCREAMING_SNAKE_CASE_:	str            =self.get_tokenizer()

     SCREAMING_SNAKE_CASE_:	List[Any]            =WhisperProcessor(tokenizer=lowerCAmelCase    ,						feature_extractor=lowerCAmelCase						)

     SCREAMING_SNAKE_CASE_:	List[str]            ="""This is a test string"""

     SCREAMING_SNAKE_CASE_:	Tuple            =processor(text=lowerCAmelCase						)

     SCREAMING_SNAKE_CASE_:	List[Any]            =tokenizer(lowerCAmelCase						)

     for key in encoded_tok.keys():
        self.assertListEqual(encoded_tok[key]    ,						encoded_processor[key]						)



  def 		lowerCamelCase__    (  self	:   Optional[Any]						)       ->   Any:


     '''simple docstring'''




     SCREAMING_SNAKE_CASE_:	Optional[int]            =self.get_feature_extractor()
     SCREAMING_SNAKE_CASE_:	str            =self.get_tokenizer()

     SCREAMING_SNAKE_CASE_:	Union[str, Any]            =WhisperProcessor(tokenizer=lowerCAmelCase    ,						feature_extractor=lowerCAmelCase						)

     SCREAMING_SNAKE_CASE_:	List[str]            =[[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]

     SCREAMING_SNAKE_CASE_:	Optional[int]            =processor.batch_decode(lowerCAmelCase						)
     SCREAMING_SNAKE_CASE_:	Dict            =tokenizer.batch_decode(lowerCAmelCase						)

     self.assertListEqual(lowerCAmelCase    ,						lowerCAmelCase						)



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


     '''simple docstring'''




     SCREAMING_SNAKE_CASE_:	str            =self.get_feature_extractor()
     SCREAMING_SNAKE_CASE_:	List[Any]            =self.get_tokenizer()

     SCREAMING_SNAKE_CASE_:	Optional[Any]            =WhisperProcessor(tokenizer=lowerCAmelCase    ,						feature_extractor=lowerCAmelCase						)

     self.assertListEqual(
         processor.model_input_names    ,						feature_extractor.model_input_names    ,						msg="""`processor` and `feature_extractor` model input names do not match"""    ,						)



  def 		lowerCamelCase__    (  self	:   Optional[int]						)       ->   Union[str, Any]:


     '''simple docstring'''




     SCREAMING_SNAKE_CASE_:	Optional[Any]            =self.get_feature_extractor()
     SCREAMING_SNAKE_CASE_:	Any            =self.get_tokenizer()

     SCREAMING_SNAKE_CASE_:	List[Any]            =WhisperProcessor(tokenizer=lowerCAmelCase    ,						feature_extractor=lowerCAmelCase						)
     SCREAMING_SNAKE_CASE_:	Any            =processor.get_decoder_prompt_ids(task="""transcribe"""    ,						no_timestamps=lowerCAmelCase						)

     self.assertIsInstance(lowerCAmelCase    ,						lowerCAmelCase						)
     for ids in forced_decoder_ids:
        self.assertIsInstance(lowerCAmelCase    ,						(list, tuple)						)

     SCREAMING_SNAKE_CASE_:	Tuple            =[TRANSCRIBE, NOTIMESTAMPS]
     self.assertListEqual([ids[-1] for ids in forced_decoder_ids]    ,						lowerCAmelCase						)



  def 		lowerCamelCase__    (  self	:   List[str]						)       ->   List[str]:


     '''simple docstring'''




     SCREAMING_SNAKE_CASE_:	Union[str, Any]            =WhisperProcessor(tokenizer=self.get_tokenizer()    ,						feature_extractor=self.get_feature_extractor()						)
     SCREAMING_SNAKE_CASE_:	Optional[int]            =processor.get_prompt_ids("""Mr. Quilter"""						)
     SCREAMING_SNAKE_CASE_:	List[str]            =processor.tokenizer.decode(lowerCAmelCase						)

     self.assertListEqual(prompt_ids.tolist()    ,						[5_0360, 1770, 13, 2264, 346, 353]						)
     self.assertEqual(lowerCAmelCase    ,						"""<|startofprev|> Mr. Quilter"""						)



  def 		lowerCamelCase__    (  self	:   Dict						)       ->   Tuple:


     '''simple docstring'''




     SCREAMING_SNAKE_CASE_:	Optional[Any]            =WhisperProcessor(tokenizer=self.get_tokenizer()    ,						feature_extractor=self.get_feature_extractor()						)
     SCREAMING_SNAKE_CASE_:	int            =processor.get_prompt_ids(""""""						)
     SCREAMING_SNAKE_CASE_:	Union[str, Any]            =processor.tokenizer.decode(lowerCAmelCase						)

     self.assertListEqual(prompt_ids.tolist()    ,						[5_0360, 220]						)
     self.assertEqual(lowerCAmelCase    ,						"""<|startofprev|> """						)





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


     '''simple docstring'''




     SCREAMING_SNAKE_CASE_:	Dict            =WhisperProcessor(tokenizer=self.get_tokenizer()    ,						feature_extractor=self.get_feature_extractor()						)

     def _test_prompt_error_raised_helper(lowerCAmelCase	:   List[str]    ,						lowerCAmelCase	:   int						):
        with pytest.raises(lowerCAmelCase						) as excinfo:
           processor.get_prompt_ids(lowerCAmelCase						)
        SCREAMING_SNAKE_CASE_:	List[Any]            =f'''Encountered text in the prompt corresponding to disallowed special token: {special_token}.'''
        self.assertEqual(lowerCAmelCase    ,						str(excinfo.value						)						)

     _test_prompt_error_raised_helper("""<|startofprev|> test"""    ,						"""<|startofprev|>"""						)
     _test_prompt_error_raised_helper("""test <|notimestamps|>"""    ,						"""<|notimestamps|>"""						)
     _test_prompt_error_raised_helper("""test <|zh|> test <|transcribe|>"""    ,						"""<|zh|>"""						)



