
    /j>                        d dl Z d dlmZ d dlmZmZ d dlZd dlm	Z	 d dl
mZ g dZ G d dej        j                  Z	 dd
ej        j        dededeej        j        ej        j        f         fdZdej        j        dedefdZ	 	 ddeej        j        ej        j        f         deeej        j        gef                  dedefdZdS )    N)Callable)OptionalUnion)map_arg)split_module)FoldedGraphModuleget_unique_attr_name_in_modulesplit_const_subgraphsc                        e Zd ZdZ	 	 	 ddej        j        dej        j        de	ej        j                 de	e
         de
f
 fd	Z fd
Zd Z xZS )r   a  
    FoldedGraphModule is a GraphModule which also contains another
    `const_subgraph_module` representing a subgraph which has all const attr
    inputs and which can be run once before running the main standard
    `graph`. The `const_output_names` are the ordered list names of attrs which
    represent what each respective output from the const_subgraph should be set
    on which attrs.
    Ncudarootgraphconst_subgraphfx_const_folded_attrs_namedevice_for_folded_attrsc                     t                                          ||           |d nt          j                            ||          | _        d| _        || _        || _        d S )NF)	super__init__torchfxGraphModuleconst_subgraph_modulehas_folding_been_runr   r   )selfr   r   r   r   r   	__class__s         e/home/longshao/multi-rider-rag/.venv/lib/python3.11/site-packages/torch/fx/experimental/const_fold.pyr   zFoldedGraphModule.__init__   sk     	u%%% % D%%dN;; 	"
 %*!*D''>$$$    c                 f    | j         s|                                   t                      j        | S N)r   run_foldingr   __call__)r   argskwargsr   s      r   r!   zFoldedGraphModule.__call__.   s4    ( 	uww&&r   c                 X     j          j        d S  j        rt          d          d _                                          } fdt	          |t
                    r+t          j                            fd|D                       n
 |          }t            j        |           d S )NzFolding has already been runTc                 V   t           j                            t          | t                    s&|                                                                 n-t          j        | g                              j	                  t          | t           j                  r| j
        nd          S )N)deviceF)requires_grad)r   nn	Parameter
isinstanceintdetachcloneTensortor   r'   )ir   s    r   _create_paramz4FoldedGraphModule.run_folding.<locals>._create_paramE   s    8%%!!S))O

  """\1#&&))1M)NN1;Au|1L1LWaooRW	 &   r   c                 &    g | ]} |          S  r3   ).0r0   r1   s     r   
<listcomp>z1FoldedGraphModule.run_folding.<locals>.<listcomp>N   s#    #K#K#KMM!$4$4#K#K#Kr   )
r   r   r   AssertionErrorr*   tupler   r(   ParameterListsetattr)r   folded_attrsparamsr1   s   `  @r   r    zFoldedGraphModule.run_folding3   s     &..6F$ 	A !?@@@$(!
 1133	 	 	 	 	 ,..-EH""#K#K#K#Kl#K#K#KLLL|,, 	
 	d5v>>>>>r   )NNr   )__name__
__module____qualname____doc__r   r(   Moduler   Graphr   strr   r!   r    __classcell__)r   s   @r   r   r      s          4848'-? ?ho? x~? !0	?
 %-SM? "%? ? ? ? ? ?$' ' ' ' '
? ? ? ? ? ? ?r   r   Tgminline_mod_namerun_dcereturnc                    t          |                                           |         }t          |t          j        j                  st          dt          |                     d}| j        j	        D ]}|j
        dk    r|j        |k    r|} n|t          d|           |j        }|j        }i d}fd}	|j        j	        D ]}
|
j
        dk    r'|
j        |v r||
j                 n||         |
<   |dz  }5|
j
        d	k    r|
j        d         }t          ||	          }g }t          |t           t"          f          rddlfd
|j        D             }|                    |           |D ]}|j        d         }t          |t*                    st          dt          |                     |                    ||                    | j                            |           ||         |<   /| j                            |          5  | j                            |
|	          }ddd           n# 1 swxY w Y   ||
<   | j                            |           |r| j                                         S )a  
    Given `gm` and some graph module which is called with target name `inline_mod_name`,
    this helper will inline all of the nodes from that called graph module into `gm`.

    Returns a mapping from subgraph nodes to the newly created/mapped nodes in gm.
    zExpected GraphModule, got Ncall_modulez$Could not find call_module node for r   c                 T    |          }| j                                         |_         |S r   )metacopy)nodenew_nodereplacement_mappings     r   replacement_fnz&_inline_module.<locals>.replacement_fnr   s%    &t,	((r   placeholder   outputc                     g | ]=}|j         d k    r0|j        j        u t          |j        d         t
                    ;|>S )call_functionrR   )optargetgetitemr*   r"   r+   )r4   useroperators     r   r5   z"_inline_module.<locals>.<listcomp>   sZ     ! ! !w/11x'777"49Q<55 8  877r   zExpected int index, got )dictnamed_modulesr*   r   r   r   r6   typer   nodesrV   rW   r"   r#   namer   listr7   rZ   usersreplace_all_uses_withr+   
erase_nodeinserting_before	node_copyeliminate_dead_code)rD   rE   rF   
inline_modcall_mod_node_to_replacerM   call_mod_argscall_mod_kwargsph_countrP   inline_nodeoutputsoutput_replacementsgetitem_usersrY   idxrN   rZ   rO   s                    @@r   _inline_modulerq   U   sT    b&&(())/:Jj%("677 NL$z:J:JLLMMM#  7m##(F(F'+$E'UOUUVVV -1M.5O>@H    
 "'- ,4 ,4>]** #66   011"8,  , MH>X%%!&q)G")'>"B"B 24M-e}== 	! ! ! ! 8 >! ! ! %::;NOOO & E Eil!#s++ Q()ODII)O)OPPP**+>s+CDDD##D))),?,D#D))X&&'?@@ 	G 	Gx))+~FFH	G 	G 	G 	G 	G 	G 	G 	G 	G 	G 	G 	G 	G 	G 	G+3K((
 H0111 '
$$&&&s   H;;H?	H?	
mod_tracedr_   c                 J   t          j        dd|          }|d                                         rd| }t          | |          r]t          j        d|          }||dz   }n0|                    dd          \  }}| dt          |          dz    }t          | |          ]|S )	zP
    Make sure the name is unique (in a module) and can represents an attr.
    z[^0-9a-zA-Z_]+_r   z(.*)_(\d+)$N_1rR      )resubisdigithasattrmatchgroupr+   )rr   r_   r{   basenums        r   r	   r	      s    
 6"C..DAw 4zz
*d
#
# ,..=$;DDAq))ID#++SXX\++D *d
#
# , Kr   cpumoduleskip_folding_node_fnr   c           	      8   ddl }t          | t          j        j                  s t          j                            |           }n| }dt          j        j        dt          ffdt                      d}|j        j	        D ]}|j
        dv r|j
        dk    r(t          |j                                                s@|r ||          rN|                                rct          |j                            d	d          |j                  r|j
        d
k    rG|                    |j                  x}r+t          |t          j        j                  r |          r                    |           |j
        dk    rd}|st)          ||j                  S dt          j        j        ffd}t-          || |          }	d\  }
}|	j        t1          |	|d          }}|r|j        j	        ng D ]6}|j
        d
k    r)t3          |	|j        t1          ||j                             7|j        j	        D ]6}|j
        d
k    r)t3          |	|j        t1          ||j                             7d}|	j        j	        D ]!}|j
        d
k    r|j        |
k    r	|j        } n"|t7          d          t          j                            |	|j                  }d}|j        j	        D ]>}|j
        dk    r!t          |j        d         t8                    }/|j
        dk    r;|t;          |          k    r#t7          d| dt;          |           d          ||         }|dz  }|j
        dk    rt7          d|j
                   |j                            |          5  |j                            |j                  }ddd           n# 1 swxY w Y   |j         !                                |_         |"                    |           |j        #                    |           @dtI                      vrt7          d          tK          |d          }t3          |	||rt          j&        '                                nt          j&        (                                           |	j        j	        D ]}|j
        d
k    r|j        |
k    r|j                            |          5  |j                            |          }ddd           n# 1 swxY w Y   |j         !                                |_         |"                    |            ntS          |	|          rtU          |	|           |	j        +                                 t)          |	|	j        |j        ||          S )aJ  
    Looks through `module` for any nodes that have all constant attribute inputs
    and separates them out into their own constant subgraph, and returns a
    FoldedGraphModule which runs that constant subgraph on the first run to set
    attributes on the module prior to running the non-constant portion of the
    graph.
    r   Nr   rG   c                 l   t          | t          j        j                  st	          d          | j        j        D ]w}|j        dk    r|                                r dS |j        dk    rH| 	                    |j
                  x}r,t          |t          j        j                  r |          c S xdS )z`
        Return True if a GraphModule type subgraph contains any impure op, else False.
        zDcaller should only pass GraphModule to subgraph_has_impure_ops checkrU   TrI   F)r*   r   r   r   r6   r   r^   rV   	is_impureget_submodulerW   )r   rM   	submodule_subgraph_has_impure_opss      r   r   z7split_const_subgraphs.<locals>._subgraph_has_impure_ops   s     &%("677 	 V   L& 		; 		;Dw/))dnn.>.>)tt=(("("6"6t{"C"CCY ) y%(*>?? )
 0/	:::::ur   F>   rS   rQ   get_attr
fill_valuerI   TrM   c                     | v rdndS )Nr   rR   r3   )rM   const_nodess    r   mod_partitionz,split_const_subgraphs.<locals>.mod_partition  s    K''qqQ.r   )submod_0submod_1z,Could not find call_module node for const_gmrS   rQ   zPlaceholder index z out of range for args (len=)rR   zExpected get_attr, got multiple_outputsz multiple_outputs not set in loop_FX_CONST_FOLDED_ATTRS),sympyr*   r   r   r   symbolic_traceboolsetr   r^   rV   all_input_nodesissubsetr   r#   getExprr   rW   addr   Noder   r   getattrr9   r"   r6   r7   lenrd   r   rK   rL   rb   rc   localsr	   r(   r8   r)   rz   rq   rf   )r   r   r   r   rr   found_const_foldingrM   
target_modr   splitconst_mod_namenon_const_mod_nameconst_gmnon_const_gmcall_const_gm_argsroot_const_gmph_idxr   in_noderN   r   r:   r   r   s                         @@r   r
   r
      s    LLLfeh233 X,,V44


)= $      , '*eeK & &' &' 7/// 7j  T-A)B)B)K)K*
 *
     	$8$8$>$> 	 >> 	 dkoolD995:FF 	 G}$$)77DDD % :ux';<< % )(44	 %  	7j  "&  ? Z-=>>>/EHM / / / / / / V];;E)?&N&"^WU<NPT-U-UlH
 -9@"((b L L7m##E4;dk(J(JKKK$ H H7m##E4;$+(F(FGGG !  7m##{n,,%)Y"!KLLL H((??M
 F#) - -7h)$)A,>>7m##S+,,,, 3V 3 3.//3 3 3   %V,!:## !G7:!G!GHHH 11$77 	D 	D$*33GNCCH	D 	D 	D 	D 	D 	D 	D 	D 	D 	D 	D 	D 	D 	D 	D	((""8,,,&&t,,,,))?@@@ "@," " "$4N   %(:L:L:N:N  
 !  7m##~(E(E,,T22 O O#z223MNNO O O O O O O O O O O O O O O $	 0 0L&&|444E
 u()) 2u0111	K##%%%"  s$    O

O	O	TT		T		)T)Nr   )rw   collections.abcr   typingr   r   torch.fxr   torch.fx.noder   torch.fx.passes.split_moduler   __all__r   r   r   rB   r   r[   r   rq   r	   r(   r@   r
   r3   r   r   <module>r      s   				 $ $ $ $ $ $ " " " " " " " "  ! ! ! ! ! ! 5 5 5 5 5 5  @? @? @? @? @?, @? @? @?H EIW WW/2W=AW	%(-
&'W W W Wtux/C 3 SV    , GK#(H H%(/58#778H"8UX]OT,A#BCH !H 	H H H H H Hr   