
    BVhQ                        d Z ddlZddlZddlZddlZddlZddlmZmZ ddl	m
Z
 ddl	mZ ddlmZ ddlmZ ddlmZ dd	lmZ dd
lmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddl m!Z" 	 ddl#m$Z$ dZ%dZ*dZ+d Z,d Z-d Z.dZ/d Z0d Z1d Z2de)dejf                  de)d e)d!ee)   d"ee)e)f   fd#Z4	 	 d(d$Z5d% Z6d& Z7d' Z8y# e&$ r'Z' e&djQ                   e)e'                  Z%Y dZ'['qdZ'['ww xY w))z%Helper utilities for AOT compilation.    N)ListTuple)
config_pb2)meta_graph_pb2)session)convert_to_constants)ops)tensor_shape)versions)tf_optimizer)file_io)	array_ops)	sysconfig)test)
tf_logging)saver)_pywrap_tfcompilezUnable to import _pywrap_tfcompile; you must build TensorFlow with XLA.  You may need to build tensorflow with flag --define=with_xla_support=true.  Original error: {})ReadVariableOpIsVariableInitializedOpResourceGatherResourceGatherNdVariableShape)Identity	IdentityNc                 ,    t        j                  |       S N)shlexquote)ss    _/home/dcms/DCMS/lib/python3.12/site-packages/tensorflow/python/tools/saved_model_aot_compile.py_shlex_quoter!   =   s    	Q    c                  b    	 t        j                         } t         S # t        t        f$ r Y yw xY w)zHLoad tf.sysconfig if available and working (i.e., inside a pip package).N)sysconfig_libget_includeImportError
ValueError)_s    r    _sysconfig_moduler)   A   s8    !!#A
 
	 z	"  s    ..c                     d| v rI| j                  d      s8| d| j                  d       }t        | | j                  d      dz   d       }||fS | dfS )zAConvert a tensor name like 'tensor:0' into a tuple ('tensor', 0).:N   )endswithrfindint)name	node_nameoutput_slots      r    _parse_tensor_namer3   L   s]    D[s+%djjo&Id4::c?Q./01Kk!!:r"   zM
INC = -I{tensorflow_includes}
LIB = -L{compiled_dir}
CXXFLAGS = {cxx_flags}
c                    t               }t        j                  j                  |       \  }}|rt	        |j                               }nrt        j                  j                  t              rt        }t        j                  j                  |      r5t        j                  |      }t        j                  j                  |      r5t        j                  j                  t        j                  j                  t        j                  j                  |      gt        j                  j                  gdz         }n	 t        j                  d      }t        j                  j                  |dddd      }t        j                  j!                  |      s$t#        j$                  dj'                  |             |}t(        j'                  |t	        |      dj'                  t*        j,                        	      S # t        $ r~ t        j                  j                  t        j                  j                  t        j                  j                  t              gt        j                  j                  gdz         }Y ,w xY w)
a  Returns a Makefile string with variables for using XLA binary object files.

  Attempts to identify the right include header paths when run from either
  an installed TensorFlow pip package, or from bazel run.

  Args:
    output_prefix: A string containing the output prefix for the XLA AOT
      compiled header + object files.

  Returns:
    A string containing a filled out `_XLA_MAKEFILE_TEMPLATE`.
      
tensorflowcompilertf2xlazxla_compiled_cpu_function.hz/Could not find includes path.  Missing file: {}z-D_GLIBCXX_USE_CXX11_ABI={})tensorflow_includescompiled_dir	cxx_flags)r)   ospathsplitr!   r%   islink__file__readlinkrealpathjoindirnamepardirr   test_src_dir_pathKeyErrorexistsloggingerrorformat_XLA_MAKEFILE_TEMPLATEr   CXX11_ABI_FLAG)output_prefixr   
output_dirr(   r:   	this_filebaseexpected_headers           r    _xla_makefile_stringrT   ]   s     !)''--.-*a&y'<'<'>? 
ww~~hiGGNN9%KK	*	 GGNN9%WW
'',,rwwy1
Kbggnn5E5I
KMdN%%b) gglllJ2OQO77>>/*mm
;6/"$ 		&	&-
+-44

!
!# 
' 
$ $  NwwGGLL2Lrww~~6F6JLNNs   ?G: :BJ Jc                    | j                   D cg c]  }|j                  dk(  s| }}t        d |D              }t        j                  d       }| j                   D ]9  }|j
                  D ](  }|j                  d      r||   j                  |       * ; i }|j                         D ]  \  }}t        ||         }t        g       }	|r|j                         }
|
j                  |	v r!|	j                  |
j                         |
j                  t        v r.|j                  |
j                  g       }|j!                  |       n|
j                  t"        vr	|df||<   g }|r||vs|df||<    |S c c}w )a  Get the list of Variable nodes from `graph_def`.

  Args:
    graph_def: An instance of `GraphDef`.  This GraphDef *must*
      have already been optimized by Grappler.  In particular, function
      inlining must have already happened.

  Returns:
    A dict mapping string names of variables to tuples `(node_def, modified)`,
    where `node_def` is the `NodeDef` corresponding to variable, and `modified`
    is a python bool describing whether the variable is modified during runtime.
  VarHandleOpc              3   8   K   | ]  }|j                   |f  y wr   r0   .0ns     r    	<genexpr>z5_get_variable_nodes_from_graph_def.<locals>.<genexpr>   s     :1AFFA;:   c                      g S r    r_   r"   r    <lambda>z4_get_variable_nodes_from_graph_def.<locals>.<lambda>   s    b r"   ^TF)nodeopdictcollectionsdefaultdictinput
startswithappenditemslistsetpopr0   add_PASS_THROUGH_VARIABLE_OPSgetextend_READ_ONLY_VARIABLE_OPS)	graph_defr[   	variablesvariable_name_map	child_mapinpv_namev_nodequeue	processed	n_currentchildrens               r    "_get_variable_nodes_from_graph_defr~      sl    $..BQADDM,AqB)B:	::%%j1)>> !aww !^^C #a !! )+113 *vv6"#EBI
))+i	9	$mmINN#	3	3==4X<<66#TN	&  Y!5/i*" 
3 Cs
   E5E5c                    t        |j                  D cg c]  }|j                   c}      }t        j                         }|j                  |        | j                  j                         D ]T  \  }}t        |j                        \  }}||vs#t        j                  dj                  ||             |j                  |= V |S c c}w )zIdentify the inputs in the signature no longer in graph_def, prune them.

  Args:
    signature_def: A `SignatureDef` instance.
    graph_def: A `GraphDef` instance.

  Returns:
    A new pruned `SignatureDef`.
  zSignature input key '{}', tensor name '{}', has been pruned while freezing the graph.  Removing it from the compiled signatures.)rl   rb   r0   r   SignatureDefCopyFrominputsrj   r3   rJ   warnrL   )	signature_defrs   r[   
node_namesnew_signature_defkvtensor_namer(   s	            r    _prune_removed_feed_nodesr      s     INN3qAFF34*$113]+$$**, &fq!'/NK*$llQ6![!# 
"
"1
%& 
 4s   Ccheckpoint_pathmeta_graph_defrO   signature_def_keyvariables_to_feedreturnc                    |j                   }||vr(t        d| dt        |j                                      ||   }|j                  st        d| dt        |             t        j                  |       t        j                         t        j                  k\  rht        j                  j                  |d      }t        j                  |d      5 }|j                  |j                   j#                                ddd       t%        |j                   |       t'        ||      }	t)        |	      }
|t        |
j+                               }nQt-        |      j/                  t        |
            }|rt        d| d	t        |
             |D cg c]  }|
|   	 }}t        j                         t        j                  k\  r^t        j                  j                  |d
      }t        j                  |d      5 }|j                  |	j#                                ddd       t1        j2                  t5        j6                               5 }t9        j:                  |d      }||j=                  ||        |	j?                  tA        jB                  ||	|j                  j+                         D cg c]  }tE        |jF                        d    c}|D cg c]  \  }}|jF                   c}}             ddd       tI        ||	      }t        j                  j                  |d      }t        j                  j                  |d      }t        jJ                  djM                  |             t        j                  |d      5 }|j                  |	j#                                ddd       tO        ||      }t        jJ                  djM                  |             t        j                  |d      5 }|j                  t        |             ddd       ||fS # 1 sw Y   !xY wc c}w # 1 sw Y   xY wc c}w c c}}w # 1 sw Y   QxY w# 1 sw Y   xY w# 1 sw Y   ||fS xY w)an  Freeze a `MetaGraphDef` in preparation for tfcompile`.

  The graph is always optimized with grappler, and optionally (by default)
  variables are frozen as constants, before compilation happens.

  Args:
    checkpoint_path: Python string.  Path to checkpoints/variables.
    meta_graph_def: Instance of `MetaGraphDef`.
    output_prefix: Python string.  Path prefix for outputs.
    signature_def_key: String, the signature_def to use in the SavedModel.
    variables_to_feed: A list of strings, the variables that will be fed by the
      user; these won't be frozen.  If `None`, then we will extract all the
      variables in the graph and mark them as to-feed.  The default behavior is
      an empty tuple: all variables must be frozen.
  Returns:
    a pair containing the path to the frozen model and the path to the config.
  Raises:
    RuntimeError: If tensorflow was not built with XLA.
    ImportError: If tensorflow was built with XLA but there was another
      issue importing the tfcompile python wrapper.
    ValueError: If `meta_graph_def.signature_def[signature_def_key]` is
      missing or has empty outputs.
  z"Unable to find signature_def_key 'z<' in signature def map of `meta_graph_def`. Available keys: zSignature key z" must have outputs, but saw none:
zoriginal_graph.pbwbNz6Asked to feed variables that were not found in graph: z$. Variables contained in the graph: zprefrozen_graph.pb)graphT)clear_devicesr   )output_node_namesvariable_names_blacklistzfrozen_graph.pbzconfig.pbtxtzWriting graph def to: {})variable_nodes_to_feedzWriting config_pbtxt to: {}wmode)(r   r'   rk   keysoutputsstrr   recursive_create_dirrJ   get_verbosityINFOr=   r>   rD   FileIOwriters   SerializeToString/_replace_input_placeholders_with_default_values_optimize_graphr~   valuesrl   
differencer   Sessionops_libGraph	saver_libimport_meta_graphrestorer   r   convert_variables_to_constantsr3   r0   r   inforL   _signature_to_tf2xla_config)r   r   rO   r   r   signature_def_mapr   original_graph_def_locationgraph_writerrs   all_variablesr   not_in_graphr0   prefrozen_graph_def_locationsessrestorerr[   r(   frozen_graph_def_locationconfig_pbtxt_locationconfigconfig_writers                          r    freeze_modelr      s   6 %22//

,->,? @8!&&()
*	,- - $$56-			

*++N}
	 ! ! 
}-,"$'',,}/B#D	3T	: Gl11CCEFG 2/ nm<)4Y?-!-"6"6"89()44T-5HILO&'K}-.0 1 1 ): $d  ,#%77<<0D$F 	4d	; 8|44678 W]]_- **>NHt_-;; '..557 #166*1-
 $:&1a&
	
	" ,M9E- ggll=:KL'',,}nE	,,)001JKL~~/6 6,y22456&,BD&	,,,334IJK~~+#6 %-F$%	"$9	99uG G$8 8& ,6 6
%	"$9	99sa   *PP*; P/A$Q/P<QQ+Q Q6Q P'/P9<QQQ Q,c	                    t         rt         t        j                  j                  d      }	|	sdj	                  |rdnd      }	n|	dj	                  |rdnd      z  }	|	t        j                  d<   t        j                         }
t        j                  |
       t        | ||
||      \  }}t        j                  j                  |      }t        j                  |       t        j                  ddd	|z   d
z   |z         }t        j                  dj	                  |             dj	                  |      }t        j                   |d      5 }|j#                  t%        |             ddd       t'        |      }t)        j*                  ||||||dj	                  |      dj	                  |      dj	                  |      dd       y# 1 sw Y   bxY w)a"  Compile a `MetaGraphDef` to header+object files in `output_prefix`.

  Use XLA AOT (`tfcompile`) to convert the given meta graph and
  signature into a header + object files.  Also create an include makefile
  that helps identify the appropriate necessary include and library paths
  to incorporate these files into your C++ program.

  Freezing a graph entails restoring the checkpoint and replacing any inputs and
  variables with constants. If values are feed, those are used, else inputs are
  replaced with default all-zero constants. Finally, the graph is pruned and
  then optimized with grappler.

  If the `freeze_graph` is `True`, all variables are embedded as constants
  into the graph and binary objects.  If it is `False`, then the variable
  values become inputs and outputs of the compiled class and the C++
  caller must set these values manually.

  Args:
    checkpoint_path: Python string.  Path to checkpoints/variables.
    meta_graph_def: Instance of `MetaGraphDef`.
    output_prefix: Python string.  Path prefix for outputs.
    signature_def_key: String, the signature_def to use in the SavedModel.
    cpp_class: String, Name of output C++ class.
    target_triple: String, LLVM target triple.
    target_cpu: String, LLVM target cpu name.
    variables_to_feed: A list of strings, the variables that will be fed by the
      user; these won't be frozen.  If `None`, then we will extract all the
      variables in the graph and mark them as to-feed.  The default behavior is
      an empty tuple: all variables must be frozen.
    multithreading: Whether to enable multithreading in the compiled
      computation.  Note that if using this option, the resulting object files
      may have external dependencies on multithreading libraries like Abseil.

  Raises:
    RuntimeError: If tensorflow was not built with XLA.
    ImportError: If tensorflow was built with XLA but there was another
      issue importing the tfcompile python wrapper.
    ValueError: If `meta_graph_def.signature_def[signature_def_key]` is
      missing or has empty outputs.
  	XLA_FLAGSz--xla_cpu_multi_thread_eigen={}truefalsez  --xla_cpu_multi_thread_eigen={})r   r   rO   r   r   z[^0-9a-zA-Z]+r(   __xla___z#Generating XLA AOT artifacts in: {}z{}_makefile.incr   r   Nz{}.oz{}.hz{}_metadata.oTF)r   r   	cpp_classtarget_triple
target_cpuentry_pointout_function_object
out_headerout_metadata_objectgen_name_to_indexgen_program_shape)_pywrap_tfcompile_import_errorr=   environrp   rL   r   get_temp_dirr   r   r   r>   rE   resubrJ   r   r   r   rT   r!   r   Compile)r   r   rO   r   r   r   r   r   multithreading	xla_flagstemp_dirr   r   rP   r   makefile_inc_locationmakefile_writers                    r    aot_compile_cpu_meta_graph_defr   4  s   b $
((
 

{+I3::"&1i 5<<"&1 1i'BJJ{ (	x(5A%#))6+22 ww}-*	z*s%	13+ 
,,4;;JGH+22=A~~+#6 ?/.}=>? }--%"! --6}-)00?? ?s   GGc                 6   t        j                  |       }t        j                         }t	        |j
                  j                               t	        |j                  j                               z   D ]1  }|j                  j                  j                  |j                         3 |j                  d   j                  |       |j                  d       t        j                          }|j"                  j$                  }d|_        t)        j*                  ||      S )z@Optimize `meta_graph_def` using grappler.  Returns a `GraphDef`.train_op	saver_def)copydeepcopyr   CollectionDefrk   r   r   r   	node_listvalueri   r0   collection_defr   
ClearFieldr   ConfigProtograph_optionsrewrite_optionsmin_graph_nodesr   OptimizeGraph)r   r   new_meta_graph_deffetch_collectiontensor_infor   r   s          r    r   r     s     }}^4#113
=&&()
=  '')*+>k $$++K,<,<=>
 ##J/889IJ,!!#&((88/$&/!		#	#F,>	??r"   c           
      J   t        d | j                  D              }t        g       }|j                  j	                         D ]  \  }}t        |j                        \  }}||v r$|j                  |       ||vr(t        d| dt        |j                                      ||   }|j                  dvr&t        j                  dj                  ||             t        j                   |j                        }	|	j#                         st%        d| d| d|	 d	      t'        j(                         }
|
j+                         5  t-        j.                  |	|j0                  |
      }ddd       |j3                  j                  j4                         |
j7                         D ]n  }|j                  |j                  j                  k(  r'| j                  j9                  |j4                         |j4                  ||j4                  j                  <   p  y# 1 sw Y   xY w)zFReplace graphdef's `tf.placeholder` input ops with all-zero constants.c              3   8   K   | ]  }|j                   |f  y wr   rX   rY   s     r    r\   zB_replace_input_placeholders_with_default_values.<locals>.<genexpr>  s     >!1661+>r]   z'Unable to find input signature tensor 'z*' in optimized GraphDef. Graph nodes are: )PlaceholderPlaceholderV2zjTried to convert SavedModel input node '{}' from a placeholder, but it doesn't look like a placeholder: {}z6Expected fully defined input shape for signature_def 'z', tensor name: 'z'; but shape is: .)dtyper0   N)rd   rb   rl   r   rj   r3   r0   rn   RuntimeErrorrk   r   rc   rJ   r   rL   r
   TensorShapeis_fully_definedr'   r   r   
as_defaultr   zerosr   r   node_defget_operationsri   )rs   r   name_to_node_mapprocessed_nodesr0   input_r   r(   rb   shape
temp_graphconstrc   s                r    r   r     s   >y~~>>G/#**002 7ldF'4NKo%$**3K= A((,-=-B-B-D(E'FHI I K(Dww66ll88>{?C9EF $$V%8%89E!!#B4& I&-'8qBC C J				  7oo
v||+7e7 	MM%((##$'') 7	EHHMM	!nnBKK(+-;;r{{''(	777,7 7s   #HH"	c           
      P   ddl m} |j                         }|j                  }| j                  j                         D ]  \  }}|j                  dd      }dj                  |      }t        |j                        \  }}t        |      }|j                  j                  |j                   |||      ||j                  |j                                | j                   j                         D ]  \  }}	|j                  dd      }dj                  |      }t        |	j                        \  }}t        |      }|j"                  j                  |j%                   |||      ||	j                  |	j                                |D ]  \  }
}|
j                  j                  dd      }d	j                  |      }|j&                  j                  |j)                  |
j                  ||
j*                  d
   j,                  |
j*                  d   j.                  |               |S )a  Convert `signature_def` to tf2xla config.  Returns a `tf2xla.Config` proto.

  Args:
    signature_def: Instance of `SignatureDef`.
    variable_nodes_to_feed: List of tuples of form `(node_def, modified)`
      corresponding to VarHandleOp, and a boolean `modified` that describes
      whether the variable was modified during execution.

  Returns:
    An instance of `tf2xla.Config` proto.

  Raises:
    RuntimeError: If TensorFlow was not compiled with XLA.
  r   )
tf2xla_pb2/r(   zfeed_{})r1   output_index)idr0   typer   zfetch_{}zparam_{}r   r   )r1   r0   r  r   readonly)tensorflow.compiler.tf2xlar   ConfigTensorIdr   rj   replacerL   r3   r0   r/   feedri   Feedr   r
   r   fetchFetchvariableVariableattrr  r   )r   r   r   r   	tensor_idr0   r   r1   r  output_rb   modifieds               r    r   r     s    4&!!)#**002 
(ldF<<S!DD!D 26;; ?Y|$L
KK9<H%%	 	 	'(
( %,,224 
)mdG<<S!DT"D 27<< @Y|$L
LL9<H&&	 	 	()
) 1 	$tX99S#&DT"D
OOii7#(())G$**!\ 	 	#$	$ 
-r"   )r_   F)9__doc__re   r   r=   r   r   typingr   r   tensorflow.core.protobufr   r   tensorflow.python.clientr   tensorflow.python.frameworkr   r	   r   r
   r   tensorflow.python.grapplerr   tensorflow.python.lib.ior   tensorflow.python.opsr   tensorflow.python.platformr   r$   r   r   rJ   tensorflow.python.trainingr   r   tensorflow.pythonr   r   r&   erL   r   rr   ro   r!   r)   r3   rM   rT   r~   r   MetaGraphDefr   r   r   r   r   r_   r"   r    <module>r      s3   ,   	 	   / 3 , < 6 4 0 3 , + A + < 9(1 $(   7  +$\&R0e:# e:!/!<!<e: #e:8;e: %)Ie: 38S/e:^ 6827cL@(#7L5W  L#.<<BF3q6N$L Ls   4C C2C--C2