
    9j>                        d dl 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)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	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rootgraphconst_subgraphfx_const_folded_attrs_namedevice_for_folded_attrsc                     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         `/media/conek/DATA/Code/OCR/venv/lib/python3.12/site-packages/torch/fx/experimental/const_fold.pyr   zFoldedGraphModule.__init__   sW     	u% % %%dN; 	"
 %*!*D''>$    c                 T    | j                   s| j                          t        |   | S N)r   run_foldingr   __call__)r   argskwargsr   s      r   r   zFoldedGraphModule.__call__-   s(    ((w&&r   c                 l     j                    j                  y  j                  rt        d      d _         j                         } fd}t	        |t
              r3t        j                  j                  |D cg c]
  } ||       c}      n ||      }t          j                  |       y c c}w )NzFolding has already been runTc                 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$   )ir   s    r   _create_paramz4FoldedGraphModule.run_folding.<locals>._create_paramD   s    88%%!!S) 
  "\\1#&))1M1M)N1;Au||1Laoo	 &   SX	 &  r   )
r   r   r   AssertionErrorr'   tupler   r%   ParameterListsetattr)r   folded_attrsr.   r-   paramss   `    r   r   zFoldedGraphModule.run_folding2   s     &&...6$$ !?@@$(!
 113	 ,. HH""l#KM!$4#KL|, 	
 	d55v>	 $Ls   ;B1)NNcuda)__name__
__module____qualname____doc__r   r%   Moduler   Graphstrr   r   r   __classcell__)r   s   @r   r   r      ss     1515'-?hhoo? xx~~? -	?
 %($J? "%?$'
?r   r   gminline_mod_namerun_dcereturnc                    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}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                  j/                  |       ||   |<   q i| j                  j1                  |      5  | j                  j3                  |
|	      }ddd       |
<    | j                  j/                  |       |r| j                  j5                          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   c                 P    |    }| j                   j                         |_         |S r   )metacopy)node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   r/   typer   nodesoptargetr   r    namer   listr0   operatorusersgetitemr(   replace_all_uses_with
erase_nodeinserting_before	node_copyeliminate_dead_code)r>   r?   r@   
inline_modcall_mod_node_to_replacerG   call_mod_argscall_mod_kwargsph_countrJ   inline_nodeoutputsoutput_replacementsgetitem_usersrW   useridxrH   rI   s                     @r   _inline_modulerj   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
 "''-- ,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   3AK
$KK	
mod_tracedrU   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+)$_1rL      )resubisdigithasattrmatchgroupr(   )rk   rU   rt   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*                  ffd}t-        || |      }	d\  }
}|	j.                  t1        |	|d      }}|r|j                  j                  ng D ]=  }|j                  d
k(  st3        |	|j$                  t1        ||j$                               ? |j                  j                  D ]=  }|j                  d
k(  st3        |	|j$                  t1        ||j$                               ? d}|	j                  j                  D ]/  }|j                  d
k(  s|j$                  |
k(  s#|j4                  } n |t7        d      t        j                  j	                  |	|j                        }d}|j                  j                  D ].  }|j                  dk(  rt        |j4                  d   t8              }1|j                  dk7  rA|t;        |      k\  rt7        d| dt;        |       d      ||   }|dz  }|j                  dk7  rt7        d|j                         |j                  j=                  |      5  |j                  j?                  |j$                        }ddd       |j@                  jC                         _         |jE                  |       |j                  jG                  |       1 dtI               vrt7        d      tK        |d      }t3        |	|rt        jL                  jO                         nt        jL                  jQ                                |	j                  j                  D ]  }|j                  d
k(  s|j$                  |
k(  s#|j                  j=                  |      5  |j                  j?                  |      }ddd       |j@                  jC                         _         |jE                  |        n tS        |	|      rtU        |	|       |	j                  jW                          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   Nrx   rA   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 checkrN   TrC   F)r'   r   r   r   r/   r   rR   rS   	is_impureget_submodulerT   )rx   rG   	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>   rM   rK   get_attr
fill_valuerC   TrG   c                     | v rdS dS )Nr   rL    )rG   const_nodess    r   mod_partitionz,split_const_subgraphs.<locals>.mod_partition  s    K'q.Q.r   )submod_0submod_1z,Could not find call_module node for const_gmrM   rK   zPlaceholder index z out of range for args (len=)rL   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   rR   rS   all_input_nodesissubsetr|   r    getExprr}   rT   addr   Noder   r   getattrr2   r   r/   r0   lenr\   r   rE   rF   rZ   r[   localsr   r%   r1   r&   rs   rj   r^   )rx   ry   r   r   rk   found_const_foldingrG   
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_noderH   r   r3   r   r   s                         @@r   r   r      sM    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 / V];E)?&N&"^^WU<NPT-UlH
 -9""((b L77m#E4;;dkk(JKL $$ 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   &W3X 3W=	 X		)T)Ncpu)rp   collections.abcr   torch.fxr   torch.fx.noder   torch.fx.passes.split_moduler   __all__r   r   r   r<   r   rO   r   rj   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#(HHHOOehh222H"EHHMM?D#89D@H !H 	Hr   