
    ɯwgL                     h    d dl Z d dlZd dlmZmZ d dlmZ  G d d      Z G d de      Z	d
dZ
d	 Zy)    N)EmptyQueue)get_device_contextc                        e Zd ZddZd Zd Zy)ClosureHandlerNc                      y N )selfs    X/home/mcse/projects/flask/flask-venv/lib/python3.12/site-packages/torch/_lazy/closure.py__init__zClosureHandler.__init__
   s        c                      |        y)zVRun closure function

        Args:
        closure: callable function to run
        Nr
   )r   closures     r   runzClosureHandler.run   s	     		r   c                 4    |D ]  }| j                  |        y r	   )r   )r   closuresr   s      r   __call__zClosureHandler.__call__   s     	GHHW	r   )returnN)__name__
__module____qualname__r   r   r   r
   r   r   r   r   	   s    r   r   c                   0     e Zd ZdZd fd	Zd Zd Z xZS )AsyncClosureHandlerai  Handler for Asynchronous Step Closures
    Args:
        max_queue_size: The maximum length of the closure queue after which
        the training loop will block until closures are evaluated.
        By default, a reasonable limit of a maximum of 100 on the queue.
        This value can be set using the `XLA_MAX_ASYNC_QUEUE` environment
        variable.
    c                     t         |           t        t        t        j
                  j                  d|                  | _        t               | _        t        j                         | _        t        j                         | _        d | _        y )NLTC_MAX_ASYNC_QUEUE)superr   r   intosenvironget_closure_queue_closure_exception	threadingLock_closure_lockEvent_closure_event_loop_finished_closure_event_loop)r   max_queue_size	__class__s     r   r   zAsyncClosureHandler.__init__$   se    %*

4nEF&
 */&^^-,5OO,=)#' r   c                       j                   ; fd}t        j                  |       _          j                   j                          yy)z'Start closure event loop if not startedNc                     	 	 j                   j                  dd      }  |         j                   j                          @# t        $ re j                  5  j                   j                         r%j                  j                          	 d d d        Y y 	 d d d        n# 1 sw Y   nxY wY nt        $ r%}j                  j                  |       Y d }~y d }~ww xY w)NT   )blocktimeout)r"   r!   	task_done
EmptyQueuer&   emptyr(   set	Exceptionr#   put)r   er   s     r   
event_loopz8AsyncClosureHandler.start_event_loop.<locals>.event_loop2   s    "&"5"5"9"9a"9"P	++557	 
 & '!// '#2288: $ A A E E G &' ':' ' ' % //33A6s;   >A C6B"C	C"B+	'C0C8CC)target)r)   r$   Threadstart)r   r8   s   ` r   start_event_loopz$AsyncClosureHandler.start_event_loop.   s@    ##+  (1'7'7z'JD$$$**,' ,r   c                 j   | j                   5  | j                  j                  |d       | j                  | j                  j	                         s)	 | j
                  j                  d      }t        d      |d d d        y # t        $ r d | _        | j                          Y +w xY w# 1 sw Y   y xY w)NT)r/   FzBCannot run asynchronous closure due to previously raised exception)
r&   r"   r6   r)   is_aliver#   r!   RuntimeErrorr2   r<   )r   r   r7   s      r   r   zAsyncClosureHandler.runE   s     	,##G4#8((0//88:,//33%3@A&\	, 	, " ,/3D,))+,	, 	,s*   AB)(B B&#B)%B&&B))B2)d   )r   r   r   __doc__r   r<   r   __classcell__)r+   s   @r   r   r      s    (-.,r   r   c                      t               }|rdnd}t        ||d      }|g }t        |||       |j                  |f fd	       y)a  Adds a closure to the list of the ones to be run at the end of the step.
    Many times during model training there is the need to print/report (print to
    console, post to tensorboard, etc...) information which require the content of
    intermediary tensors to be inspected.
    Inspecting different tensors content in different points of the model code
    requires many executions and typically causes performance issues.
    Adding a step closure will ensure that it will be run after the barrier, when
    all the live tensors will be already materialized to device data.
    Live tensors which will include the ones captured by the closure arguments.
    So using `add_step_closure()` will ensure a single execution will be
    performed, even when multiple closures are queued, requiring multiple tensors
    to be inspected.
    Step closures will be run sequentially in the order they have been queued.
    Note that even though using this API the execution will be optimized, it is
    advised to throttle the printing/reporting events once every N steps.
    Args:
      closure (callable): The function to be called.
      args (tuple): The arguments to be passed to the closure.
      run_async: If True, run the closure asynchronously.
    async_step_closuresstep_closuresNc                      |  S r	   r
   )ar   s    r   <lambda>z"add_step_closure.<locals>.<lambda>q   s     r   )r   getattrsetattrappend)r   args	run_asyncdevctxclosures_typerE   s   `     r   add_step_closurerP   V   sM    *  !F-6)OMFM48M}5$34r   c                     t               } t        | dd       }|/g | _        t        | dd       }|t               }|| _         ||       t        | dd       }|/g | _        t        | dd       }|t               }|| _         ||       | S )NrD   async_closure_handlerrE   closure_handler)r   rI   rD   r   rR   rE   r   rS   )rN   rD   rR   rE   rS   s        r   run_step_closuresrT   t   s    !F!&*?F&%'" '0G N ($7$9!+@F(12FOT:M !!&*;TB",.O%4F"&Mr   )r
   F)r   r$   queuer   r2   r   torch._lazy.device_contextr   r   r   rP   rT   r
   r   r   <module>rW      s2    	  , 9 "9,. 9,x5<r   