
    ^j7A                        d dl Z d dlmZ d dl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j*                  j,                  ej                  j                  z  deej                  j$                  gef   dz  dedefdZy)    N)Callable)Any)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j                  j                  dz  de	dz  de	ddf fd	Z
d
ededef fdZd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rootgraphconst_subgraphfx_const_folded_attrs_namedevice_for_folded_attrsreturnc                     t         |   ||       |d nt        j                  j	                  ||      | _        d| _        || _        || _        y )NF)	super__init__torchfxGraphModuleconst_subgraph_modulehas_folding_been_runr   r   )selfr   r   r   r   r   	__class__s         k/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/torch/fx/experimental/const_fold.pyr   zFoldedGraphModule.__init__   sW     	u% % %%dN; 	"
 %*!*D''>$    argskwargsc                 T    | j                   s| j                          t        |   | S N)r   run_foldingr   __call__)r   r   r   r   s      r   r"   zFoldedGraphModule.__call__-   s(    ((w&&r   c                      j                    j                  y  j                  rt        d      d _         j                         }dt        j
                  t        z  dt        j                  j                  f fd}t        |t              r3t        j                  j                  |D cg c]
  } ||       c}      n ||      }t          j                  |       y c c}w )NzFolding has already been runTir   c                 T   t         j                  j                  t        | t              s| j                         j                         n/t        j                  | g      j                  j                        t        | t         j                        r| j                        S d      S )N)deviceF)requires_grad)r   nn	Parameter
isinstanceintdetachcloneTensortor   r'   )r$   r   s    r   _create_paramz4FoldedGraphModule.run_folding.<locals>._create_paramD   s    88%%!!S) 
  "\\1#&))1M1M)N1;Au||1Laoo	 &   SX	 &  r   )r   r   r   AssertionErrorr   r.   r+   r(   r)   r*   tupleParameterListsetattr)r   folded_attrsr0   r$   paramss   `    r   r!   zFoldedGraphModule.run_folding2   s     &&...6$$ !?@@$(!
 113	U\\C/ 	EHH4F4F 	 ,. HH""l#KM!$4#KL|, 	
 	d55v>	 $Ls   -C#)NNcuda)r   N)__name__
__module____qualname____doc__r   r(   Moduler   Graphstrr   objectr   r"   r!   __classcell__)r   s   @r   r   r      s     1515'-?hhoo? xx~~? -	?
 %($J? "%? 
?$'f ' '3 '
?r   r   gminline_mod_namerun_dcer   c                     t        | j                               |   }t        |t        j                  j
                        st        dt        |             d}| j                  j                  D ]%  }|j                  dk(  s|j                  |k(  s#|} n |t        d|       |j                  }|j                  }i d}dt        j                  j                  dt        j                  j                  ffd}	|j                  j                  D ]  }
|
j                  d	k(  r+|
j                  |v r||
j                     n||   |
<   |d
z  }>|
j                  dk(  r|
j                  d   }t!        ||	      }g }t        |t"        t$        f      raddl}|j(                  D cg c]H  }|j                  dk(  r7|j                  |j*                  u rt        |j                  d
   t,              r|J }}|j/                  |       |D ]o  }|j                  d
   }t        |t,              st        dt        |             |j/                  ||          | j                  j1                  |       ||   |<   q i| j                  j3                  |      5  | j                  j5                  |
|	      }ddd       |
<    | j                  j1                  |       |r| j                  j7                          S c c}w # 1 sw Y   OxY w)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   noder   c                 P    |    }| j                   j                         |_         |S r    )metacopy)rF   new_nodereplacement_mappings     r   replacement_fnz&_inline_module.<locals>.replacement_fnq   s$    &t,		(r   placeholder   outputcall_functionzExpected int index, got )dictnamed_modulesr*   r   r   r   r1   typer   nodesoptargetr   r   Nodenamer   listr2   operatorusersgetitemr+   replace_all_uses_with
erase_nodeinserting_before	node_copyeliminate_dead_code)rA   rB   rC   
inline_modcall_mod_node_to_replacerF   call_mod_argscall_mod_kwargsph_countrL   inline_nodeoutputsoutput_replacementsgetitem_usersrZ   useridxrJ   rK   s                     @r   _inline_modulerm   T   s    b&&()/:Jj%(("6"679$z:J9KLMM# 77m#(F'+$  'COCTUVV -11M.55O>@HUXX]] uxx}} 
 "''-- ,4>>]* ##6   0 01"8,  , MH>>X%!&&q)G")'>"B 24M-e}= !9 > >!ww/1x'7'77"499Q<5	 ! ! %::;NO & Eiil!#s+(+CDI;)OPP**+>s+CD##D),?,D#D)E XX&&'?@ 	Gxx))+~FH	G+3K(Y,4b HH01
$$&A!*	G 	Gs   (AK?LL	
mod_tracedrX   c                 "   t        j                  dd|      }|d   j                         rd| }t        | |      rSt        j                  d|      }||dz   }n(|j                  dd      \  }}| dt        |      dz    }t        | |      rS|S )zP
    Make sure the name is unique (in a module) and can represents an attr.
    z[^0-9a-zA-Z_]+_r   z(.*)_(\d+)$_1rN      )resubisdigithasattrmatchgroupr+   )rn   rX   rw   basenums        r   r   r      s    
 66"C.DAw4&z
*d
#.=$;DAq)ID#V1SX\N+D *d
# Kr   moduleskip_folding_node_fnr   c           	      $   ddl }t        | t        j                  j                        s t        j                  j                  |       }n| }dt        j                  j                  dt        ffdt               d}|j                  j                  D ]  }|j                  dv r|j                  dk7  r%t        |j                        j                        sG|r	 ||      rR|j                         rct        |j                  j                  d	d      |j                         r|j                  d
k(  rJ|j#                  |j$                        x}r-t        |t        j                  j                        r	 |      rj'                  |       |j                  dk7  sd} |st)        ||j                        S dt        j                  j*                  dt,        ffd}t/        || |      }	d\  }
}t1        |	|
      }t        |t        j                  j                        st3        d|
 dt5        |             t1        |	|d      }d}|@t        |t        j                  j                        st3        d| dt5        |             |}|V|j                  j                  D ]=  }|j                  d
k(  st7        |	|j$                  t1        ||j$                               ? |j                  j                  D ]=  }|j                  d
k(  st7        |	|j$                  t1        ||j$                               ? d}|	j                  j                  D ]/  }|j                  d
k(  s|j$                  |
k(  s#|j8                  } n |t3        d      t        j                  j	                  |	|j                        }d}|j                  j                  D ].  }|j                  dk(  rt        |j8                  d   t:              }1|j                  dk7  rA|t=        |      k\  rt3        d| dt=        |       d      ||   }|dz  }|j                  dk7  rt3        d|j                         |j                  j?                  |      5  |j                  jA                  |j$                        }ddd       |jB                  jE                         _!        |jG                  |       |j                  jI                  |       1 dtK               vrt3        d      tM        |d      }t7        |	|rt        jN                  jQ                         nt        jN                  jS                                |	j                  j                  D ]  }|j                  d
k(  s|j$                  |
k(  s#|j                  j?                  |      5  |j                  jA                  |      }ddd       |jB                  jE                         _!        |jG                  |        n tU        |	|      rtW        |	|       |	j                  jY                          t)        |	|	j                  |j                  ||      S # 1 sw Y   xY w# 1 sw Y   xY w)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{   r   c                    t        | t        j                  j                        st	        d      | j
                  j                  D ]  }|j                  dk(  r|j                         r y|j                  dk(  s4| j                  |j                        x}sRt        |t        j                  j                        sw |      c S  y)z`
        Return True if a GraphModule type subgraph contains any impure op, else False.
        zDcaller should only pass GraphModule to subgraph_has_impure_ops checkrP   TrE   F)r*   r   r   r   r1   r   rT   rU   	is_impureget_submodulerV   )r{   rF   	submodule_subgraph_has_impure_opss      r   r   z7split_const_subgraphs.<locals>._subgraph_has_impure_ops   s     &%(("6"67 V  LL&& 		;Dww/)dnn.>=("("6"6t{{"CCYCy%((*>*>?/	::		; r   F>   rO   rM   get_attr
fill_valuerE   TrF   c                     | v rdS dS )Nr   rN    )rF   const_nodess    r   mod_partitionz,split_const_subgraphs.<locals>.mod_partition  s    K'q.Q.r   )submod_0submod_1zExpected GraphModule for z, got z,Could not find call_module node for const_gmrO   rM   zPlaceholder index z out of range for args (len=)rN   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   rT   rU   all_input_nodesissubsetr   r   getExprr   rV   addr   rW   r+   r   getattrr1   rS   r4   r   r2   lenr_   r   rH   rI   r]   r^   localsr   r(   r3   r)   rv   rm   ra   )r{   r|   r   r   rn   found_const_foldingrF   
target_modr   splitconst_mod_namenon_const_mod_nameconst_gmnon_const_modnon_const_gmcall_const_gm_argsroot_const_gmph_idxr   in_noderJ   r   r5   r   r   s                          @@r   r	   r	      s    fehh223XX,,V4

)=)= $ , '*eK  && &' 77// 77j T-A-A)B)K)K*
   $8$> >> dkkoolD95::F GG}$)77DDD:uxx';';<(4 	77j "&M&'R  Z-=-=>>/EHHMM /c / V];E)?&N&un-Hh 4 45''7vd8n=MN
 	
 E#5t<M04L -)=)=> +,>+?vd=FYEZ[  %
  &&,, 	PDww-'t{{GL$++,NO	P $$ H77m#E4;;$++(FGH !! 77m#{{n,%)YY"	
 !KLL HH((?M
 F##)) -77h)$))A,>77m#S+,, $VH -./03  %V,!::# #:7::,!GHH  11$7 	D$**33GNNCH	D		(""8,&&t,'-( )?@@ "@," "$4 %((:L:L:N
 !! 77m#~(E,,T2 O#zz223MNO $		 0L&&|4 u()u01	KK##%" I	D 	D,O Os   &Y9Z9Z	Z	)T)Ncpu)rs   collections.abcr   typingr   torch.fxr   torch.fx.noder   torch.fx.passes.split_moduler   __all__r   r   r   r>   r   rQ   rW   rm   r   r(   r<   r	   r   r   r   <module>r      s   	 $   ! 5@?,, @?H EIWW/2W=AW	%((--
&'Wtuxx/C/C 3 SV , DH#(UHHOOehh222U"EHHMM?D#89D@U !U 	Ur   