
    BVhU                        d Z ddlZddlZddl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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l0m1Z2 ddl0m3Z3 dd l4m5Z5 dd!l4m6Z6  e#d" e7       d#      Z8 e#d$ e7       d%      Z9 e#d& e7       d'      Z: e#d( e7       d)      Z; e#d* e7       d+      Z< e#d, e7       d-      Z= e#d. e7       d/      Z> e#d0 e7       d1      Z? e#d2 e7       d3      Z@ej                  j                  ej                        ZDeDj                  ej                         dOd4Z+d5 ZGd6 ZHd7 ZI G d8 d9eJ      ZKd: ZLd; ZMd< ZNd= ZOd> ZPd? ZQd@ ZRdA ZS G dB dCeJ      ZTdD ZU G dE dFeJ      ZVdPdGZWdH ZXdI ZY G dJ dKeT      ZZdL Z[dM Z\dN Z]y)Qz!Keras SavedModel deserialization.    N)message)context)ops)sparse_tensor)tensor_shape)tensor_spec)backend)regularizers)
input_spec)optimizer_v2)saved_metadata_pb2)versions_pb2)saving_utils)	constants)
json_utils)utils)CommonEndpoints)generic_utils)metrics_utils)
LazyLoader)ragged_tensor)gfile)
tf_logging)load)loader_impl)nested_structure_coder)revived_types)base)data_structures)compat)nest
models_libztensorflow.python.keras.models
base_layerz)tensorflow.python.keras.engine.base_layerlayers_moduleztensorflow.python.keras.layersinput_layerz*tensorflow.python.keras.engine.input_layerfunctional_libz)tensorflow.python.keras.engine.functionaltraining_libz'tensorflow.python.keras.engine.trainingtraining_lib_v1z*tensorflow.python.keras.engine.training_v1metricsztensorflow.python.keras.metrics	recurrentz(tensorflow.python.keras.layers.recurrentc           	      n   t        j                         }t        j                  |       j                  d   }|j
                  }t        j                  j                  | t        j                        }t        j                  |      rB	 t        j                  |d      5 }|j                         }ddd       |j                         n!t+        j,                  d       t/        ||       |j0                  st3        j4                  | |      S t7        ||      }
|
j9                  |       ddi}|
j:                  j=                         D ]  \  }}|||
j?                  |      <    t3        j@                  | ||      }|
jC                          |
jE                          |d   }tG        |tH        jJ                        r|r|jL                  d	   jO                  d
d      }| |jP                  di tS        jT                  |      ddi tS        jV                  |       tG        |jX                  tZ        j\                        rE|jX                  j_                         r+t+        j,                  d       nt+        j,                  d       ta        jb                         sPte        jf                         }|ji                  tk        jl                  tj        jn                  jp                               |S # 1 sw Y   ?xY w# t         j"                  $ r)}	t%        dj'                  |t)        |	                  d}	~	ww xY w)a  Loads Keras objects from a SavedModel.

  Any Keras layer or model saved to the SavedModel will be loaded back
  as Keras objects. Other objects are loaded as regular trackable objects (same
  as `tf.saved_model.load`).

  Currently, Keras saving/loading only retains the Keras object's weights,
  losses, and call function.

  The loaded model can be re-compiled, but the original optimizer, compiled loss
  functions, and metrics are not retained. This is temporary, and `model.save`
  will soon be able to serialize compiled models.

  Args:
    path: Path to SavedModel.
    compile: If true, compile the model after loading it.
    options: Optional `tf.saved_model.LoadOptions` object that specifies
      options for loading from SavedModel.


  Returns:
    Object loaded from SavedModel.
  r   rbNz#Cannot parse keras metadata {}: {}.a  SavedModel saved prior to TF 2.5 detected when loading Keras model. Please ensure that you are saving the model with model.save() or tf.keras.models.save_model(), *NOT* tf.saved_model.save(). To confirm, there should be a file named "keras_metadata.pb" in the SavedModel directory.)options)compilerootmetadatatraining_configfrom_serializedTzYour optimizer uses slots. Slots cannot be restored from saved_model, as a result, your model is starting with  a new initialized optimizer.zcNo training configuration found in save file, so the model was *not* compiled. Compile it manually. )9r   SavedMetadatar   parse_saved_modelmeta_graphsobject_graph_defospathjoinr   SAVED_METADATA_PATHr   ExistsGFilereadParseFromStringr   DecodeErrorIOErrorformatstrloggingwarning_read_legacy_metadatanodestf_loadr   KerasObjectLoaderload_layersloaded_nodesitemsget_pathload_partialfinalize_objectsdel_tracking
isinstancer'   Model_serialized_attributesgetr.   r   !compile_args_from_training_configtry_build_compiled_arguments	optimizerr   OptimizerV2get_slot_namesr   executing_eagerlyr	   get_sessionrunr   get_collection	GraphKeysTABLE_INITIALIZERS)r9   r.   r-   r0   meta_graph_defr7   path_to_metadata_pbffile_contentekeras_loadernodes_to_loadnode_idloaded_nodeloadedmodelr1   sesss                     _/home/dcms/DCMS/lib/python3.12/site-packages/tensorflow/python/keras/saving/saved_model/load.pyr   r   ]   s   8  --/(006BB1E.#44T9+H+HI
\\%&:;;*D1  Qvvx |,
 OO M N
 *H5	<<g.. #8-=>,7+ 4.-*77==? @g{4?M,''01@mWE& !
.% |))*w 22:>BB4!O"emm 2lDD
 2,02//6	EOO\%=%=	>OO**,
// 9 :
 oo G H
 
	"	"	$ DHHS @ @AB	,y     :9V/Q8: ::s0   K8 K+.K8 +K50K8 8L4$L//L4c           
         t        |       }t        | j                        D ]  \  }}|j                  d      dk(  s|j                  j
                  t        j                  v sB|j                  j                  st        d      |j                  j                  |||   t        j                  ddg       |j                  j
                  |j                  j                          y)z@Builds a KerasMetadata proto from the SavedModel ObjectGraphDef.kinduser_objectzUnable to create a Keras model from this SavedModel. This SavedModel was created with `tf.saved_model.save`, and lacks the Keras metadata.Please save your Keras model by calling `model.save`or `tf.keras.models.save_model`.   )producermin_consumerbad_consumers)rg   	node_pathversion
identifierr0   N)_generate_object_paths	enumeraterG   
WhichOneofro   rv   r   KERAS_OBJECT_IDENTIFIERSr0   
ValueErroraddr   
VersionDef)r7   r0   
node_pathsrg   protos        rl   rF   rF      s     &&67*!"2"8"89 /ngu M1$$	(J(JJ'' < = 	=
 nnw'))q<&&11$$--  //    c                 *   ddi}dg}|r|j                         }||   }| j                  |   j                  D ]U  }|j                  |v rdj	                  ||j
                        ||j                  <   |j                  |j                         W |r|S )zGTraverses through an ObjectGraphDef and builds a map of all node paths.r   r/   {}.{})poprG   childrenrg   rB   
local_nameappend)r7   pathsnodes_to_visitcurrent_nodecurrent_path	references         rl   rw   rw      s    f+%3.!%%'L&L%++L9BB /				e	#!(090D0D"FeII--./ 	 
,r   c                     t        | t              ryt        | t        j                        r(| j                  xs t        | t
        j                        S y)z0Determines whether the layer is a graph network.F)rQ   RevivedNetworkr&   
Functional_is_graph_networkr"   
Sequentiallayers    rl   r   r      sG     ~&%223## 5uj3346	r   c                       e Zd ZdZd Zd Zd ZddZd Zd Z	d Z
d	 Zd
 Zd Zd Zd Zd Zd Zd Zd Zd Zd ZddZd Zy)rI   aN  Loader that recreates Keras objects (e.g. layers, models).

  Layers and models are revived from either the config or SavedModel following
  these rules:
  1. If object is a graph network (i.e. Sequential or Functional) then it will
     be initialized using the structure from the config only after the children
     layers have been created. Graph networks must be initialized with inputs
     and outputs, so all child layers must be created beforehand.
  2. If object's config exists and the class can be found, then revive from
     config.
  3. Object may have already been created if its parent was revived from config.
     In this case, do nothing.
  4. If nothing of the above applies, compose the various artifacts from the
     SavedModel to create a subclassed layer or model. At this time, custom
     metrics are not supported.

  c                 *   |j                   D ci c]  }|j                  | c}| _        || _        |j                   D ci c]  }|j                  |j                   c}| _        i | _        t               | _        i | _	        g | _
        y c c}w c c}w N)rG   rg   	_metadata_protort   _node_pathsrK   set_traversed_nodes_from_configmodel_layer_dependencies_models_to_reconstruct)selfr0   r7   x	node_datas        rl   __init__zKerasObjectLoader.__init__  s    ,4NN;qaiil;DN"DK *29% "))9+>+>> 9DD ),D%
 %'D!"$D <9s   B Bc                 x   | j                   j                         D ]  }|d   }t        |t        j                        s#t
        D ]  }|j                  |        t        |t        j                        sZt        |j                        }|D ]*  }t        j                  d|      |j                  |       ,  y)zERemoves tracked references that are only used when loading the model.r   ^layer(_with_weights)?-[\d+]N)rK   valuesrQ   r#   LayerPUBLIC_ATTRIBUTES_delete_trackingr&   r   list$_self_unconditional_dependency_namesrematch)r   nodenamedependenciess       rl   rP   zKerasObjectLoader.del_tracking  s     !!((* (!Wdj../ 	# $$d#$ 
D.33	4
 DEEF  	(DXX5t<H!!$'	((r   c                 B   || j                   v ry| j                  |   }| j                   j                  |       |j                          t	        |t
        j                        rZ|j                  sNt        j                  | j                  |   j                        }| j                  |||j                  d             g }|j                  D ]E  }|j                  |j                         }|j#                  ||j$                  |j                   f       G | j'                  |t(        j*                  dg      }	|	t-        |d      r|j.                  D 
ci c]  }
|
j0                  |
 }}
| j2                  j4                  |	   j                  D ]h  }|j                  |j                         }|!dj7                  t(        j*                  |j                         }|j#                  ||j$                  |f       j |D ]  \  }}}| j2                  j4                  |   }t	        |t8        j:                        s<|j<                  j>                  tA        jB                         v r tA        jD                  |j<                        }n)|jF                  t(        jH                  v rtJ        }ntL        }|| jN                  v r9| jN                  |   d   |ur$tQ        jR                  dj7                  |             |jU                  d      d	k(  r4|jV                  j0                  r|jV                  j0                  d
z   |_,        t	        |tZ        j\                        rd }dj7                  ||      }|| j                  |<   | j_                  |||       ||f| jN                  |<    yc c}
w )z2Recursively records objects recreated from config.Nbuild_input_shapelayer_metrics_metricsz{}.layer_metrics.{}r   zLooks like there is an object (perhaps variable or layer) that is shared between different layers/models. This may cause issues when restoring the variable values. Object: {}rn   variablez:0c                       y r   r3   )argss    rl   <lambda>zGKerasObjectLoader._add_children_recreated_from_config.<locals>.<lambda>u  s    r   r   )0r   r   r|   _maybe_initialize_trackablerQ   r#   r   builtr   decoder   r0   _try_build_layerrT   r   _lookup_dependencyr   r   rg   _search_for_child_noder   
KERAS_ATTRhasattrr   r   r   rG   rB   	trackable	Trackablero   rv   r   registered_identifiers
get_setter_object_identifierrz   _revive_settersetattrrK   rD   rE   ry   r   _handle_namer   TrackableDataStructure#_add_children_recreated_from_config)r   objr   rg   parent_pathr0   r   r   	obj_childmetric_list_node_idmobj_metricsmetricmetric_pathchild_id
child_namechild_protosetter
child_paths                      rl   r   z5KerasObjectLoader._add_children_recreated_from_config4  s5    $333""7+K%%))'2##%#z''(""4>>'#:#C#CDh
C(,,7J*KL H^^ L	(()=)=>iooy)"3"3Y5I5IJKL 55)&&8:&73
+C(+51QVVQY5k5{{(()<=FF D)!5!56-44Y5I5I5>5I5IK+
//69#4#4kB
CD .6 %6)HjKK%%h/k	9#6#67

!
!
,
,

.
.
01))+*A*AB''9+M+MM 
T&&	&X&q): //# $*6)#4	6
 	 
 
 
(J
6



#
#!,!5!5!:!:T!A		IEE	F#>>+z:j#-dx 
..
[(,$-v$5d!K%6 6s   Nc                 "   g }| j                   j                         D ]y  }|j                  t        j                  k(  r|j                  |       2| j                  |j                  |j                  |j                        | j                  |j                  <   { |D ]K  }	 | j                  |j                  |j                  |j                        | j                  |j                  <   M y# t        $ r |r t        j                  d       Y rw xY w)z'Load all layer nodes from the metadata.zUnable to restore custom metric. Please ensure that the layer implements `get_config` and `from_config` when saving. In addition, please use the `custom_objects` arg when calling `load_model()`.N)r   r   rv   r   METRIC_IDENTIFIERr   _load_layerrg   r0   rK   r{   rD   rE   )r   r.   metric_listnode_metadatas       rl   rJ   zKerasObjectLoader.load_layers}  s   
 K..0 "		!	!Y%@%@	@=)151A1A


!9!9

 
 2"d--." % MM373C3C!!=#;#;""4$-//0M
  	M 
 L 	M	Ms   AC**!DDc                    t        j                  |      }|| j                  v r| j                  |   \  }}t        ||       |j	                  d      }t        |      rTt        j                  |      r?| j                  |      }||f| j                  |<   |s| j                  j                  |       ||fS | j                  |||      \  }}|t        ||      \  }}t        ||       ||fS )z1Load a single layer from a SavedUserObject proto.config)r   r   rK    _maybe_add_serialized_attributesrT   r   r   validate_config_get_child_layer_node_idsr   r   r   _revive_from_configrevive_custom_object)	r   rg   rv   r0   r   r   r   child_nodesr   s	            rl   r   zKerasObjectLoader._load_layer  s      *H $###&&w/ldF 'tX6||H%f	4	 ]%B%B6%J44W=261D%%g.

%
%
,
,W
56\ **:xIKC
{(X>kc6 %S(3;r   c                 &   |t         j                  k(  r| j                  |      }n'| j                  |||      xs | j	                  ||      }|y| j                  t              }| j                  || j                  j                  |   |       ||fS )z3Revives a layer/model from config, or returns None.)NN)
r   r   _revive_metric_from_config_revive_graph_network"_revive_layer_or_model_from_config_config_node_setterr   r   r   rG   )r   rv   r0   rg   r   r   s         rl   r   z%KerasObjectLoader._revive_from_config  s    Y000++H5c 
$
$Z7
C E

1
1(G
D 
 {%%n5F,,T[[w'2;r   c                 <   |j                  d      }t        j                  |      syt        j                  |d         }t        j
                  |      y|j                  dd      xs |dk(  xs |dk(  }|sy|dk(  rt        j                  |d   	      }nE|t        j                  k(  rt        j                  |	      }nt        j                  g g |d   
      }| j                  |      }||f| j                  |<   |s| j                  j                  |       |S )z$Revives a graph network from config.r   N
class_nameis_graph_networkFr   r   r   r   )inputsoutputsr   )rT   r   r   r    as_strget_registered_objectr"   r   r   SEQUENTIAL_IDENTIFIERr   r   r   r   r   )	r   rv   r0   rg   r   r   !model_is_functional_or_sequentialrj   layerss	            rl   r   z'KerasObjectLoader._revive_graph_network  s$    \\(#F((0x56J**:6B'/ 	#l"	#l" & - \!###8e	y66	6###4e##RfVn $ 6e
 ++G4F.3V_D!!'*
!!((1Lr   c                    |j                  d      }|j                  d      }|j                  d      }|j                  d      }t        j                  |      sy	 t        j	                  t        j
                  |||            }|d	   |_	        |j                  d
      
|d
   |_
        |j                  d      |j                  |d          |j                  d      
|d   |_        t        |t        j                        r$|j                  d      }||j!                  |       |j                  d      }	| j#                  |||	      }
|
sy|S # t        $ r  |rt        dj                  |            Y yw xY w)zERevives a layer/custom model from config; returns None if infeasible.r   r   shared_object_idmust_restore_from_configN)r   a\  Unable to restore a layer of class {cls}. Layers of class {cls} require that the class be provided to the model loading code, either by registering the class using @keras.utils.register_keras_serializable on the class def and including that file in your program, or by passing the class in a keras.utils.CustomObjectScope that wraps this load call.)clsr   	trainabledtypestateful	save_specr   )rT   r   r   r$   deserialize serialize_keras_class_and_configr{   RuntimeErrorrB   _namer   _set_dtype_policyr   rQ   r'   rR   _set_save_specr   )r   r0   rg   r   r   r   r   r   r   r   r   s              rl   r   z4KerasObjectLoader._revive_layer_or_model_from_config  s    l+J\\(#F||$67'||,FG((0%%

8
8&3CEFc(  CI||K ,{+cm||G(	HW-.||J+j)cl #|))*,,{+i		9% !%89!!#w0ABEJM  	! FzF*, 	, s   +E &E<;E<c                 V   t        j                  |d         }|j                  d      }t        j                  |      sy	 t
        j                  t        j                  ||            }|j                  d      }|t        |d      r|j                  |       |S # t        $ r Y yw xY w)z?Revives a metric object using the config saved in the metadata.r   r   Nr   _build)r    r   rT   r   r   r)   r   r   r{   r   r  )r   r0   r   r   r   r   s         rl   r   z,KerasObjectLoader._revive_metric_from_config/  s    x56J\\(#F((0

8
8V
LNc
 !%89$h)?	jj"#J  s   )B 	B('B(c                     |j                   st        |j                  d      rd|_         y|| j                  |d      }|2|j                  |       t        j
                  j                  ||       yy)zAttempts to build the layer._is_defaultTconvert_to_shapesF)r   r   build_infer_inputsr#   r   )r   r   rg   r   s       rl   r   z"KerasObjectLoader._try_build_layerC  sl    
yyGCII}5ci ,,W,M$	ii!"S"34r   c                     t        | j                  j                        D ]&  \  }}|| j                  vs| j	                  ||       ( y)z?Add edges for all nodes that are not waiting on initialization.N)rx   r   rG   r   _add_object_graph_edges)r   rg   r   s      rl   _load_edgeszKerasObjectLoader._load_edgesS  sB    #DKK$5$56 5	55	5$$UG45r   c                      | j                   |   S r   )r   )r   rg   s     rl   rM   zKerasObjectLoader.get_pathY  s    G$$r   c                    g }g }| j                   j                         D ]  \  }\  }}t        |t        j                        r|| j
                  v r2| j                  ||       t        |t        j                        r_t        |t        j                        rzt        |t        t        f      r|j                  |       |j                  |        t        |       t        |       | j!                          y)a  Finish setting up Keras objects.

    This function is executed after all objects and functions have been created.
    Call functions and losses are attached to each layer, and once all layers
    have been fully set up, graph networks are initialized.

    Subclassed models that are revived from the SavedModel are treated like
    layers, and have their call/loss functions attached here.
    N)rK   rL   rQ   r#   r   r   _unblock_model_reconstructionr%   
InputLayerr)   MetricRevivedLayerRevivedInputLayerr   _finalize_saved_model_layers_finalize_config_layers_reconstruct_all_models)r   layers_revived_from_configlayers_revived_from_saved_modelrg   r   _s         rl   rO   z"KerasObjectLoader.finalize_objects\  s     "$&(#"//557 0$z//0
T22
2
(($7	D+00	1dGNN+	D<):;	<'..t4"))$/!0$ !!@A67 	  "r   c                     | j                   j                         D ]Q  \  }}|\  }}||vr|||j                  |      <   t        d |D              s7| j                  j                  |       S y)z1Removes layer from blocking model reconstruction.c              3   P   K   | ]  }t        |t        j                           y wr   )rQ   r#   r   ).0r   s     rl   	<genexpr>zBKerasObjectLoader._unblock_model_reconstruction.<locals>.<genexpr>  s     =Z:++,=s   $&N)r   rL   indexallr   r   )r   layer_idr   model_idvr  r   s          rl   r  z/KerasObjectLoader._unblock_model_reconstruction  sm    44::< 5!ia		',fV\\(#$	=f=	=##**845r   c                 ,   t               }| j                  rj| j                  j                  d      }|j                  |       | j                  |   \  }}| j                  |||       t        |g       | j                  rj|t        | j                  j                               k7  rit        | j                  j                               |z
  }|D cg c]  }| j                  |   d   j                    }}t        dj                  |            yc c}w )z1Reconstructs the network structure of all models.r   zWError when loading from SavedModel -- the following models could not be initialized: {}N)r   r   r   r|   r   _reconstruct_modelr  keysr   r{   rB   )r   all_initialized_modelsr  rj   r   uninitialized_model_idsuninitialized_model_namess          rl   r  z)KerasObjectLoader._reconstruct_all_models  s    U

%
%,,003h  *33H=meV
hv6ug& 
%
% T%B%B%G%G%I!JJ d++002
36L
L  2#3 
'
'
1!
4
9
9#3 #3  =89; ; K#3s   #Dc           
         t        j                  | j                  |   j                        d   }|j                  rnt        |t        j                        rf|rt        |d   t        j                        s|d   d   d   dk(  r9|j                  dt        j                  j                  |d   d   d                ngd|d   d   d   v rZ|d   d   d   d   }|j                  dt        j                  |dd |d   |d   j                  |d   j                  d	z   
             |j                  ||d          |j                  s| j                  |      d   }| j!                  |      }| j!                  |d      }|j#                  |       |j$                  st        |t&              ss|j)                  |       nat*        j-                  ||D 	ci c]  }	|	j                  |	 c}	      \  }
}}|j                  |
||d          t*        j/                  ||       t1        |       | j3                  ||       yc c}	w )z#Reconstructs the network structure.r   r   r   r   r  batch_input_shaperp   N_input)input_shape
batch_sizer   r   r   r   Tr  )created_layers)r   r   r   r0   r   rQ   r"   r   r%   r  insertfrom_configr   r   r   r   r  _set_inputsr   dictr  r&   reconstruct_from_configconnect_ancillary_layers%_set_network_attributes_from_metadatar  )r   r  rj   r   r   r(  first_layerinput_specsinput_shapesr   r   r   r,  s                rl   r"  z$KerasObjectLoader._reconstruct_model  s(   t~~h7@@A(KF || 	E:00	1:fQi1G1GH(A|,<
--;11==Xq!(+- . F8$4Q$7$AA$X.q1(;<OP

--;11+AB/*1-1IOO!9>>H,	 2 . /
 nnV&.n1\\44X>qA((5))+)N+&{{:k4#@
++l
# (??&"I5::u#4"I @ KvwnnVW6&>n:--e^D *%0 	&&x7 #Js   H>
c                    d}i }t        j                  d      }| j                  j                  |   j                  D ]X  }|j                  |j                        }|!t        |j                  d            }t        |dz   |      }|j                  ||<   Z g }t        |      D ])  }	|j                  |	      }| |S |j                  |       + |S )zDReturns the node ids of each layer in a Sequential/Functional model.r   zlayer-(\d+)rp   )r   r.   r   rG   r   r   r   intgroupmaxrg   rangerT   r   )
r   rg   
num_layerschild_layerspatternchildr   layer_norderedns
             rl   r   z+KerasObjectLoader._get_child_layer_node_ids  s     JLjj(G""7+44 ,
--((
)a	
AGGAJgw{J/j#mml7, G: q!e	N nnU	
 Nr   c                     |s|S | j                   j                  |   j                  D ]5  }|j                  |d   k(  s| j	                  |j
                  |dd       c S  y)aa  Returns node id of child node.

    A helper method for traversing the object graph proto.

    As an example, say that the object graph proto in the SavedModel contains an
    object with the following child and grandchild attributes:

    `parent.child_a.child_b`

    This method can be used to retrieve the node id of `child_b` using the
    parent's node id by calling:

    `_search_for_child_node(parent_id, ['child_a', 'child_b'])`.

    Args:
      parent_id: node id of parent node
      path_to_child: list of children names.

    Returns:
      node_id of child, or None if child isn't found.
    r   rp   N)r   rG   r   r   r   rg   )r   	parent_idpath_to_childr?  s       rl   r   z(KerasObjectLoader._search_for_child_node  si    , ""9-66 M			]1-	-**5==-:KLLM r   c                 N   | j                  |dg      }|y| j                  j                  |   j                  j                  }|sy|d   }| j                  j                  |   }t        j                  |j                        }|d   d   }|rt        j                  d |      S |S )z6Infers input shape of layer from SavedModel functions.&call_and_return_all_conditional_lossesNr   c                     | j                   S r   )shape)specs    rl   r   z1KerasObjectLoader._infer_inputs.<locals>.<lambda>  s
    TZZ r   )
r   r   rG   functionconcrete_functionsr   decode_protocanonicalized_input_signaturer!   map_structure)	r   layer_node_idr  
call_fn_idrL  call_fn_namecall_fn_protostructured_input_signaturer   s	            rl   r  zKerasObjectLoader._infer_inputs  s    ,,@ACJ 	*%..AA %a(LKK22<@M!7!D!D33"5'*1-F 7@@mr   c                     fd}|S )z7Creates edges for nodes that are recreated from config.c                 >    | j                  |       | ||       y y r   )r   )r   r   valuer   s      rl   setattr_wrapperz>KerasObjectLoader._config_node_setter.<locals>.setattr_wrapper  s%    				%	-sD%  
.r   r3   )r   r   rX  s    ` rl   r   z%KerasObjectLoader._config_node_setter  s    ! r   N)T)F)__name__
__module____qualname____doc__r   rP   r   rJ   r   r   r   r   r   r   r
  rM   rO   r  r  r"  r   r   r  r   r3   r   rl   rI   rI      ss    $%$(:G6RM>B"&P7r( 5%$#L5;*(8T0<*r   rI   c                    | D ]  }d|_         t        t        |      dd      }|rg|j                  r[t	        j
                  ||d      |_        |j                  d   d   }d|j                  j                  v rd}|j                  |       t        j                  t        |      |_         | D ]  }t        |t              rzt!        |       t#        t        |      d      rZt        |      j$                  }|j                  sU|j&                  t)        |      }n|j&                  d   }|j+                  |       t-        |       t/        |       t1        |        y)	z=Runs the final steps of loading Keras Layers from SavedModel.T"call_and_return_conditional_lossesN)return_methodr0   expects_training_argtrainingr   )r   getattr_get_keras_attrrL  r   use_wrapped_callcallrS   function_spec	arg_names_init_call_fn_argstypes
MethodType0_unable_to_call_layer_due_to_serialization_issuerQ   r   r3  r   r^  input_signature(infer_inputs_from_restored_call_functionr/  #_restore_layer_unconditional_losses_restore_layer_activation_loss_restore_layer_metrics)r   r   
layer_callr`  call_fnr   s         rl   r  r    sR   
  CeEK/=tEJj33))
41ej"99*E
 "	z//99	9  $34##
:ECejC$  "e%(+E2	')M	N!%(KK))
""*;GD&**1-&&! (."5) 5!)"r   c                 ^    t        dj                  | j                  t        |                   )a  Replaces the `layer.call` if the layer was not fully serialized.

  Keras Model/Layer serialization is relatively relaxed because SavedModels
  are not always loaded back as keras models. Thus, when there is an issue
  tracing a non-signature function, a warning is logged instead of raising an
  error. This results in a SavedModel where the model's call function is saved,
  but the internal layer call functions are not.

  When deserialized with `tf.keras.models.load_model`, the internal layers
  which do not have serialized call functions should raise an error when called.

  Args:
    layer: Layer without the serialized call function.

  Raises:
    ValueError
  a  Cannot call custom layer {} of type {}, because the call function was not serialized to the SavedModel.Please try one of the following methods to fix this issue:

(1) Implement `get_config` and `from_config` in the layer/model class, and pass the object to the `custom_objects` argument when loading the model. For more details, see: https://www.tensorflow.org/guide/keras/save_and_serialize

(2) Ensure that the subclassed model or layer overwrites `call` and not `__call__`. The input shape and dtype will be automatically recorded when the object is called, and used when saving. To manually specify the input shape/dtype, decorate the call function with `@tf.function(input_signature=...)`.)r{   rB   r   type)r   unused_argsunused_kwargss      rl   rk  rk  O  s.    ( 	- .4VEJJU-L	N Nr   c                    | D ]  }t        |      rt        |       t        |       t        |       t	        |t
        j                        ru|j                  rit        t        |      d      rTt        t        |      dd      |_        t        j                  |j                        D ]  }t        j                  |        |j!                           y)z9Runs the final steps of loading Keras Layers from config.statesN)r   rn  ro  rp  rQ   r*   RNNr   r   rc  rb  rx  r!   flattenr	   track_variablefinalize_state)r   r   r   s      rl   r  r  r  s     e )%0 #5) 5! 	5)--(&1_U3XtDelll5<<0 )(x() 
9r   c                     t        j                  t        j                  | j                  j
                        |       | _        | j                  j                  | _        y r   )ri  rj  r   update_state_wrapper	keras_apiupdate_stateresult)r   s    rl   _finalize_metricr    sG    (()K)K##*%&,.&""))&-r   c                     t        t        |       d      rt        t        |       dg       }n| j                  j	                  dg       }|D ]  }| j                  |        y)z-Restore unconditional losses from SavedModel.layer_regularization_lossesregularization_lossesN)r   rc  rb  rS   rT   add_loss)r   losseslosss      rl   rn  rn    s\    _U#%BC_U+-JBOF
 ))--.ErJF d	NN4r   c                 ~    t        t        |       dd      }|r| j                  s		 || _        yyy# t        $ r Y yw xY w)z'Restore actiation loss from SavedModel.activity_regularizer_fnN)rb  rc  activity_regularizerAttributeError)r   r  s     rl   ro  ro    sR     !!7!:DB%"<"<#7e  #=   s   0 	<<c                    t        j                         rt        j                  }nt        j                  }t
        j                  t        t        j                  ft
        j                  t        t        j                  ft
        j                  t        |ft
        j                   t        t"        j$                  ft
        j&                  t        t(        j*                  fi}|j-                  | d      }|9||    }t/        t1        j2                  |d         |i       }|j5                  |      S t7        dj9                  |             )zRevives object from SavedModel.Nr   zUnable to restore custom object of type {} currently. Please make sure that the layer implements `get_config`and `from_config` when saving. In addition, please use the `custom_objects` arg when calling `load_model()`.)r   #executing_eagerly_outside_functionsr'   rR   r(   r   INPUT_LAYER_IDENTIFIERr  r%   r  LAYER_IDENTIFIERr  r#   r   MODEL_IDENTIFIERr   NETWORK_IDENTIFIERr&   r   r   r"   r   rT   rt  r    r   _init_from_metadatar{   rB   )rv   r0   model_classrevived_classesparent_classesrevived_clss         rl   r   r     s   ,,.$$K!''K &&
[33)5  <1A1A"B  >;"?""^^5N5N$O%%
8M8M'N/ #&&z48.$Z0Nh|,-~rCK**844
 M fZ(	* *r   c                     t        t        |       di       }| j                  D ci c]  }|j                  | }}|j	                         D ]%  \  }}||vs| j                  j                  |       ' y c c}w )Nr   )rb  rc  r   r   rL   r   )r   metrics_listr   r   r   r   s         rl   rp  rp    so    /"E,&+nn5166195-5"((* $ldF= nnF#$ 6s   A4c                   6    e Zd ZdZed        Zed        Zd Zy)r  z%Keras layer loaded from a SavedModel.c                    t        |d   |d         }|j                  d      |d   |d<   |j                  d      |d   |d<    | di |}t        j                  |      5  |d   |_        |j                  d      }t        j                  |      r||_        |j                  d	      %t        |d	   d
t        j                  i      |_	        |j                  d      t        j                  |d         |_        |j                  d      
|d   |_        |j                  d      
|d   |_        ddd       |t         fS # 1 sw Y   |t         fS xY w)zBCreate revived layer from metadata stored in the SavedModel proto.r   r   )r   r   r   Nr(  r`  r   r   	InputSpecmodule_objectsr  _is_feature_layerr   r3   )r0  rT   r   &no_automatic_dependency_tracking_scope_expects_training_argr   r   _config$recursively_deserialize_keras_objectr   r  r
   r   r  r  r   r   )r   r0   	init_argsrevived_objr   s        rl   r  z RevivedLayer._init_from_metadata  sq    f;')I ||G(#G,i||'(4'/0C'Di#$"	"K		5	5k	B 4*23I*Jk'||H%f		&	&v	.$	l	#	/!E\"')=)=>"@ 
,	-	9+7+C+C+,,.(	)	*	6(01D(E%	j	!	-'
3!4& &&'4& &&s   #CEEc                 V    | j                   j                  t        j                  d       S r   )rS   rT   r   r   r   s    rl   r  zRevivedLayer.keras_api  s!    &&**9+?+?FFr   c                 >    t        | d      r| j                  S t        )Nr  )r   r  NotImplementedErrorr  s    rl   
get_configzRevivedLayer.get_config  s    tY\\r   N)	rY  rZ  r[  r\  classmethodr  propertyr  r  r3   r   rl   r  r    s3    -' 'B G G r   r  c                 N   |t         v r=t        |t        j                        r| j	                  ||       || j
                  |<   yt        | t        j                        r+t        j                  d|      | j	                  ||d       yt        | |d      yt        | ||       y)zBSetter function that saves some attributes to separate dictionary.r   r   NT)	overwrite)r   rQ   r   r   _track_trackablerS   r&   r   r   r   rb  r   )r   r   rW  s      rl   r   r     s     
%,,-U.).E  &5.334
0$7C 
5$$7udD!-E4r   c                   &    e Zd ZdZed        Zd Zy)r  z$InputLayer loaded from a SavedModel.c                     t        |d   |d   |d   |d   |d         } | d	i |}t        j                  |      5  |d   |_        ddd       |t        fS # 1 sw Y   |t        fS xY w)
z/Revives the saved InputLayer from the Metadata.r   r   sparseraggedr(  )r   r   r  r  r(  r   Nr3   )r0  r   r  r  r   )r   r0   r  r  s       rl   r  z%RevivedInputLayer._init_from_metadata/  s     fw!!"#679I "	"K		5	5k	B /$X.k/ / s   AA(c                     | j                   S r   )r  r  s    rl   r  zRevivedInputLayer.get_config>  s    <<r   N)rY  rZ  r[  r\  r  r  r  r3   r   rl   r  r  ,  s    ,   r   r  c                 <   t        | t              r9d| v rt        j                  | |      S | D ci c]  }|t	        | |   |       c}S t        | t
        t        f      r| D cg c]  }t	        ||       c}S t        dj                  |             c c}w c c}w )z1Deserialize Keras object from a nested structure.r   r  zUnable to decode config: {})	rQ   r0  r   deserialize_keras_objectr  tupler   r{   rB   )r   r  keyr   s       rl   r  r  B  s    v33
1 1
  ! 7s8FH H ! ! & 1NC   299&A
BB!s   B$Bc                    | dcxu r|cxk7  rn nt        d| d|      | yt        | t        j                        st	        d|       t        |t        j                        st	        d|      | j
                  |j
                  k7  s| j
                  t        j                  d      S g }t        | j                  |j                        D ]j  \  }}||k7  s*t        j                  |      t        j                  |      |j                  d       G|j                  t        j                  |             l t        j                  |      S )z>Find a `TensorShape` that is compatible with both `x` and `y`.NzXCannot find a common shape when LHS shape is None but RHS shape is not (or vice versa): z vs. z'Expected x to be a TensorShape but saw z'Expected y to be a TensorShape but saw )
r   rQ   r   TensorShape	TypeErrorrankzipdimsdimension_valuer   )r   yr  dim_xdim_ys        rl   get_common_shaper  S  s   $!
/0!	56 6 Y	A|//	0
1F
GG	A|//	0
1F
GGVVqvv##D))	$!&&!&&) 7leU''.6''.6
kk$
kk,..u567 
	!	!$	''r   c                     d }| j                   d   j                  d   d   }| j                   dd D ]+  }|j                  d   d   }t        j                  |||      }- |S )a  Returns TensorSpec of inputs from a restored call function.

  Args:
    fn: Restored layer call function. It is assumed that `fn` has at least
        one concrete function and that the inputs are in the first argument.

  Returns:
    TensorSpec of call function inputs.
  c                    t        | j                  |j                        }t        | t        j                        r t        j                  || j
                        S t        | t        j                        r t        j                  || j
                        S t        j                  || j
                  | j                        S r   )r  rI  rQ   r   SparseTensorSpecr   r   RaggedTensorSpecr   
TensorSpecr   )r   r  common_shapes      rl   common_specz=infer_inputs_from_restored_call_function.<locals>.common_specv  s    #AGGQWW5L!]334++L!''BB	A}55	6++L!''BB!!,@@r   r   rp   N)rL  rT  r!   rO  )fnr  rJ  concretespec2s        rl   rm  rm  l  sv    A 
		q	!	<	<Q	?	B$''+ 8h//215Ek47D8 
+r   c                        e Zd ZdZed        Zy)r   z1Keras network of layers loaded from a SavedModel.c                 V    | |d         }t        j                  |      5  |d   |_        |j                  d      }t	        j
                  |      r||_        |j                  d      t        j                  |d         |_	        ddd       |t        fS # 1 sw Y   |t        fS xY w)zDCreate revived network from metadata stored in the SavedModel proto.r   r   r`  r   r  N)r   r  r  rT   r   r   r  r
   r   r  r   )r   r0   r  r   s       rl   r  z"RevivedNetwork._init_from_metadata  s     8F+,K
 
	5	5k	B 	.*23I*Jk'||H%f		&	&v	.$	,	-	9+7+C+C+,,.(	. &&	. &&s   A&BB(N)rY  rZ  r[  r\  r  r  r3   r   rl   r   r     s    9' 'r   r   c                     t        j                  |       5  | j                  d   }|j                  d      | j	                  |d          |d   | _        ddd       y# 1 sw Y   yxY w)z)Sets attributes recorded in the metadata.r0   r   Nr   )r   r  rS   rT   r   
_trainable)r  r0   s     rl   r3  r3    sd    33K@ 311*=H||G(##HW$56%k2K3 3 3s   ?AA'c                     t        | d      s(t        j                  |       5  d|i| _        d d d        y y # 1 sw Y   y xY w)NrS   r0   )r   r   r  rS   )r   r0   s     rl   r   r     sI     
0	1		5	5e	< <&0(%;e"< < 
2< <s   
6?c                 X    t        | di       j                  t        j                  d       S )NrS   )rb  rT   r   r   r   s    rl   rc  rc    s,    	0"	5	9	9):N:N:>
@ @r   )TNr   )^r\  r8   r   ri  google.protobufr   tensorflow.python.eagerr   tensorflow.python.frameworkr   r   r   r   tensorflow.python.kerasr	   r
   tensorflow.python.keras.enginer   $tensorflow.python.keras.optimizer_v2r    tensorflow.python.keras.protobufr   r   tensorflow.python.keras.savingr   *tensorflow.python.keras.saving.saved_modelr   r   r   @tensorflow.python.keras.saving.saved_model.serialized_attributesr   tensorflow.python.keras.utilsr   r   +tensorflow.python.keras.utils.generic_utilsr   tensorflow.python.ops.raggedr   tensorflow.python.platformr   r   rD   tensorflow.python.saved_modelr   rH   r   r   r   tensorflow.python.trackabler   r   r   tensorflow.python.utilr    r!   globalsr"   r#   r$   r%   r&   r'   r(   r)   r*   all_functionsunionall_checkpointable_objectsr   r|   r   rF   rw   r   objectrI   r  rk  r  r  rn  ro  r   rp  r  r   r  r  r  rm  r   r3  r   rc  r3   r   rl   <module>r     s   ( 	 	  # + + 5 4 3 + 0 5 = ? 9 7 @ A < \ 7 7 B 6 , < 9 5 @ 7 9 7 ) ' gi8:
')/1
 WY$& 7902 gi/1 GI-/ wy02 Y	68.0	 $1177..0    i** +^B/.$j jZ+"` NFB*
*<$- 6 - ` < ,C"(22'\ '43<@r   