o
    MeTL  ã                   @   sÊ   d dl Z d dlZd dlmZ d dlmZ d dlmZmZm	Z	 d dl
Z
eƒ r3eƒ s3d dlmZ dd„ ZndZdd„ Zg d	¢Zd aG d
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S )é    N)Úcore)Ú_hash_with_id)Úis_compiled_with_cudaÚis_compiled_with_rocmÚ	CUDAPlace)Ú	CUDAGraphc                   C   ó   dS )NT© r	   r	   r	   úID:\Projects\ConvertPro\env\Lib\site-packages\paddle/device/cuda/graphs.pyÚis_cuda_graph_supported   ó   r   c                   C   r   )NFr	   r	   r	   r	   r
   r      r   )ÚglobalÚthread_localÚrelaxedc                   @   s@   e Zd Zddd„Zdd„ Zdd„ Zd	d
„ Zdd„ Zddd„ZdS )r   Nr   c                 C   sZ   t d usJ dƒ‚d | _|d u rttj dd¡ƒ}t|ƒ}|| _|tv s%J ‚t 	|¡| _
d S )NzFCUDA Graph is only supported on PaddlePaddle compiled with NVIDIA GPU.ZFLAGS_selected_gpusr   )ÚCoreCUDAGraphÚ_graphÚintÚosÚenvironÚgetr   Ú_placeÚ	ALL_MODESÚindexÚ_mode)ÚselfZplaceÚmodeZ	device_idr	   r	   r
   Ú__init__(   s   zCUDAGraph.__init__c                 C   s   t  | j| j¡ d S ©N)r   Úbegin_capturer   r   ©r   r	   r	   r
   Úcapture_begin3   s   zCUDAGraph.capture_beginc                 C   s   t  ¡ | _d S r   )r   Úend_capturer   r   r	   r	   r
   Úcapture_end6   ó   zCUDAGraph.capture_endc                 C   ó   | j  ¡  d S r   )r   Úreplayr   r	   r	   r
   r%   9   r#   zCUDAGraph.replayc                 C   r$   r   )r   Úresetr   r	   r	   r
   r&   <   r#   zCUDAGraph.resetc                 C   sZ   t |ttfƒs
|j}tj|dd� tj |¡sJ d |¡ƒ‚|d u r$d}| j	 
||¡ d S )NT)ÚnameÚexist_okz$The dirname {} should be a directoryiÿ  )Ú
isinstanceÚstrÚbytesr'   r   ÚmakedirsÚpathÚisdirÚformatr   Úprint_to_dot_files)r   ÚdirnameÚflagsr	   r	   r
   r0   ?   s   ÿÿzCUDAGraph.print_to_dot_files)Nr   r   )	Ú__name__Ú
__module__Ú__qualname__r   r    r"   r%   r&   r0   r	   r	   r	   r
   r   &   s    
r   r   Údefaultc           
         s
  |t v sJ ‚t ¡ sAddlm} ttƒ}td7 a|dkrd}n|dkr(t ¡ }nt	d|ƒ‚||d t|ƒ d | ƒ‡ fdd	„ƒS dd
l
m} ddlm} |ˆ ƒ}tˆ |ƒrZ|j}	n|}	||	_|dkrhd|	_|S |dkrst ¡ |	_|S t||ƒr|jj|	_|S |j|	_|S )Nr   )Ú_cuda_graph_guardé   r6   ÚnewzFmemory_pool should be one of default or new under static mode, but gotú;c                     s   ˆ | i |¤ŽS r   r	   )ÚargsÚkwargs©Úfunctionr	   r
   Ú<lambda>\   s    z!wrap_cuda_graph.<locals>.<lambda>)Ú	to_static)ÚLayer)r   ÚpaddleZin_dynamic_modeZpaddle.fluid.frameworkr7   r*   Úcuda_graph_idr   Zgen_new_memory_pool_idÚ
ValueErrorZ
paddle.jitr@   Z	paddle.nnrA   r)   ÚforwardZ_cuda_graph_capture_modeZ_cuda_graph_pool_id)
r>   r   Zmemory_poolr7   Zgraph_idÚmemory_pool_idr@   rA   Znew_functionZ	mock_funcr	   r=   r
   Úwrap_cuda_graphJ   sL   
þÿÿ
þ
ù

ü
ÿrG   c                 C   sX   |   |j¡ |  |j¡ |  |j¡ |  |j¡ |  |j	¡ |  
|j¡ |  |j¡ dS )zÕ
    copy var desc from src to dst

    :param dst: framework.VarDesc(cpp), dst var desc, cpp VarDesc instance
    :param src: framework.VarDesc(cpp), src var desc, cpp VarDesc instance
    :return: no return
    N)Ú	set_shapeÚshapeZ	set_dtypeZdtypeZset_lod_levelZ	lod_levelÚset_typeÚtypeZset_persistableÚpersistableZset_is_parameterZis_parameterZset_stop_gradientÚstop_gradient)ÚdstÚsrcr	   r	   r
   Úcopy_var_descr   s   rP   c                 C   sD   g }t | jƒD ]\}}||krq|jD ]}| |¡ qqtt|ƒƒS )a1  
    find all inputs of ops after an idx, used to determine the logical output of a cuda graph section

    :param block: framework.Block, the original block
    :param begin_idx: int, from which idx (not include) to find the later ins
    :return: a list of inputs names for all ops behind begin_idx
    )Ú	enumerateÚopsÚinput_arg_namesÚappendÚlistÚset)ÚblockZ	begin_idxÚinsÚidxÚopÚin_namer	   r	   r
   Úall_inputs_of_later_opƒ   s   
ÿr\   c                 C   sN  t j ¡ }| ¡ }| ¡ }g }g }tj ¡ }t||d ƒ}	| D ]}}
|
jD ]=}| 	|¡}|j
 	|j d¡¡}t||ƒ | |¡dkrN| |¡dkrN| |¡ q$|	 |¡dkra| |¡dkra| |¡ q$|
jD ]"}| 	|¡}|j
 	|j d¡¡}t||ƒ | |¡dkr‡| |¡ qe|j
 ¡ }| |
j
¡ | ||
 |¡¡ q| ¡  |||gfS )aÞ  
    1. Construct a new program for corresponding section
    2. Find all the logical inputs and outputs of a program section

    :param section: list, one cuda graph section, list of ops
    :param origin_program: framework.Program, origin program
    :param section_idx: list, the section ops' idx corresponding to the cuda graph section, a list of idx
    :return: a new program for the cuda graph section
             the logical ins and outs of the cuda graph section
    éÿÿÿÿÚasciir   )rB   ZstaticZProgramÚglobal_blockr   Úop_proto_and_checker_makerÚkOpRoleAttrNamer\   rS   ÚvarÚdescr'   ÚencoderP   ÚcountrT   ÚremoveZoutput_arg_namesZ	append_opZ	copy_fromZ	_set_attrÚattrZ_sync_with_cpp)ÚsectionÚorigin_programÚsection_idxÚprogramrW   Úorigin_blockrX   ÚoutsÚop_role_attr_nameZ	later_insrZ   r[   rb   Znew_var_descZout_nameZnew_op_descr	   r	   r
   Ú#construct_program_and_find_ins_outs”   s:   





€



€
ro   c                 C   s¶  |   ¡ }g }g }d}g }g }g }g }d}	tj ¡ }
ttjjjƒ}ttjjjƒ}||B }t|j	ƒD �]\}}|j
dks?|j
dkrH|jdu sHJ dƒ‚| d¡rT| d¡rTd}|jdu�r-t|jtƒsdJ d	ƒ‚|j d
¡}t|ƒdkstJ dƒ‚t|d ƒ}||	k�rt|ƒdkrót|ƒt|ƒks‘J dƒ‚|D ]H}t| |
¡ƒ|kp¦t| |
¡|kƒ}|j
dkp°|j
dk}|sµ|rÛg }g }t|ƒt|ƒksÅJ dƒ‚t|ƒdkrÕ| |¡ | |¡ g }g } nq“tt|ƒƒD ]}| || ¡ | || ¡ qâg }g }| |¡ | |¡ q0g }g }|}	t|ƒt|ƒk�sJ dƒ‚t|ƒdk�r&| |¡ | |¡ |g}|g}q0| |¡ | |¡ q0t|ƒt|ƒk�sEJ dƒ‚t|ƒdk�rV| |¡ | |¡ |||fS )a  
    get all sections that should run under cuda graph and the corresponding idx

    :param program: framework.Program, the original program
    :return: A list of cuda graph sections and the corresponding ops' idx in the block.
             The program is under is test or not.
    Fr]   Zconditional_blockÚwhileNz9Cuda graph not support conditional block op and while op.Úis_testTzcuda_graph_attr should be a strr:   é   zccuda graph attr should have three fields: cuda graph mode, cuda graph memory pool id, cuda graph idé   r   z@len of internal section should be equal with len of internal idxz-num of section's op is not equal with the idxz0num of section's op is not equal with num of idx)r_   r   r`   ra   r   ZOpRoleZLossZBackwardrQ   rR   rK   Ú_cuda_graph_attrZhas_attrrg   r)   r*   ÚsplitÚlenrT   Úrange)rk   rW   Úcuda_graph_sectionsÚsections_idxrq   Zinternal_sectionZinternal_idxZcurrent_sectionZcurrent_idxZcurrent_cuda_graph_idrn   Zloss_op_roleZbackward_op_roleZloss_grad_op_rolerY   rZ   Zcuda_graph_attrsZlocal_cuda_graph_idZinternal_opZloss_relatedZsub_block_relatedÚir	   r	   r
   Úget_cuda_graph_sectionsÈ   s¶   
ÿÿ
ÿþÿÿÿÿ
ÿ
ÿ

ë

ÿþ



ÿÿ


r{   c                 C   s.  | d }| d }|d }	|  ¡ }
t|ƒD ]	}|
j|dd� qd}d}|D ]}|jdur=|j d¡}|d }t|d ƒ} nq$|durF|dusJJ dƒ‚|
jdt|ƒ tj	j
jd	d	d
�}|
jdt|ƒ tj	j
jd	d	d
�}t|| ƒ}|
j|	dd|i|||dœ|  ¡ dt|  ¡ jƒ||||d|  ¡ |  ¡ dœ
d� dS )a÷  
    Use section_program and ins_and_outs to initialize a run_program_op,
    and replace the section_idx marks ops in the origin program.

    :param ins_and_outs: list, the logical ins and outs of the section program
    :param section_program: framework.Program, the partial program need to run under cuda graph
    :param section_idx: list, the idx need to be removed from origin program
    :param origin_program: framework.Program, the origin program
    :param cuda_graph_section: list, the ops in current sections, used to get the mode, memory pool id and is_test
    :param order: int, the order of current section, used to create unique cuda graph var
    :param is_test: bool, the program is running under is_test or not
    :return: no return
    r   r8   F)ZsyncNr:   z>mode and memory pool id should be specified in cuda graph attrZcuda_graph_T)r'   rK   rL   rM   Zprogram_out_scope_Zrun_programÚX)ZOutZOutScoper   )
r_   Zstart_op_indexZend_op_indexrq   Ú
program_idZcuda_graph_capture_modeZcuda_graph_pool_idZuse_interpretorcoreZforward_global_blockZbackward_global_block)rK   ZinputsZoutputsÚattrs)r_   ÚreversedZ
_remove_oprt   ru   r   Z
create_varr*   r   ZVarDescZVarTypeZRAWZSTEP_SCOPESr   Z
_insert_oprv   rR   )Úins_and_outsÚsection_programrj   ri   Zcuda_graph_sectionÚorderrq   rX   rm   Z
insert_idxrl   rY   r   rF   rZ   r~   Zcuda_graph_varZout_scope_varr}   r	   r	   r
   Úreplace_cuda_graph_section7  sf   
üÿ
ü
ü
ýõ
÷rƒ   c           	   
   C   sÜ   t | jƒdkrt d¡ t| ƒ\}}}t |ƒt |ƒksJ dƒ‚g }g }tt |ƒƒD ]}t|| | || ƒ\}}| |¡ | |¡ q)t |ƒt |ƒksNJ dƒ‚ttt |ƒƒƒD ]}t	|| || || | || ||d� qV|S )zí
    replace the ops marked with cuda_graph_attr to run_program_op to use cuda graph

    :param program: framework.Program, the program to be transformed
    :return: the cuda graph section program, user should hold these programs!
    r8   z‚Sub block(s) has been detected in the program. Cuda graph not support op with sub block, and it will only handle the global block.z@num of cuda graph sections is not equal with num of idx sectionszJthe num of cuda graph sections should be equal with the num of new program)r‚   rq   )
rv   ÚblocksÚwarningsÚwarnr{   rw   ro   rT   r   rƒ   )	rk   rx   ry   rq   r€   Zsection_programsrz   r�   Zins_outsr	   r	   r
   Úcuda_graph_transformˆ  s>   ÿ
ÿÿÿ
ÿú	r‡   )r   r6   )r   rB   Zpaddle.fluidr   Zpaddle.fluid.layers.utilsr   Zpaddle.fluid.corer   r   r   r…   r   r   r   r   rC   rG   rP   r\   ro   r{   rƒ   r‡   r	   r	   r	   r
   Ú<module>   s*   

$(4oQ