o
    hm2                     @   sf   d dl Z ddlmZmZmZ e rd dlZeeZG dd dZ	dd Z
dd	 ZG d
d deZdS )    N   )ExplicitEnumis_torch_availableloggingc                   @   s   e Zd ZdZdg dfddZd ddZdd	 Zd
d Zdd Zdd Z	dd Z
dd Zdd Zdd Zdd Zdd Zdd Zdd ZdS )!DebugUnderflowOverflowa  
    This debug class helps detect and understand where the model starts getting very large or very small, and more
    importantly `nan` or `inf` weight and activation elements.

    There are 2 working modes:

    1. Underflow/overflow detection (default)
    2. Specific batch absolute min/max tracing without detection

    Mode 1: Underflow/overflow detection

    To activate the underflow/overflow detection, initialize the object with the model :

    ```python
    debug_overflow = DebugUnderflowOverflow(model)
    ```

    then run the training as normal and if `nan` or `inf` gets detected in at least one of the weight, input or output
    elements this module will throw an exception and will print `max_frames_to_save` frames that lead to this event,
    each frame reporting

    1. the fully qualified module name plus the class name whose `forward` was run
    2. the absolute min and max value of all elements for each module weights, and the inputs and output

    For example, here is the header and the last few frames in detection report for `google/mt5-small` run in fp16
    mixed precision :

    ```
    Detected inf/nan during batch_number=0
    Last 21 forward frames:
    abs min  abs max  metadata
    [...]
                      encoder.block.2.layer.1.DenseReluDense.wi_0 Linear
    2.17e-07 4.50e+00 weight
    1.79e-06 4.65e+00 input[0]
    2.68e-06 3.70e+01 output
                      encoder.block.2.layer.1.DenseReluDense.wi_1 Linear
    8.08e-07 2.66e+01 weight
    1.79e-06 4.65e+00 input[0]
    1.27e-04 2.37e+02 output
                      encoder.block.2.layer.1.DenseReluDense.wo Linear
    1.01e-06 6.44e+00 weight
    0.00e+00 9.74e+03 input[0]
    3.18e-04 6.27e+04 output
                      encoder.block.2.layer.1.DenseReluDense T5DenseGatedGeluDense
    1.79e-06 4.65e+00 input[0]
    3.18e-04 6.27e+04 output
                      encoder.block.2.layer.1.dropout Dropout
    3.18e-04 6.27e+04 input[0]
    0.00e+00      inf output
    ```

    You can see here, that `T5DenseGatedGeluDense.forward` resulted in output activations, whose absolute max value was
    around 62.7K, which is very close to fp16's top limit of 64K. In the next frame we have `Dropout` which
    renormalizes the weights, after it zeroed some of the elements, which pushes the absolute max value to more than
    64K, and we get an overlow.

    As you can see it's the previous frames that we need to look into when the numbers start going into very large for
    fp16 numbers.

    The tracking is done in a forward hook, which gets invoked immediately after `forward` has completed.

    By default the last 21 frames are printed. You can change the default to adjust for your needs. For example :

    ```python
    debug_overflow = DebugUnderflowOverflow(model, max_frames_to_save=100)
    ```

        To validate that you have set up this debugging feature correctly, and you intend to use it in a training that
        may take hours to complete, first run it with normal tracing enabled for one of a few batches as explained in
        the next section.


        Mode 2. Specific batch absolute min/max tracing without detection

        The second work mode is per-batch tracing with the underflow/overflow detection feature turned off.

        Let's say you want to watch the absolute min and max values for all the ingredients of each `forward` call of a
    given batch, and only do that for batches 1 and 3. Then you instantiate this class as :

    ```python
    debug_overflow = DebugUnderflowOverflow(model, trace_batch_nums=[1, 3])
    ```

    And now full batches 1 and 3 will be traced using the same format as explained above. Batches are 0-indexed.

    This is helpful if you know that the program starts misbehaving after a certain batch number, so you can
    fast-forward right to that area.


    Early stopping:

    You can also specify the batch number after which to stop the training, with :

    ```python
    debug_overflow = DebugUnderflowOverflow(model, trace_batch_nums=[1, 3], abort_after_batch_num=3)
    ```

    This feature is mainly useful in the tracing mode, but you can use it for any mode.


    **Performance**:

    As this module measures absolute `min`/``max` of each weight of the model on every forward it'll slow the training
    down. Therefore remember to turn it off once the debugging needs have been met.

    Args:
        model (`nn.Module`):
            The model to debug.
        max_frames_to_save (`int`, *optional*, defaults to 21):
            How many frames back to record
        trace_batch_nums(`List[int]`, *optional*, defaults to `[]`):
            Which batch numbers to trace (turns detection off)
        abort_after_batch_num  (`int``, *optional*):
            Whether to abort after a certain batch number has finished
       Nc                 C   sR   || _ || _|| _tg || _g | _d| _d| _d| _	d| _
|   |   d S )Nr   Fz                 )modeltrace_batch_numsabort_after_batch_numcollectionsdequeframesframebatch_numbertotal_callsdetected_overflowprefixanalyse_modelregister_forward_hook)selfr   max_frames_to_saver	   r
    r   l/var/www/html/construction_image-detection-poc/venv/lib/python3.10/site-packages/transformers/debug_utils.py__init__   s   zDebugUnderflowOverflow.__init__c                 C   s0   |d ur	|  | | jd| j g | _d S N
)expand_framer   appendjoinr   )r   r   r   r   r   
save_frame   s   

z!DebugUnderflowOverflow.save_framec                 C   s   | j | d S N)r   r   )r   liner   r   r   r         z#DebugUnderflowOverflow.expand_framec                 C   s   t d| j g | _d S r   )printr   r   r   r   r   r   trace_frames   s   
z#DebugUnderflowOverflow.trace_framesc                 C   s
   g | _ d S r    )r   r$   r   r   r   reset_saved_frames   s   
z)DebugUnderflowOverflow.reset_saved_framesc                 C   s`   t d| j  t dt| j d t dddddd t d	| j t d
 g | _d S )Nz&
Detected inf/nan during batch_number=zLast z forward frames:abs min8 abs max	 metadatar   

)r#   r   lenr   r   r$   r   r   r   dump_saved_frames   s   
z(DebugUnderflowOverflow.dump_saved_framesc                 C   s   dd | j  D | _d S )Nc                 S   s   i | ]\}}||qS r   r   ).0namemr   r   r   
<dictcomp>   s    z8DebugUnderflowOverflow.analyse_model.<locals>.<dictcomp>)r   named_modulesmodule_namesr$   r   r   r   r      s   z$DebugUnderflowOverflow.analyse_modelc                 C   sn   t |r| t|| t||rd| _d S d S |d u r*| ddd|  d S | ddd|  d S )NTNonez>17r)   znot a tensor)torch	is_tensorr   get_abs_min_maxdetect_overflowr   )r   varctxr   r   r   analyse_variable   s   


z'DebugUnderflowOverflow.analyse_variablec                 C   s:   |  d| j d| j d |  dddddd d S )	Nr,   z *** Starting batch number=z ***r'   r(   r)   r*   r+   r   r   r   r$   r   r   r   batch_start_frame   s   z(DebugUnderflowOverflow.batch_start_framec                 C   s"   |  | j d| jd  d d S )Nz *** Finished batch number=r   z ***

r=   r$   r   r   r   batch_end_frame   s   "z&DebugUnderflowOverflow.batch_end_framec           
   
   C   s  |  | j d| j|  d|jj  |jddD ]
\}}| || qt|tr=t	|D ]\}}| |d| d q-n| |d t|trxt	|D ]*\}}t|trlt	|D ]\}}	| |	d| d| d qYqL| |d| d qLn| |d	 | 
  d S )
Nr)   F)recursezinput[]inputzoutput[z][output)r   r   r4   	__class____name__named_parametersr<   
isinstancetuple	enumerater   )
r   modulerB   rC   r0   pixjyr   r   r   create_frame   s$   &


z#DebugUnderflowOverflow.create_framec                 C   s   | j | j d S r    )r   apply_register_forward_hookr$   r   r   r   r      s   z,DebugUnderflowOverflow.register_forward_hookc                 C   s   | | j d S r    )r   forward_hook)r   rJ   r   r   r   rR      r"   z-DebugUnderflowOverflow._register_forward_hookc                 C   s   d}| j | jv r
dnd}|r|   | jdkr|   |  jd7  _|| jkr0|  j d7  _ d}| ||| |r=|   |rC|   | jrP|sP| 	  t
d| jd urh| j | jkrjt
d| j  d| j dd S d S )	NFTr   r   zDebugUnderflowOverflow: 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.z'DebugUnderflowOverflow: aborting after z' batches due to `abort_after_batch_num=z` arg)r   r	   r&   r   r>   r   rP   r%   r   r.   
ValueErrorr
   )r   rJ   rB   rC   last_frame_of_batch
trace_moder   r   r   rS      s6   



z#DebugUnderflowOverflow.forward_hookr    )rE   
__module____qualname____doc__r   r   r   r%   r&   r.   r   r<   r>   r?   rP   r   rR   rS   r   r   r   r   r      s     u

r   c                 C   s(   |   }| dd| dd| S )Nz8.2er)   )absminmax)r:   r;   abs_varr   r   r   r8   %  s    r8   c                 C   sV   d}t |   rd}t| d t |   r&d}t| d 	 	 	 |S )a&  
    Report whether the tensor contains any `nan` or `inf` entries.

    This is useful for detecting overflows/underflows and best to call right after the function that did some math that
    modified the tensor in question.

    This function contains a few other helper features that you can enable and tweak directly if you want to track
    various other things.

    Args:
        var: the tensor variable to check
        ctx: the message to print as a context

    Return:
        `True` if `inf` or `nan` was detected, `False` otherwise
    FTz	 has nansz	 has infs)r6   isnananyitemr#   isinfgerZ   numelr[   r\   r:   mean)r:   r;   detectedn100n1000n10000r   r   r   r9   *  s   r9   c                   @   s   e Zd ZdZdZdS )DebugOptionunderflow_overflowtpu_metrics_debugN)rE   rW   rX   UNDERFLOW_OVERFLOWTPU_METRICS_DEBUGr   r   r   r   ri   X  s    ri   )r   utilsr   r   r   r6   
get_loggerrE   loggerr   r8   r9   ri   r   r   r   r   <module>   s   
  .