o
    ir5                     @   s   d dl Z d dlmZ d dlm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mZ d dlZG dd dZeG d	d
 d
ZeG dd dZdefddZdd Zd dlmZ edd Zdd Zdd ZdS )    N)innermost_fn)_debug_get_cache_entry_list)CodeType)ListCallableDictUnionSet)	dataclassc                   @   s   e Zd ZU i Zeed f ed< e Ze	e ed< e
defddZe
defddZe
dd	edefd
dZd	efddZdd Zeje
dd ZdS )	CodeProxy	instancesused_instancesnamec                 C   sL   d}| }| dr$| d d } 	 |  d| }|tjvr	 |S |d7 }q|S )Nr   :T_   )endswithr   r   )r   inew_name r   P/home/ubuntu/veenaModal/venv/lib/python3.10/site-packages/depyf/explain/utils.pyget_new_name   s   

zCodeProxy.get_new_namec                 C   s   t | }d t j|< |S N)r   r   r   )r   r   r   r   r   consume_new_name   s   

zCodeProxy.consume_new_nameFcodec                 C   s   ddl m} t| dr| j} | jds| jdr%t| j }| j}nt	
|}|s2|| |}nd}t	|}||_d|j d|j d	|_|t	j|j< |S )
Nr   )decompile_ensure__code__transformed_code___transformed_code_ z<details>
  <summary>z</summary>

  ```python
z
  ```
</details>
)depyf.utilsr   hasattrr   co_name
startswithopenco_filenamereadr   r   r   raw_coder   r   )r   r   skip_decompiler   srcr   selfr   r   r   decompile_with_name#   s&   


zCodeProxy.decompile_with_namec                 C   s   d dd | D | _d S )Nr    c                 S   s$   g | ]}|  d krd| d qS )r    z  
)strip.0liner   r   r   
<listcomp>A   s   $ z&CodeProxy.__init__.<locals>.<listcomp>)join
splitlinesr(   )r+   r   r   r   r   __init__>   s   
zCodeProxy.__init__c                 C   s   t j| j | jS r   )r   r   addr   r+   r   r   r   __str__C   s   zCodeProxy.__str__c                   c   s    t  t_tjV  d S r   )setr   r   r   r   r   r   recordG   s   zCodeProxy.recordN)F)__name__
__module____qualname__r   r   str__annotations__r9   r   r	   staticmethodr   r   r   r,   r5   r8   
contextlibcontextmanagerr:   r   r   r   r   r      s   
 r   c                   @   sb   e Zd ZU eed< eed< ee ed< eed< eed< eed< e	edf ed< d	d
 Z
dd ZdS )CacheResultoriginal_codetransformed_codeguardcompiled_subgraphcompiled_subgraph_proxytransformed_code_proxyDynamoOptimizationResultreferenced_global_functionsc                    s  || _ d}t|drdnd}t||}z&ttjjdd p,ttjjdd p,ttjjjdd }|d us3J t||}W n	 tyB   Y nw |sU|j	}|j
j}	dd |jD }
n=d  fdd	g }|j}|| t|d
ry| D ]}t|| qq|jd u rt }	g }
nt|j }	t|j }
|| _dd t|	|
D | _|j}dd |jD }t|dksJ |rt||d  | _tj| j|d dd| _nd | _d | _|| _ t| j d| _!dd |jD }i | _"|D ]}t#|| j
||d| j"|< qd S )NFguard_managercheck_fnGuardManagerWrapperGuardManagerc                 S   s   g | ]}|j qS r   )cell_contents)r0   xr   r   r   r2   r   s    z(CacheResult.__init__.<locals>.<listcomp>c                    sR   |   D ]}t|tjjjjr sd nqt|| q|  D ]}|| qd S )NT)	get_leaf_guards
isinstancetorch_C_dynamoguardsNO_TENSOR_ALIASINGappend_guard_codeget_child_managers)rootans
leaf_guardchildtensor_aliasing_guard_seenvisitr   r   ra   w   s   z#CacheResult.__init__.<locals>.visitget_epilogue_lambda_guardsc                 S   s   i | ]\}}||qS r   r   r0   r   valuer   r   r   
<dictcomp>   s    z(CacheResult.__init__.<locals>.<dictcomp>c                 S      g | ]	}| d r|qS )
__compiledr$   r0   r   r   r   r   r2      
    
r   r   T)r)   ztransformed_code:c                 S   rf   )__resumerh   ri   r   r   r   r2      rj   )rD   function_namemodule)$rD   r"   getattrrT   rV   rW   rU   rS   	Exception
code_partsr   co_freevars__closure__r[   rb   rY   closure_varstuplekeyslistvaluesrF   zipfreevarsr   co_nameslenr   rG   r   r,   rH   rE   rI   rK   rJ   )r+   rD   rm   cache	cpp_guard	attr_namerL   klassguard_codesfreevar_namesfreevar_valuesr[   lambda_guardr   compiled_subgraphs
resume_fnsr   r   r_   r   r5   X   sz   




zCacheResult.__init__c                 C   s:   | j t| j| jd urt| jnddd | j D dS )Nz"No compiled subgraph."c                 S   s   i | ]	\}}||  qS r   to_data)r0   r   fnr   r   r   re      s
    z'CacheResult.to_data.<locals>.<dictcomp>)rF   rE   rG   rK   )rF   r>   rI   rH   rK   itemsr7   r   r   r   r      s   
zCacheResult.to_dataN)r;   r<   r=   r   r?   r   r>   r   r   r   r5   r   r   r   r   r   rC   N   s   
 YrC   c                   @   sT   e Zd ZU eed< eed< eed< eed< ee	 ed< dddZ
d	d
 Zdd ZdS )rJ   rl   rm   rD   source_code_proxytransformed_code_entriesNc                    sX   | _ |d u rj| _n|| _ | _t} fdd|D | _t| j | j| _d S )Nc                    s   g | ]}t  |qS r   )rC   )r0   r|   rm   rD   r   r   r2      s    z5DynamoOptimizationResult.__init__.<locals>.<listcomp>)	rD   r#   rl   rm   r   r   r   r,   r   )r+   rD   rl   rm   cachesr   r   r   r5      s   

z!DynamoOptimizationResult.__init__c                 C   s$   | j t| jdd | jD d}|S )Nc                 S   s   g | ]}|  qS r   r   )r0   entryr   r   r   r2      s    z4DynamoOptimizationResult.to_data.<locals>.<listcomp>)rl   source_coder   )rl   r>   r   r   )r+   datar   r   r   r      s   z DynamoOptimizationResult.to_datac              	   C   sN  | j j}| d ddd}| }| j}|j|j }|jd | }dd	dd |D  d	 }|d
| 7 }|d7 }d}| j
D ]}	d	dd |	j D }
|
rUd|
 }
dg}|	jD ]}|dd| d  q[|d d	|}|	jjdr|	jjdd}ntd}|d|
 d| d | 7 }|	jd ur|	jj}|d7 }|d| d7 }|d7 }|d7 }|d7 }|d7 }|d7 }|d| d7 }|dt|	jj d 7 }|	j D ]
\}}| | }q|d
d | d! d" d#|	jj d$d	| d% 7 }q@|d&t| j j d 7 }|d'd#| j j d$d	| d% 7 }|| d(| j d) S )*Nr   zdef zdef transformed_r   z__local_dict = {z, c                 S   s   g | ]
}d | d| qS )"z": r   ri   r   r   r   r2          z3DynamoOptimizationResult.to_src.<locals>.<listcomp>}z
    z
    __global_dict = globals()r    c                 S   s(   g | ]\}}|d vr| d| dqS ))__builtins__z = '''z'''
r   rc   r   r   r   r2      s   ( zD# Note: the following variables are used inside the guard function.
z    __guard_hit = True
z    z__guard_hit = __guard_hit and r-   z    return __guard_hit
r   __guard_zguard:z(L, G, **___kwargs_ignored):
z*# Note: please refer to the graph code in z*.py.
zP# Captured Graph: Dynamo generated graph (debuggable when using eager backend).
z?# Joint graph: joint forward+backward graph from aot autograd.
z\# Forward graph: forward graph from aot autograd (debuggable when using aot_eager backend).
z^# Backward graph: backward graph from aot autograd (debuggable when using aot_eager backend).
z;# AFTER XXX: graph processed by inductor (not debuggable).
z(*args, **kwargs):
    pass
zif z(__local_dict, __global_dict):
z        zreturn ()z
# Note: if there is a transformed version below, this function might well not be executed directly. Please check the transformed version if possible.
z
    # Note: this function might well not be executed directly. It might well be transformed again, i.e. adding one more guards and transformed code.
    z

#============ end of z ============#
)r   r(   r4   replacer.   rD   co_argcountco_kwonlyargcountco_varnamesr3   r   ry   r   rF   appendrI   r   r$   r   r   rH   remove_indentationrK   to_srcrl   )r+   r(   	signaturer   code_objnormal_arg_count	arg_namesarg_dictadditional_coder   ry   guard_linesrQ   rF   guard_func_namesubgraph_namer   funcr   r   r   r      s   








zDynamoOptimizationResult.to_src)NN)r;   r<   r=   r>   r?   dictr   r   r   rC   r5   r   r   r   r   r   r   rJ      s   
 
	rJ   r   c                    s<   |   }t|d t|d    d fdd|D S )Nr   r    c                    s   g | ]
}| d  d qS )Nr-   r   r/   indentr   r   r2   #  r   z&remove_indentation.<locals>.<listcomp>)r4   r{   lstripr3   )r   linesr   r   r   r      s   r   c                 C   s$   |   D ]}| }|| qd S r   )verbose_code_partsr.   r   )rF   r\   verbose_strr   r   r   rY   %  s   rY   )rB   c                 c   s^    | d }ddl m} dd l}||}z| d V  W d    W d S 1 s&w   Y  W d S w )Nz.lockr   )FileLock)filelockr   os)path_template	lock_pathr   r   lockr   r   r   lock_on_file,  s   r   c              	   C   s   t |H dd l}d}	 |t| }|j|s3t|d}||  W d    n1 s-w   Y  nt| }|| kr>n|d7 }q|W  d    S 1 sOw   Y  d S )Nr   Twr   )r   r   r>   pathexistsr%   writer'   )r*   r   r   countnew_filepathfexisting_coder   r   r   write_code_to_file_template9  s"   
$r   c                  C   s<   dd l } ddlm} ddlm} t||d }dt| S )Nr   )_unique_id_counter)copyr   __compiled_fn_)rT   %torch._dynamo.bytecode_transformationr   r   nextr>   )rT   r   r   current_countr   r   r   get_current_compiled_fn_nameK  s
   r   )rT   torch._dynamo.eval_framer   r   inspectdistypesr   typingr   r   r   r   r	   dataclassesr
   rA   r   rC   rJ   r>   r   rY   rB   r   r   r   r   r   r   r   <module>   s*    Bnb
