o
    h\                     @   s   d dl Z d dlZd dlZd dlZd dlZd dlmZ d dlmZm	Z	m
Z
mZmZ d dlZd dlmZ d dlmZ d dlmZ G dd de jZG d	d
 d
eZdeejje	f deejje	f fddZdS )    N)FunctionType)AnyCallablecastOptionalUnion)normalize_source_lines)Tracer)Graphc                   @   s6   e Zd ZdZejjdefddZdd Z	dd Z
d	S )
AST_Rewriterax  
    Take a FunctionType object representing a `forward` method, then
    perform an AST rewrite to swap out nodes that are not symbolically
    traceable with a callsite to the FX alternative.

    To support swapping out an AST node, define a new `visit` method on
    that node. For more details, see:
    https://docs.python.org/3/library/ast.html#ast.NodeTransformer
    fnc                 C   s   t |\}}t|}d|}t|}t|}t| 	|}t
|dd}t|j}	t|	 }
t||	 tt|	 |
 }t|dksKJ |	|d  }dd }|||jdS )N exec   r   c                 S   s8   t | j|| j| j| jd}t|| }t| j|_|S )z?Based on https://stackoverflow.com/a/13503277/2988730 (@unutbu))nameargdefsclosure)	r   __code____name____defaults____closure__	functoolsupdate_wrappercopy__kwdefaults__)fglobalsg r   r/var/www/html/construction_image-detection-poc/venv/lib/python3.10/site-packages/torch/fx/experimental/rewriter.pychange_func_globals6   s   z1AST_Rewriter.rewrite.<locals>.change_func_globals)r   )inspectgetsourcelinesr   jointextwrapdedentastparsefix_missing_locationsvisitcompiler   __globals__setkeysr   listlen)selfr   sourcelines_sourcenormalized_str
source_astdest_astcodeglobals_dictkeys_beforenew_keysfn_compiledr    r   r   r   rewrite    s   



zAST_Rewriter.rewritec                 C   sr   t jddd}t|t jsJ |j}t|t jsJ |jr |jnt jddd}|j|g|_	t j
|d}t ||S )z
        Swap out the Assert node (Python's `assert`) with a callsite to the
        symbolically-traceable torch._assert function
        ztorch._assert()eval)moder   N)valuekind)r?   )r&   r'   
isinstance
ExpressionbodyCallmsgConstanttestargsExprcopy_location)r0   noden	call_noderE   expr_wrapperr   r   r   visit_AssertH   s   zAST_Rewriter.visit_Assertc                 C   s4   t j|jgt jt jdt  d|j|jgg ddS )a  
        Swap out Python's AnnAssign with an Assign node where the annotation function is called.
        Example:
             Original:
             y: Tensor_Type(1,2,3, Dyn) = f2(x)
            Output:
             y = annotate(f2(x),Tensor_Type((1,2,3,Dyn)))
        annotate)idctx)funcrH   keywords)targetsr?   )r&   AssigntargetrD   NameLoadr?   
annotation)r0   rK   r   r   r   visit_AnnAssign\   s   	
zAST_Rewriter.visit_AnnAssignN)r   
__module____qualname____doc__torch_dynamodisabler   r<   rO   r[   r   r   r   r   r      s    'r   c                       sF   e Zd Z	ddeejjef dee	e
ef  def fddZ  ZS )RewritingTracerNrootconcrete_argsreturnc                    s   t  t||S N)supertrace_rewrite)r0   rc   rd   	__class__r   r   rh   p   s   zRewritingTracer.tracerf   )r   r\   r]   r   r_   nnModuler   r   dictstrr   r
   rh   __classcell__r   r   rj   r   rb   o   s    rb   r   re   c                    s>   t | tjjrdtjjf fdd  | S t tt| S )Nmc                    s6   G  fdddt jj}t tt| j|_|| S )Nc                       s   e Zd Z fddZ  ZS )z9_rewrite.<locals>.rewrite_module.<locals>.RewrittenModulec                    sV   t    |j D ]\}}t|tjjr t|| j|< q
t|| j|< q
d S rf   )	rg   __init____dict__itemsrA   r_   rl   rm   r   )r0   origkv)rk   rewrite_moduler   r   rr      s   
zB_rewrite.<locals>.rewrite_module.<locals>.RewrittenModule.__init__)r   r\   r]   rr   rp   r   rx   rj   r   RewrittenModule~   s    rz   )r_   rl   rm   r   r<   r   r   forward)rq   rz   ry   r   r   rx   }   s
   	
z _rewrite.<locals>.rewrite_module)rA   r_   rl   rm   r   r<   r   r   )r   r   ry   r   ri   x   s   ri   )r&   r   r   r!   r$   typesr   typingr   r   r   r   r   r_   torch._sourcesr   torch.fx._symbolic_tracer	   torch.fx.graphr
   NodeTransformerr   rb   rl   rm   ri   r   r   r   r   <module>   s   ^.	