
    PhF                        d dl Z d dlmZ d dlZd dlmZmZmZmZ d dl	Z	d dl
Z
d dlZd dlZd dlmc mZ d dlmZ d dlmZ d dlmZmZ d dlmZ d dlmZ d d	lmZmZ d d
lm Z m!Z!m"Z" ddlm#Z# g dZ$ejJ                   G d d             Z&d Z'd!dZ( G d de)      Z* G d dejV                  jX                  e*      Z-dejV                  jX                  fdZ.dej^                  j@                  dej`                  jb                  fdZ2d Z3dejV                  jX                  de4deejj                     deee
jl                  ef   eeeef      f   fd Z7y)"    N)defaultdict)DictListOptionalTuple)
FakeTensor)SymInt)_PyTreeCodeGen_PyTreeInfo)ValueRanges)InputDim)ExportBackwardSignatureExportGraphSignature)ExportedProgramModuleCallEntryModuleCallSignature   )!_check_input_constraints_pre_hook)r   r   r   r   r   c                   V    e Zd ZU eej
                     ed<   eej
                     ed<   y)CallSpecin_specout_specN)__name__
__module____qualname__r   pytreeTreeSpec__annotations__     iC:\Users\daisl\Desktop\realtime-object-detection\venv\Lib\site-packages\torch/_export/exported_program.pyr   r   1   s     foo&&v''r    r   c           
         d}i }| j                   j                  D ]  }	|	j                  dk(  r||v r| j                   j                  |	      5  | j                   j	                  ||         }
|	j                  |
       |	j                  }| j                   j                  |	       ||
_        |
|||   <   d d d        |dz  }|	j                  dk(  sg }t        j                  |	j                        d   D ]  }|j                  }||v r||   j                  dd      }||v sJ ||   }| j                   j                  |	      5  | j                   j                  t        j                   j"                  j$                  j&                  ||f       d d d        |j)                  |        | j                   j                  |	      5  | j                   j+                  t-        |            }|	j                  |       | j                   j                  |	       d d d         | j                   j/                          |j0                  t,        k(  rt3        |j4                        dk(  r|j4                  d   j0                  t,        k(  rf|j4                  d   j0                  t6        k(  rFt3        |j4                  d   j4                        t3        |j4                  d   j4                        z   }nt3        |j4                        }t9        |      D cg c]  }d| 	 }}t;        t=        |||            | j                   _        | jA                          | j                   j                  D ]  }	|	j                  d	k(  r|	jB                  t        j                   jD                  k(  r`|	j                  \  }}}}tG        | |j                        }tG        | |j                        }i }g }tI        |      D ]  \  }}|jB                  |jK                         v r|jB                  ||<   |jB                  |v r||jB                     }n4|jB                  |v r||jB                     }ntM        d
|jB                        |jO                  |jB                  |       |jO                  |jB                  |       |j)                  |        ||||f|	_
        t        j                  |      \  } }tQ        |||d |||       tQ        |||d |||       |	j                  d	k(  s|	jB                  jR                  dk(  s|	j                  ^}!}"}tG        | |!j                        }#i }$g }|jU                         D %ci c]  \  }%}|%j                  dd      | }&}%}tI        |      D ]  \  }}|jB                  |jK                         v r|jB                  |$|<   |jB                  |&v r|&|jB                     }n6|jB                  |v r||jB                     }ntM        d
|jB                         |#jO                  |jB                  |       |j)                  |        |!|"g||	_
        t        j                  |      \  } }tQ        |#|$|d |||        | j                   j/                          | j                   jW                          | jA                          | S # 1 sw Y   xY w# 1 sw Y   xY w# 1 sw Y   xY wc c}w c c}}%w )Nr   placeholderr   output._   arg_call_functionzUnable to find value for map_impl),graphnodesopinserting_afterget_attrreplace_all_uses_withmeta
erase_noder   tree_flattenargsnamereplaceinserting_beforer)   torchopsatencopy_defaultappendr$   tuplelinttypelenchildren_specsdictranger
   r   _codegen	recompiletargetcondgetattr	enumeratevaluesRuntimeErrorregister_buffer_unliftr   itemseliminate_dead_code)'gminp_pos_to_param_buffer_namer   r   
state_dicttensor_constantsbuffers_to_mutatecountbuffer_name_to_nodenodegetattr_nodemetadatauser_output_nodesreturn_nodereturn_node_namebuffer_node_namebuffer_node
new_outputnum_argsinamespred
true_graphfalse_graphoperandstrue_gmfalse_gm'inp_pos_to_param_buffer_name_for_submodreal_operandsixoperandvaluer&   
body_graph
num_mappedbody_gm!inp_pos_to_buffer_name_for_submodkeystate_dict_for_lookups'                                          r!   rN   rN   7   s5   E77m#44XX--d3#%88#4#44U;$L ..|<#yyHHH''-(0L%O['(DU(KL 4 QJE77h "  &22499=a@#.#3#3 #'88'89I'J'R'RSVX['\$+/BBBB"56F"GK2248..!IINN0088;:T 98
 &,,[9  A **40XX__U3D-EF
**:6##D)	 10C R HHMMO 	G""#q(q!&&%/q!&&$.
 &&q)889&&q)889: 	
 w--.!&x1AtA3ZE1&	
BHH LLN 77o%$++*G6:ii3D*k8b*//2Gr;#3#34H683M(2G>>%A%H%H%JJBI..;B?~~3 *7>> : +;; 0 @*+FWW++GNNEB,,W^^UC!((1  3 z;FDI,,];JAw7 ! 7 ! 77o%$++*>*>**L04		-J
Xb*//2G02-M #-"2"2"4%"4JC C%u,"4 " %  )2G>>%A%H%H%JJ<CNN5b9~~)>> 5gnn E +;; 0 @*-Fw~~FV+WXX++GNNEB!((1  3 $Z@-@DI,,];JAw1 !I Z HHMMOHH  "LLNIi 430 98 102 2z%s3   A&[A[A["[/*[4[	["[,	c                 X   i }|j                         D ]  \  }}||j                  v rNd|v r8| j                  |j                  dd      |       |j                  dd      ||<   n| j                  ||       ||j                  v sqd|v r8| j                  |j                  dd      |       |j                  dd      ||<   | j                  ||        |Zt        |      dkD  rLt        |d      sJ |j                         D ]+  \  }}||j                  v s| j                  ||       |||<   - d}i }| j                  j                  D ]  }	|	j                  dk(  s|	j                  |j                  v r+|j                  |	j                     }
|
|v r	||
   ||<   n|
||<   |	j                  |j                  v r+|j                  |	j                     }||v r	||   ||<   n|||<   t        |d      r4|	j                  |j                  v r|j                  |	j                     ||<   |dz  } |S )Nr%   r&   r   lifted_tensor_constantsr#   !inputs_to_lifted_tensor_constantsr   )rO   buffersrM   r6   
parametersregister_parameterrA   hasattrrv   r+   r,   r-   r5   inputs_to_buffersinputs_to_parametersrw   )new_gmgraph_signaturerS   rT   #param_buffer_name_to_corrected_namer5   rn   rV   rR   rX   buffer_name
param_names               r!   '_construct_inp_pos_to_param_buffer_namer      sY    +-'!'')e?***d{&&t||C'=uE<@LLc<R3D9&&tU3?---d{))$,,sC*@%H<@LLc<R3D9))$6 * #,<(=(A(ABBB+113KD%>>>&&tU3<@3D9 4
 E#% ""77m#yyO===-??		J"EE <KH 1 ;F07yyO@@@,AA$))L
!DD <JG 1 ;E07(KL99 Q QQ (II$))T 1 QJE/ #2 ('r    c                   *     e Zd ZdZd Zd fd	Z xZS )_StatefulGraphModuleFactoryzO
    Metaclass that ensures a private constructor for _StatefulGraphModule
    c                 L    t        | j                   d| j                   d      )Nr%   z has no public constructor. )	TypeErrorr   r   )clsr4   kwargss      r!   __call__z$_StatefulGraphModuleFactory.__call__  s,    ~~a 0 011MN
 	
r    c                 *    t         |   ||||      S )Nrange_constraintsequality_constraints)superr   )r   rootr+   r   r   	__class__s        r!   _createz#_StatefulGraphModuleFactory._create  s&    w/!5	   
 	
r    NN)r   r   r   __doc__r   r   __classcell__r   s   @r!   r   r     s    


 
r    r   c                         e Zd Zd fd	Z xZS )_StatefulGraphModulec                 R    t         |   ||       |xs g | _        |xs g | _        y N)r   __init__r   r   )selfr   r+   r   r   r   s        r!   r   z_StatefulGraphModule.__init__   s,    u%!2!8b$8$>B!r    r   )r   r   r   r   r   r   s   @r!   r   r     s    ? ?r    r   )	metaclassplain_graph_modulec                 z    t         j                  | | j                  ||      }|j                  t        d       |S )Nr   T)with_kwargs)r   r   r+   register_forward_pre_hookr   )r   r   r   stateful_gms       r!   _create_stateful_graph_moduler   &  sF    &..  +1	 / K ))*KY])^r    epreturnc           	         t        j                  | j                        }t        || j                  | j
                  | j                        }t        ||| j                  j                  | j                  j                  | j
                  | j                  | j                  j                        }t        || j                  | j                        }|j                  j!                  | j                  j                         |S r   )copydeepcopygraph_moduler   r   rS   rT   rN   	call_specr   r   rU   r   r   r   r1   update)r   r~   rR   	unlift_gms       r!   %unlift_exported_program_lifted_statesr   1  s    ]]2??+F#J""BMM23F3F$  $




,,F .fb6J6JBLcLcdINN"//../r    c                    	 t         j                  j                  | |      }|S # t        $ r\ t	        j
                  d       t         j                  j                  | t         j                  j                               }||_        Y |S w xY w)NzUnable to execute the generated python source code from the graph. The graph module will no longer be directly callable, but you can still run the ExportedProgram, and if needed, you can run the graph module eagerly using torch.fx.Interpreter.)r8   fxGraphModuleSyntaxErrorwarningswarnGraph_graph)r   r+   rQ   s      r!   _create_graph_module_for_exportr   D  sx    XX!!$.  I   	G	
 XX!!$(89	Is    $ A!B	B	r   num_lifted_params_buffersexample_inputsc           	         | j                   j                  dg       }| j                   j                  dg       }t        t              }i }t	        | j
                  j                        D ]Z  \  }}|j                  dk7  r nF||k\  s|||z
     }	|t        |	         j                  |j                         |||j                  <   \ g }
t        t              }|D ]  }||d      D ]y  }t        ||d         }||   j                  t        |d   |d                |j                  dd	      x}sK||d      D ]$  }t        ||d         }|
j                  ||f       & {  i }|D ci c]  }|||   
 }}|j                         D ]  \  }}|D cg c]  }|j                   }}|D cg c]  }|j                   }}t!        |      }t#        |      }||k  sJ ||j$                     j                   d
   }t'        |t(              sJ |j*                  |j,                     }t'        |t.              sJ d| dt1        |              |j2                  j4                  }t        ||      ||<    ||
fS c c}w c c}w c c}w )a-  
    Process the constraints stored in the graph module to return something more readable.

    Args:
        graph_module (torch.fx.GraphModule): GraphModule returned from
            dynamo.export, which contains the "input_shape_constraints" and
            "inline_constraints" metadata

        example_inputs: Flattened list of example inputs used to export the graph module

    Returns:
        range_constraints (Dict[sympy.Symbol, ValueRanges]): Mapping of
            symbols (from SymInts) appearing in the fake tensors in
            node.meta["val"] to their range constraints, which are a tuple
            containing (lower, upper) constraints.

        equality_constraints (List[Tuple[InputDim, InputDim]]): List of tuples
            of (node, dim) to mark that these dimensions are equal.
    input_shape_constraintsinline_constraintsr#   t_iddimminmaxsharedNvalzExpected SymInt but got z: )r1   getr   listrJ   r+   r,   r-   idr=   r5   r   r   rO   lowerupperr   r   
input_name
isinstancer   shaper   r	   r@   rX   _expr)r   r   r   r   r   tensor_id_to_nodesplaceholder_nodesrb   rX   example_inputr   multi_range_constraints
constraintnode_dimr   
other_nodeother_node_dimr   symbol	input_dimmulti_range_constraintrcmin_valsmax_valsmin_valmax_valr   symints                               r!   _process_constraintsr   Y  s   0 +//334MrR%**../CRH 0;4/@24\//556477m# ))*1/H+HIMr-0188C+/dii( 7 =? BMTAR-
&z&'9:Dj&78H $H-44Ju-z%/@A
 $$77v7"4VF^"DJ%-j&-%HN(//>0JK #E ; .  :< K]]J\!3F!;;J\] .E-J-J-L)	) (>>'=BHH'=>'=>'=BHH'=>h-h-'!!!  	 4 45::5A#z***9==)&&)^-EfXRPTU[P\~+^^)""$/$A&! .M" 222) ^ ?>s   (I4I9*I>r   )8r   collectionsr   dataclassestypingr   r   r   r   r   sympyr8   torch.fxtorch.utils._pytreeutils_pytreer   torch._subclasses.fake_tensorr   %torch.fx.experimental.symbolic_shapesr	   torch.fx.graphr
   r   torch.utils._sympy.value_rangesr   @torch._export.passes.add_runtime_assertions_for_constraints_passr   torch.export.graph_signaturer   r   torch.export.exported_programr   r   r   r   __all__	dataclassr   rN   r   r@   r   r   r   r   r   exportnnModuler   r   intTensorSymbolr   r   r    r!   <module>r      sK    #  . .     $ $ 4 8 6 7
  5 ( ( (
[z5(p
$ 
&?588//;V ?ehh6J6J ell.J.J uxx &*U3((&&U3"U3 &U3 4k)*Dx7I1J,KKL	U3r    