'''simple docstring'''


import collections

from .utils import ExplicitEnum, is_torch_available, logging


if is_torch_available():
 import torch


snake_case__	:     Dict      =    logging.get_logger(__name__)






class 	__SCREAMING_SNAKE_CASE		:







  '''simple docstring'''






  def __init__(					self ,						snake_case_ ,						snake_case_=2_1 ,						snake_case_=[] ,						snake_case_=None		):




       '''simple docstring'''

       UpperCAmelCase_				:  Tuple  = model
       UpperCAmelCase_				:  Dict  = trace_batch_nums
       UpperCAmelCase_				:  Optional[int]  = 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
       UpperCAmelCase_				:  str  = collections.deque([] ,						snake_case_		)
       UpperCAmelCase_				:  List[str]  = []
       UpperCAmelCase_				:  List[Any]  = 0
       UpperCAmelCase_				:  List[str]  = 0
       UpperCAmelCase_				:  Any  = False
       UpperCAmelCase_				:  Tuple  = '                 '

       self.analyse_model()

       self.register_forward_hook()


  def _UpperCamelCase	(					self ,						snake_case_=None		):




       '''simple docstring'''

       if frame is not None:
            self.expand_frame(snake_case_		)
       self.frames.append('\n'.join(self.frame		)		)
       UpperCAmelCase_				:  int  = []  # start a new frame


  def _UpperCamelCase	(					self ,						snake_case_		):




       '''simple docstring'''

       self.frame.append(snake_case_		)


  def _UpperCamelCase	(					self		):




       '''simple docstring'''

       print('\n'.join(self.frames		)		)
       UpperCAmelCase_				:  str  = []


  def _UpperCamelCase	(					self		):




       '''simple docstring'''

       UpperCAmelCase_				:  List[str]  = []


  def _UpperCamelCase	(					self		):




       '''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'		)
       UpperCAmelCase_				:  Optional[Any]  = []


  def _UpperCamelCase	(					self		):




       '''simple docstring'''

       UpperCAmelCase_				:  Any  = {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 _UpperCamelCase	(					self ,						snake_case_ ,						snake_case_		):




       '''simple docstring'''

       if torch.is_tensor(snake_case_		):
            self.expand_frame(get_abs_min_max(snake_case_ ,						snake_case_		)		)
            if detect_overflow(snake_case_ ,						snake_case_		):
                 UpperCAmelCase_				:  Union[str, Any]  = True
       elif var is None:
            self.expand_frame(F'''{'None':>17} {ctx}'''		)
       else:
            self.expand_frame(F'''{'not a tensor':>17} {ctx}'''		)


  def _UpperCamelCase	(					self		):




       '''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 _UpperCamelCase	(					self		):




       '''simple docstring'''

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


  def _UpperCamelCase	(					self ,						snake_case_ ,						snake_case_ ,						snake_case_		):




       '''simple docstring'''

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

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

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

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

       self.save_frame()


  def _UpperCamelCase	(					self		):




       '''simple docstring'''

       self.model.apply(self._register_forward_hook		)


  def _UpperCamelCase	(					self ,						snake_case_		):




       '''simple docstring'''

       module.register_forward_hook(self.forward_hook		)






  def _UpperCamelCase	(					self ,						snake_case_ ,						snake_case_ ,						snake_case_		):




       '''simple docstring'''

       UpperCAmelCase_				:  Union[str, Any]  = False

       UpperCAmelCase_				:  Optional[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
            UpperCAmelCase_				:  Dict  = True

       self.create_frame(snake_case_ ,						snake_case_ ,						snake_case_		)

       # 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    _lowerCamelCase       ( lowerCamelCase_   :				Tuple      ,	lowerCamelCase_   :				Union[str, Any]  ):



     """simple docstring"""





     UpperCAmelCase_				:  Any  = var.abs()
     return F'''{abs_var.min():8.2e} {abs_var.max():8.2e} {ctx}'''


def    _lowerCamelCase       ( lowerCamelCase_   :				List[str]      ,	lowerCamelCase_   :				Optional[Any]  ):



     """simple docstring"""





     UpperCAmelCase_				:  Union[str, Any]  = False
     if torch.isnan(lowerCamelCase_  ).any().item():
          UpperCAmelCase_				:  Optional[Any]  = True
          print(F'''{ctx} has nans'''  )
     if torch.isinf(lowerCamelCase_  ).any().item():
          UpperCAmelCase_				:  Tuple  = True
          print(F'''{ctx} has infs'''  )

     # if needed to monitor large elements can enable the following
     if 0:  # and detected:
          UpperCAmelCase_				:  Union[str, Any]  = var[torch.ge(var.abs()      ,	100  )]
          if naaa.numel() > 0:
               print(F'''{ctx}:  n100={naaa.numel()}'''  )
          UpperCAmelCase_				:  str  = var[torch.ge(var.abs()      ,	1000  )]
          if naaaa.numel() > 0:
               print(F'''{ctx}: n1000={naaaa.numel()}'''  )
          UpperCAmelCase_				:  str  = var[torch.ge(var.abs()      ,	10000  )]
          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 	__SCREAMING_SNAKE_CASE		(			lowerCamelCase_			):







  '''simple docstring'''






  lowerCamelCase_						:Optional[Any]		       =						'''underflow_overflow'''
  lowerCamelCase_						:str		       =						'''tpu_metrics_debug'''










import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs


if is_torch_available():
   import torch

if is_vision_available():
   from PIL import Image

   from transformers import MobileNetVaImageProcessor



class 							a       (      unittest.TestCase ):





     def __init__(     self       :					Optional[int]     ,						SCREAMING_SNAKE_CASE_       :					str     ,						SCREAMING_SNAKE_CASE_       :					List[str]=7     ,						SCREAMING_SNAKE_CASE_       :					Union[str, Any]=3     ,						SCREAMING_SNAKE_CASE_       :					List[Any]=18     ,						SCREAMING_SNAKE_CASE_       :					List[str]=30     ,						SCREAMING_SNAKE_CASE_       :					List[Any]=400     ,						SCREAMING_SNAKE_CASE_       :					Dict=True     ,						SCREAMING_SNAKE_CASE_       :					Any=None     ,						SCREAMING_SNAKE_CASE_       :					List[str]=True     ,						SCREAMING_SNAKE_CASE_       :					Any=None     ,						):
        __lowerCamelCase:					List[Any]	 =						size if size is not None else {"""shortest_edge""": 20}
        __lowerCamelCase:					Tuple	 =						crop_size if crop_size is not None else {"""height""": 18, """width""": 18}
        __lowerCamelCase:					List[Any]	 =						parent
        __lowerCamelCase:					Optional[int]	 =						batch_size
        __lowerCamelCase:					str	 =						num_channels
        __lowerCamelCase:					Dict	 =						image_size
        __lowerCamelCase:					Tuple	 =						min_resolution
        __lowerCamelCase:					Union[str, Any]	 =						max_resolution
        __lowerCamelCase:					Tuple	 =						do_resize
        __lowerCamelCase:					List[str]	 =						size
        __lowerCamelCase:					int	 =						do_center_crop
        __lowerCamelCase:					Tuple	 =						crop_size







     def 			SCREAMING_SNAKE_CASE__							(     self       :					List[Any]				):
        return {
            "do_resize": self.do_resize,
            "size": self.size,
            "do_center_crop": self.do_center_crop,
            "crop_size": self.crop_size,
        }



@require_torch
@require_vision
class 							a       (      _UpperCAmelCase  ,unittest.TestCase ):
     UpperCAmelCase__			:	int       =						MobileNetVaImageProcessor if is_vision_available() else None





     def 			SCREAMING_SNAKE_CASE__							(     self       :					List[str]				):
        __lowerCamelCase:					Tuple	 =						MobileNetVaImageProcessingTester(self				)





     @property
     def 			SCREAMING_SNAKE_CASE__							(     self       :					str				):
        return self.image_processor_tester.prepare_image_processor_dict()





     def 			SCREAMING_SNAKE_CASE__							(     self       :					List[str]				):
        __lowerCamelCase:					List[Any]	 =						self.image_processing_class(**self.image_processor_dict				)
        self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_     ,						"""do_resize"""				)				)
        self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_     ,						"""size"""				)				)
        self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_     ,						"""do_center_crop"""				)				)
        self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_     ,						"""center_crop"""				)				)





     def 			SCREAMING_SNAKE_CASE__							(     self       :					Any				):
        __lowerCamelCase:					str	 =						self.image_processing_class.from_dict(self.image_processor_dict				)
        self.assertEqual(image_processor.size     ,						{"""shortest_edge""": 20}				)
        self.assertEqual(image_processor.crop_size     ,						{"""height""": 18, """width""": 18}				)

        __lowerCamelCase:					Optional[int]	 =						self.image_processing_class.from_dict(self.image_processor_dict     ,						size=42     ,						crop_size=84				)
        self.assertEqual(image_processor.size     ,						{"""shortest_edge""": 42}				)
        self.assertEqual(image_processor.crop_size     ,						{"""height""": 84, """width""": 84}				)





     def 			SCREAMING_SNAKE_CASE__							(     self       :					Optional[Any]				):
        pass





     def 			SCREAMING_SNAKE_CASE__							(     self       :					Optional[int]				):
        # Initialize image_processing
        __lowerCamelCase:					List[str]	 =						self.image_processing_class(**self.image_processor_dict				)
        # create random PIL images
        __lowerCamelCase:					str	 =						prepare_image_inputs(self.image_processor_tester     ,						equal_resolution=SCREAMING_SNAKE_CASE_				)
        for image in image_inputs:
           self.assertIsInstance(SCREAMING_SNAKE_CASE_     ,						Image.Image				)

        # Test not batched input
        __lowerCamelCase:					Optional[Any]	 =						image_processing(image_inputs[0]     ,						return_tensors="""pt"""				).pixel_values
        self.assertEqual(
            encoded_images.shape     ,						(
                1,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.crop_size["""height"""],
                self.image_processor_tester.crop_size["""width"""],
            )     ,						)

        # Test batched
        __lowerCamelCase:					Tuple	 =						image_processing(SCREAMING_SNAKE_CASE_     ,						return_tensors="""pt"""				).pixel_values
        self.assertEqual(
            encoded_images.shape     ,						(
                self.image_processor_tester.batch_size,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.crop_size["""height"""],
                self.image_processor_tester.crop_size["""width"""],
            )     ,						)





     def 			SCREAMING_SNAKE_CASE__							(     self       :					Optional[int]				):
        # Initialize image_processing
        __lowerCamelCase:					Union[str, Any]	 =						self.image_processing_class(**self.image_processor_dict				)
        # create random numpy tensors
        __lowerCamelCase:					Tuple	 =						prepare_image_inputs(self.image_processor_tester     ,						equal_resolution=SCREAMING_SNAKE_CASE_     ,						numpify=SCREAMING_SNAKE_CASE_				)
        for image in image_inputs:
           self.assertIsInstance(SCREAMING_SNAKE_CASE_     ,						np.ndarray				)

        # Test not batched input
        __lowerCamelCase:					List[Any]	 =						image_processing(image_inputs[0]     ,						return_tensors="""pt"""				).pixel_values
        self.assertEqual(
            encoded_images.shape     ,						(
                1,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.crop_size["""height"""],
                self.image_processor_tester.crop_size["""width"""],
            )     ,						)

        # Test batched
        __lowerCamelCase:					Optional[Any]	 =						image_processing(SCREAMING_SNAKE_CASE_     ,						return_tensors="""pt"""				).pixel_values
        self.assertEqual(
            encoded_images.shape     ,						(
                self.image_processor_tester.batch_size,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.crop_size["""height"""],
                self.image_processor_tester.crop_size["""width"""],
            )     ,						)







     def 			SCREAMING_SNAKE_CASE__							(     self       :					Optional[int]				):
        # Initialize image_processing
        __lowerCamelCase:					str	 =						self.image_processing_class(**self.image_processor_dict				)
        # create random PyTorch tensors
        __lowerCamelCase:					List[str]	 =						prepare_image_inputs(self.image_processor_tester     ,						equal_resolution=SCREAMING_SNAKE_CASE_     ,						torchify=SCREAMING_SNAKE_CASE_				)
        for image in image_inputs:
           self.assertIsInstance(SCREAMING_SNAKE_CASE_     ,						torch.Tensor				)

        # Test not batched input
        __lowerCamelCase:					Union[str, Any]	 =						image_processing(image_inputs[0]     ,						return_tensors="""pt"""				).pixel_values
        self.assertEqual(
            encoded_images.shape     ,						(
                1,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.crop_size["""height"""],
                self.image_processor_tester.crop_size["""width"""],
            )     ,						)

        # Test batched
        __lowerCamelCase:					Optional[int]	 =						image_processing(SCREAMING_SNAKE_CASE_     ,						return_tensors="""pt"""				).pixel_values
        self.assertEqual(
            encoded_images.shape     ,						(
                self.image_processor_tester.batch_size,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.crop_size["""height"""],
                self.image_processor_tester.crop_size["""width"""],
            )     ,						)


