
    BVh/                        d 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*  e+g d      Z, e-g d      Z.d Z/ G d  d!e"j`                        Z1 G d" d#e"j`                        Z2d$ Z3d% Z4d=d&Z5d' Z6d( Z7d) Z8 G d* d+e"j`                        Z9d, Z:d- Z;d. Z< e*d/g 0      d>d1       Z= G d2 d3e"j`                        Z> G d4 d5e"j`                        Z?d6 Z@d7 ZA G d8 d9ej                        ZCd: ZDd; ZEd< ZFy)?z8Utilities for working with and creating SaveableObjects.    N)saveable_compat)session)context)constant_op)device)dtypes)ops)tensor)tensor_util)	array_ops)gen_control_flow_ops)ref_variable)resource_variable_ops)	state_ops)	variables)
tf_logging)base)base_delegate)python_state)trackable_utils)saveable_object)core)compat)nest)object_identity)	tf_export)Variable
VariableV2AutoReloadVariableVarHandleOpReadVariableOp)r   r   r   c                     t        j                  |       r| S t        j                  j	                  |       }|j                  dd      }|j                         S )zCreates a new device string based on `device_string` but using /CPU:0.

  If the device is already on /CPU:0 or it is a custom device, this is a no-op.

  Args:
    device_string: A device string.

  Returns:
    A device string.
  CPUr   )device_typedevice_index)r   is_custom_devicepydev
DeviceSpecfrom_stringreplace	to_string)device_stringparsed_devices     f/home/dcms/DCMS/lib/python3.12/site-packages/tensorflow/python/training/saving/saveable_object_util.pyset_cpu0r/   9   sR     m,""..}=-''E'J-		 	 	""    c                   (     e Zd ZdZ fdZd Z xZS )ReferenceVariableSaveablez?SaveableObject implementation that handles reference variables.c                 x    t        j                  ||||j                        }t        t        |   ||g|       y Ndtype)r   SaveSpecr6   superr2   __init__)selfvar
slice_specnamespec	__class__s        r.   r9   z"ReferenceVariableSaveable.__init__N   s3    ##CTKD	
#T3C$Fr0   c                     |d   }|t        j                  ||d         }t        j                  | j                  ||d u xr( | j                  j                         j                               S )Nr   )validate_shape)r   reshaper   assignop	get_shapeis_fully_defined)r:   restored_tensorsrestored_shapesrestored_tensors       r.   restorez!ReferenceVariableSaveable.restoreR   sl    &q)O"!))/?1;MNo&$. /,,.	0 0r0   __name__
__module____qualname____doc__r9   rJ   __classcell__r?   s   @r.   r2   r2   K   s    GG0r0   r2   c                   (     e Zd ZdZ fdZd Z xZS )ResourceVariableSaveablez=SaveableObject implementation that handles ResourceVariables.c                    |j                   | _        |j                  | _        t	        |t
        j                        r!|j                  j                  d   | _	        |}nIt        j                  |      rd }|j                  | _	         ||      }nt        dt        |             t        j                   ||||j"                  |j                         }t$        t&        | S  ||g|       y )Nr   c                       fd}|S )Nc                  ~   t        j                  j                        5  t        j                         rj	                         s
	 d d d        y j                         } t        j                  d      5  t        j                  |       cd d d        cd d d        S # 1 sw Y   nxY w	 d d d        y # 1 sw Y   y xY w)Nz/device:CPU:0)r	   r   r   executing_eagerlyis_initializedread_value_no_copyr   identity)xvs    r.   fzLResourceVariableSaveable.__init__.<locals>._read_variable_closure.<locals>.fi   s    zz!((# 
+((*13C3C3E 	
+ 
+ $$&A O, +''*+ +
+ 
++ + +
+ 
+ 
+s)   &B3%B35B
	B3B&	"B33B< )r\   r]   s   ` r.   _read_variable_closurezAResourceVariableSaveable.__init__.<locals>._read_variable_closureh   s    	+ r0   zCSaveable is neither a resource variable nor a read operation. Got: )r6   r   )r   _var_deviceshape
_var_shape
isinstance
tensor_libTensorrD   inputs	handle_opr   is_resource_variablehandle
ValueErrorreprr   r7   r6   r8   rS   r9   )r:   r;   r<   r=   r
   r_   r>   r?   s          r.   r9   z!ResourceVariableSaveable.__init__`   s    zzDiiDO#z(()vv}}Q'dnf		3	3C	8  zzdn%c*f9+    ##FJ*-))CJJHD	
"D23Er0   c                    |d   }|t        j                  ||d         }t        j                  | j                        5  t        j
                  |      }	 t        j                  | j                  | j                  |      }|cddd       S # t        $ r9}t        d|j                   d| j                   d| j                   d      |d}~ww xY w# 1 sw Y   yxY w)z@Restores tensors. Raises ValueError if incompatible shape found.r   Nz(Received incompatible tensor with shape z0 when attempting to restore variable with shape z
 and name .)r   rB   r	   r   r`   rZ   r   !shape_safe_assign_variable_handlerg   rb   rj   ra   r=   )r:   rG   rH   rI   assigned_variablees         r.   rJ   z ResourceVariableSaveable.restore   s    &q)O"!))/?1;MNo	D$$	% 
!**?;o-1SSNNDOO_> 
 

  -67L7L6M N>>Boo=N O		{!%& ,-	--
 
s0    C+BC	C4C

CCCrK   rQ   s   @r.   rS   rS   ]   s    E FDr0   rS   c                 r    t        | t        j                        xr | j                  j                  t
        v S N)rc   rd   re   rD   type_VARIABLE_OPS)r\   s    r.   _tensor_comes_from_variableru      s'    	Az((	)	Haddii=.HHr0   c              #     K   t        |t              st        d|       t        | t        j                        r|  yt        | t
        t        t        j                  f      rLt        | t        j                        rt        |       } d}| D ]  }t        |t        j                        r| #t        |t        j                        st        d|       |j                  st        d|       ||j                  j                  }n>||j                  j                  k7  r%t        d| d|j                  j                         |j                  j                  t        v r$t!        ||j                  j"                  |       t%        ||j                  j"                  |       ! yt        | t&        j(                        rt        | t        j                        st+        | d      j-                         D ]m  \  }}|t&        j.                  k(  r|}n|t0        j2                  k(  r|}n|d	z   |z   }t5        |      r ||      n|} t7        | | j8                        D ]  } |   o yt        | t:        j<                        r+| j>                  r| j@                  }n| }t%        |d
|       ytC        jD                         rt        dt        |        d      tG        jH                  | d      }tK        |      st        d|       |j                  j                  t        v rt!        |d
|       yt%        |d
|       yw)a  Create `SaveableObject`s from an operation.

  Args:
    op: A variable, operation, or SaveableObject to coerce into a
      SaveableObject.
    name: A string name for the SaveableObject.

  Yields:
    `SaveableObject`s which together save/restore `op`.

  Raises:
    TypeError: If `name` is not a string.
    ValueError: For operations with no known conversion to SaveableObject.
  zfnames_to_saveables must be a dict mapping string names to trackable operations. Name is not a string: NzSlices must all be Variables: zSlices must all be slices: z)Slices must all be from the same tensor: z != T	tf1_saver_ zJCan only save/restore ResourceVariables when executing eagerly, got type: rm   as_refz]names_to_saveables must be a dict mapping string names to Tensors/Variables. Not a variable: )&rc   str	TypeErrorr   SaveableObjectlisttupler   PartitionedVariabler   rj   _save_slice_info	full_namerD   rs   _REF_VARIABLE_OPSr2   r>   rS   	trackable	Trackablesaveable_objects_from_trackableitemsVARIABLE_VALUE_KEYr   SERIALIZE_TO_TENSORS_NAMEcallablesaveable_objects_for_opr=   r   BaseResourceVariable_in_graph_mode_graph_elementr   rW   r	   convert_to_tensorru   )rD   r=   
slice_namevariableattrfactoryr   s          r.   r   r      s     
D#	
	77;f	>? ? O223
H"tUI$A$ABC"i3348bJ -	Ho<<	=)"4"459(DEE&&6xjABB		..88
22<<<7
|4((22356 	6 
		.	.'h//44d< 	< 'x1J1J1O1O'+- 	-%-* "i))*:)

4 9
d!EGg	--	- 	?<<<	3J%	"*7"3GIb'BGG4 "  "+@@A			$$$Xr488		"	"	$ 99=b
!E F 	F &&r$7h(2;;C*FG 	G 
		.	.'"d;;&xT::s   MMc                    t        | t        t        t        f      st	        d|        t        j                  t        |             } t        | d       } i }| D ]  }t        |t        j                        xs t        |t        j                        }t        |t        j                        r|||j                  <   dt        |t        j                         r6|j                  |v rt#        d|j                         |||j                  <   t        |t        j$                        re|j&                  rY|j&                  j(                  }||v r7t        ||   t              st#        d|       ||   j+                  |       +|g||<   3t        |t,        j.                        rX|sVt1        |d      j3                         D cg c]  }t5        |      r |       n| }}|j7                  t9        |             t;        |dd      smt        |t        j                        st#        d	t=        |       d
      |j?                  |j@                  |      }||ust#        d|j@                   d      |rWt        |t        j                        r|jB                  }ntE        jF                  |d      }tI        |      st	        d|       |jJ                  j<                  dk(  r.|jJ                  jL                  d   jJ                  j                  }n|jJ                  j                  }||v rt#        d|       |||<    |S c c}w )a;  Create a dictionary of names to operation lists.

  This method is only used when the variable name matters (e.g. when saving
  or restoring from a TF1 name-based checkpoint). In TF2, this can be called
  from `tf.train.Checkpoint.restore` when loading from a name-based checkpoint.

  Args:
    op_list: A (nested) list, tuple, or set of Variables or SaveableObjects.
    convert_variable_to_tensor: Whether or not to convert single Variables
      with no slice info into Tensors.

  Returns:
    A dictionary of names to the operations that must be saved under
    that name.  Variables with save_slice_info are grouped together under the
    same key in no particular order.

  Raises:
    TypeError: If the type of op_list or its elements is not supported.
    ValueError: If at least two saveables share the same name.
  z<Variables to save should be passed in a dict or a list. Got c                     | j                   S rr   r=   r[   s    r.   <lambda>z!op_list_to_dict.<locals>.<lambda>  s
    !&& r0   keyz+At least two variables have the same name: z1Mixing slices and non-slices with the same name: Trw   r   zSCan only save/restore ResourceVariables when eager execution is enabled. Got type: rm   zBTwo different ResourceVariable objects with the same shared_name 'z' were passed to the Saver. This likely means that they were created in different Graphs or isolated contexts, and may not be checkpointed together.r{   z$Variable to save is not a Variable: r!   r   )'rc   r   r   setr~   r   flattensortedr   r   r   RefVariabler   r   r=   r   r   rj   r   r   r   appendr   r   r   valuesr   updateop_list_to_dictgetattrrs   
setdefault_shared_namer   r	   r   ru   rD   rf   )	op_listconvert_variable_to_tensornames_to_saveablesr;   resource_or_ref_variabler=   r   trackable_saveablesset_vars	            r.   r   r      s9   * 
GdE3/	0
 !!(	+ , , LLg'' 7 01' :'c3-BBC 	23001  #556%("	C66	7	'	'9#((DF 	F%("	C++	,1E1E!!++d	#	#,T2D9N"V% & &4 '',$'54 	C,,	-6N .cTBIIKN !)79w6N N 
-
.0 S*D1#4IIJ''+Cyk45 5 %//0@0@#F#!../ 0IIJ J &2GGH$$C''D9C,S1B3%HII66;;**q!$$))$$%%HOP
P#&4 u:'z 
ONs   Mc                     |j                   &|j                   |v rt        d|j                         | j                  |       |j	                  |j                          y)aI  Adds the saveable to the saveables list.

  Args:
    saveables: List to append the SaveableObject to.
    seen_ops: Set of the ops of the saveables already processed.  Used to
      check that each saveable is only saved once.
    saveable: The saveable.

  Raises:
    ValueError: If the saveable has already been processed.
  Nz3The same saveable will be restored with two names: )rD   rj   r=   r   add)	saveablesseen_opssaveables      r.   _add_saveabler   R  sU     [[!8
J ( ) )8
,,x{{r0   c                     g }t        j                         }t        | j                         d       D ]#  \  }}t	        ||      D ]  }t        |||        % |S )a  Returns the variables and names that will be used for a Saver.

  Args:
    names_to_saveables: A dict (k, v) where k is the name of an operation and
       v is an operation to save or a BaseSaverBuilder.Saver.

  Returns:
    A list of SaveableObjects.

  Raises:
    TypeError: If any of the keys are not strings or any of the
      values are not one of Tensor or Variable or a trackable operation.
    ValueError: If the same operation is given in more than one value
      (this also applies to slices of SlicedVariables).
  c                     | d   S )Nr   r^   r   s    r.   r   z+validate_and_slice_inputs.<locals>.<lambda>y  s
    qt r0   r   )r   ObjectIdentitySetr   r   r   r   )r   r   r   r=   rD   converted_saveable_objects         r.   validate_and_slice_inputsr   e  sp      )..0(+113+- DhdB &=R%F D!Ix)BCDD
 
r0   c                     t        |t        j                        rt        j                  d| d       g S t        d | D              rg S | S )z:Makes sure SaveableObjects are compatible with SavedModel.zNote that object zu stores python values into the checkpoint. These values will not be restored when loading the SavedModel into python.c              3   P   K   | ]  }t        |t        j                           y wrr   )rc   r   NoRestoreSaveable).0r   s     r.   	<genexpr>z5validate_saveables_for_saved_model.<locals>.<genexpr>  s%      	$ 
Hi99	: 	$s   $&)rc   r   PythonStateloggingwarnany)r   objs     r.   "validate_saveables_for_saved_modelr     sV    \--.LL
C5 ! 	 I 	$"	$ $I	r0   c                   (     e Zd ZdZ fdZd Z xZS )RestoredSaveableObjectzFSaveableObject restored from SavedModel using the traced save/restore.c           	         || _         || _        t        j                  |      r|}n2t	        j
                         5  t        j                  |      }d d d         |      }g }t        ||      D ]4  \  \  }}	}
|j                  t        j                  |
d   |	||z                6 t        t        | ;  d ||       y # 1 sw Y   lxY w)Nr
   )save_functionrestore_functionr   
is_tf_typer	   
init_scoper   constantzipr   r   r7   r8   r   r9   )r:   names_and_slicesr   r   r=   name_tensortensorsspecsstr_name	str_slicetensor_infor?   s              r.   r9   zRestoredSaveableObject.__init__  s    &D,Dd#k>> 1!**401K(GE.12BG.L >*9{ll?++K,A9,08O= >> 

 $0udC1 1s   B==Cc                     ~ | j                   t        t        | j                              D cg c]  }||   	 c} S c c}w rr   )r   rangelenr   )r:   rG   rH   is       r.   rJ   zRestoredSaveableObject.restore  s@     4  ',S_'=	>!
1
	>@ @	>s   >rK   rQ   s   @r.   r   r     s    ND @r0   r   c           	      H   g }t        j                         5  | j                         D ]  \  }} |d      D ]  }|d   }|d   }t        j                         sPt        j
                         }|$|d   |d   }nt        j                         x}|d<   |j                  ||g      \  }}|j                  t        |      t        |      f         	 ddd       i }	| j                         D ](  \  }\  }}
t        j                  t        |||
      |	|<   * |	S # 1 sw Y   HxY w)zEReturns a dict of SaveableObject factories generated from loaded fns.rz   r=   r<   Nr   )r   r   r   )r	   r   r   r   rW   get_default_sessionr   Sessionrunr   _convert_to_stringr   	functoolspartialr   )saveable_fn_by_nametemp_sessionr   save_fnry   r   r=   r<   sesssaveable_factories
restore_fns              r.   recreate_saveable_objectsr     sB    
~~ -)002 -
  -+6" .
((*((*$\A*!!_d'.'88d\!_!XXtZ&89
$
t$z*!, 	----$ %8%>%>%@ %!d!Wj(00)#	 %t% 
3- -s   B9DD!c                     	 ||      S | t         j                  k(  r
 ||      S t        |      r5|j                  d   fd}|j                  d   fd} ||||      S  ||      S )aR  Creates a SaveableObject while potentially in a different graph.

  When creating the frozen saver for SavedModel, the save and restore ops are
  placed in a separate graph. Since RestoredSaveableObject uses tf.functions to
  save and restore, the function captures must be mapped to the new graph.

  Args:
    name: Name of SaveableObject factory.
    key: Checkpoint key of this SaveableObject.
    factory: Factory method for creating the SaveableObject.
    call_with_mapped_captures: Helper that calls a tf.function while remapping
      the captures.

  Returns:
    a SaveableObject.
  r   )r=   call_with_mapped_capturesr   c                      | g      S rr   r^   )r=   r   concrete_save_fns    r.   r   z'create_saveable_object.<locals>.save_fn  s    &'7$@@r0   r   c                       |       S rr   r^   )rG   r   concrete_restore_fns    r.   r   z*create_saveable_object.<locals>.restore_fn  s    &':<LMMr0   )r   r   r=   )r   r   'is_factory_for_restored_saveable_objectkeywords)r=   r   r   r   r   r   r   r   s      `  @@r.   create_saveable_objectr     s    " &	_666-FH H.w7''8A "**+=>N :  r0   c                 ^    t        | t        j                        xr | j                  t        u S rr   )rc   r   r   funcr   )r   s    r.   r   r     s)    
Wi//
0 1
,,0
02r0   z5__internal__.tracking.saveable_objects_from_trackable)v1c                 J    t         t        j                        r@t        j                  t	        j
                  t         j                   j                        iS |r j                         }|r|S t               rd fd	}t        j                  |iS  j                         S )a
  Returns SaveableObject factory dict from a Trackable.

  Args:
    obj: A `Trackable`
    tf1_saver: Boolean, whether this is being called from a TF1 Saver (
        `tf.compat.v1.train.Saver`). When this is True, the SaveableObject will
        be generated from `obj`'s legacy `_gather_saveables_for_checkpoint` fn.
        When saving with TF2, `Trackable._serialize_from_tensors` is preferred.

  Returns:
    A dict mapping attribute names to SaveableObject factories (callables that
    produce a SaveableObject).
  )state_callbackrestore_callbackc           	      N   j                   }|r$t        |t        j                        r
 ||g       }n |       }g }g }|j	                         D ]  \  }}|j                  |       t        |t              sd|i}| t        j                  |      z   }|j	                         D ]X  \  }	}
t        |
t        j                        r|
}||_        |	|_        nt        j                  |
|	|      }|j                  |       Z  t        || |t        j                        xs d|      S )Nrz   )r   r   r=   local_namesprefixr   )_serialize_to_tensorsrc   r   ConcreteFunctionr   r   dictr   escape_local_namer   r7   r=   r<   TrackableSaveabler   get_saveable_name)r=   r   r   tensor_dictr   r   tensor_namemaybe_tensor	spec_namer<   r
   r>   r   s               r.   create_saveablez8saveable_objects_from_trackable.<locals>.create_saveable  s#   ))g
#
Wd33
4/<iek'2'8'8': 
#+|;',-l+,?<<[II	"."4"4"6 	J 8 89D!DI(DO"++FJ	JD
,,t
	" ! 2237=2$=? ?r0   )rz   N)rc   r   r   PYTHON_STATEr   r   _PythonStringStateSaveable	serializedeserialize _gather_saveables_for_checkpoint!trackable_has_serialize_to_tensorr   r   )r   rx   r   r  s   `   r.   r   r     s     \--.!!*"}}!$2  ==?&s+!?F 55GG//11r0   c                   2     e Zd ZdZ	 d fd	Zd Zd Z xZS )r   z>A SaveableObject that defines `Trackable` checkpointing steps.c                 h    || _         || _        || _        || _        t        t
        |   |||       y rr   )_prefix_local_names
_trackable_call_with_mapped_capturesr8   r   r9   )r:   r   r   r=   r   r   r   r?   s          r.   r9   zTrackableSaveable.__init__=  s5    DL#DDO&?D#	
T+C=r0   c           	      J   ~i }t        | j                        D ]  \  }}||   ||<    | j                  j                  }t	        j
                         sst        | j                  D cg c]L  }t        |j                  t        j                        r&|j                  j                  j                  t        v N c}      r ||      S | j                  r.t        |t         j"                        r| j                  ||g      }n ||      }||S t%        j&                         S c c}w rr   )	enumerater  r  _restore_from_tensorsr	   #executing_eagerly_outside_functionsr   r   rc   _tensorrd   re   rD   rs   r   r  r   r   r   no_op)	r:   rG   rH   restored_tensor_dictn
local_namer   r>   rets	            r.   rJ   zTrackableSaveable.restoreE  s	   "4#4#45 =:)9!)<:&= 66J 224JJ>8dllJ$5$56 	 11>8 :9 ,-- 	'':t445++J9M8NOc+,c
j%%''>8s   &AD c                     t        | j                  | j                        D cg c]   \  }}| j                  |z   |j                  f" c}}S c c}}w rr   )r   r  r   r  r=   )r:   r  r>   s      r.   #get_proto_names_and_checkpoint_keysz5TrackableSaveable.get_proto_names_and_checkpoint_keys_  sM    $'(9(94::$FH 
D \\J&		2 H H Hs   %Arr   )rL   rM   rN   rO   r9   rJ   r  rP   rQ   s   @r.   r   r   :  s    F *.>(4Hr0   r   c                   .     e Zd ZdZ fdZd Zd Z xZS )r  z#Saves Python state in a checkpoint.c                 x   fd}|| _         || _        t        j                  d      5  t	        j
                  dt        j                        | _        ddd       t        j                  | j                  d|t        j                        }t        t        | 7  | j                  |g|       y# 1 sw Y   [xY w)a5  Configure saving.

    Args:
      name: The checkpoint key to write to.
      state_callback: A function taking no arguments which returns a string.
        This function is run every time a checkpoint is written.
      restore_callback: A function taking a Python string, used to restore
        state.
    c                  f    t        j                         5           cd d d        S # 1 sw Y   y xY wrr   )r	   r   )r   s   r.   _state_callback_wrapperzD_PythonStringStateSaveable.__init__.<locals>._state_callback_wrapperr  s(    >>       s   '0z/cpu:0rz   r5   N)_state_callback_restore_callbackr	   r   r   r   r   string_save_stringr   r7   r8   r  r9   )r:   r=   r   r   r  r>   r?   s     `   r.   r9   z#_PythonStringStateSaveable.__init__g  s      3D-D	H	 H%..rGdH##2t6==:D	
$d4T5F5F59;	H Hs   +B00B9c                 :    | j                   | j                         iS )z4When running a graph, indicates fresh state to feed.)r"  r  r:   s    r.   feed_dict_additionsz._PythonStringStateSaveable.feed_dict_additions  s    t33566r0   c                 p      fd}t        j                  |t        j                   j                  d      S )z?Create a frozen `SaveableObject` which saves the current state.c                  j    t        j                   j                         t        j                        S r4   )r   r   r  r   r!  r$  s   r.   _constant_statez:_PythonStringStateSaveable.freeze.<locals>._constant_state  s#    !!$"6"6"8NNr0   zcpu:0)r
   r6   r=   r   )r   r   r   r!  r=   )r:   r(  s   ` r.   freezez!_PythonStringStateSaveable.freeze  s2    O &&mmYY	 r0   )rL   rM   rN   rO   r9   r%  r)  rP   rQ   s   @r.   r  r  d  s    +;07
r0   r  c                    | t         j                  u rt        | j                        S 	 d| j                  v ry	 t        |       j                         D ]_  }|t         j                  u rt        | j                        c S |t        j                  u r yd|j                  v r yd|j                  v s_ y y# t
        t        f$ r Y w xY w)z@Returns whether obj's class has `_serialize_to_tensors` defined.r   TFr  )r   DelegatingTrackableMixinr  r  __dict__AttributeErrorr~   rs   mror   r   )r   ts     r.   r  r    s    M222 -S^^<<	#,,.  / 9==? aM222 /s~~>>I 	 AJJ	.	+qzz	9 
+ )	$ 		s   B5 5CCc                 R    t        j                  t        j                  |             S rr   )r   as_strr   constant_valuer   s    r.   r   r     s    	{11!4	55r0   c                   F    e Zd ZdZdZd Zed        Zed        Zd Z	d Z
y)	SaveableCompatibilityConverteraW  Converts object's `SaveableObjects` to functions used in TF2 checkpointing.

  A class that converts a Trackable object's `SaveableObjects` to save and
  restore functions with the same signatures as
  `Trackable._serialize_to_tensors` and `Trackable._restore_from_tensors`.
  This class also produces a method for filling the object proto.
  _obj
_saveablesc                      || _         || _        y)zkConstructor.

    Args:
      obj: A Trackable object.
      saveables: A list of saveables for `obj`.
    Nr5  )r:   r   r   s      r.   r9   z'SaveableCompatibilityConverter.__init__  s     DIDOr0   c                     | j                   S rr   )r6  r$  s    r.   r   z"SaveableCompatibilityConverter.obj  s    99r0   c                     | j                   S )zFReturns a list of SaveableObjects generated from the Trackable object.)r7  r$  s    r.   r   z(SaveableCompatibilityConverter.saveables  s     ??r0   c                 ,    t        | j                        S )z'Returns a dict of tensors to serialize.)saveable_object_to_tensor_dictr   r$  s    r.   r   z4SaveableCompatibilityConverter._serialize_to_tensors  s    )$..99r0   c                 D   g }| j                   D ]$  }|j                  d |j                  D               & t        |      |j	                         k7  r5t        d| j                   d| dt        |j	                                       t        | j                         |      S )z1Returns the restore ops defined in the Saveables.c              3   l   K   | ],  }t        j                  t        |j                               . y wrr   )r   extract_local_namer   r=   )r   r>   s     r.   r   zGSaveableCompatibilityConverter._restore_from_tensors.<locals>.<genexpr>  s-      & 
,
,-?		-J
K&s   24zCould not restore object zE because not all expected tensors were in the checkpoint.
	Expected: z
	Got: )	r   extendr   r   keysrj   r6  r   saveable_object_to_restore_fn)r:   rG   expected_keysr   s       r.   r  z4SaveableCompatibilityConverter._restore_from_tensors  s    
 MNN & &nn& && =-22442499+ >((5"4(8(=(=(?#@"AC D D
 9(89IJJr0   N)rL   rM   rN   rO   	__slots__r9   propertyr   r   r   r  r^   r0   r.   r4  r4    sF     %)     :Kr0   r4  c                    i }| D ]}  }|j                   D ]l  }t        |j                        }t        |j                        }t	        |j
                        r|n|j
                  }|r||j                  |i       |<   h|||<   n  |S )z:Converts a list of SaveableObjects to a tensor dictionary.)r   r   r=   r<   r   r  r   )r   r   r   r>   r=   r<   r
   s          r.   r<  r<    s    + 
#h 	#		*d%doo6j  -t4<<f	7=tR(4"D	#
# 
r0   c                       fd}|S )zAGenerates `Trackable._restore_from_tensors` from SaveableObjects.c                 T   i }D ]  }g }|j                   D ]l  }t        j                  t        |j                              }t        |j
                        }| |   }t        |t              sd|i}|j                  ||          n |j                  |d       ||j                  <    |S )Nrz   )rH   )
r   r   r?  r   r=   r<   rc   r   r   rJ   )	rG   restore_opsr   saveable_restored_tensorsr>   r=   r<   r   r   s	           r.   r  z<saveable_object_to_restore_fn.<locals>._restore_from_tensors  s    K ;"$.. C$112DTYY2OP'8
'-,-l+,!((j)ABC $,#3#3
#T $4 $;k(-- ; r0   r^   )r   r  s   ` r.   rB  rB    s    $ 
r0   c           
         t        j                         }| j                         D ]  \  }}|s
t        |t              rK|j
                  }i ||<   |j                  D ]*  }t        j                  |j                        }|g||   |<   , eg }g }t        j                  |      xs d}	|j                         D ]  \  }
}t        |t              sd|i}|j                         D ]W  \  }}t        |t        j                        r|j                  |       2|j                  t        j                  |||
             Y |j                  t        j                  |
|	              t        j                   t#        t%        |j'                                           }t        j(                  t+        |||||	      gi||<    |S )a'  Converts a tensor dict to a SaveableObject cache.

  Args:
    serialized_tensors: Map from Trackable to a tensor dict. The tensor dict
      maps checkpoint key (-> slice_spec) -> Tensor

  Returns:
    A dict mapping Trackable objects to a map from local savable name to
    SaveableObject.
  rz   )r   r   )r   ObjectIdentityWeakKeyDictionaryr   rc   r4  r   r   r   r?  r=   r   r   r   r   r7   r   extract_object_namenextiterrA  r   r   )serialized_tensorssaveables_cacher   r   trackable_objr   r  r   r   r   checkpoint_keyr   r<   r
   object_names                  r.   $serialized_tensors_to_saveable_cacherU    s    $CCE/,224 "Oc;#56ggm')om$mm @($77F
6>Z&z2@ E K..s39rF(3(9(9(; E$d+L) , 2 2 4 A
*ffo667
,,v

,,//0:0>@ A	A ;;N<BD EE "55T+""$%&(K 	114EV5M 4NOOCA"OF 
r0   )T)F)GrO   r   tensorflow.python.checkpointr   tensorflow.python.clientr   tensorflow.python.eagerr   tensorflow.python.frameworkr   r   r'   r   r	   r
   rd   r   tensorflow.python.opsr   r   r   r   r   r   tensorflow.python.platformr   r   tensorflow.python.trackabler   r   r   r   r   !tensorflow.python.training.savingr   tensorflow.python.typesr   tensorflow.python.utilr   r   r    tensorflow.python.util.tf_exportr   r   rt   	frozensetr   r/   r   r2   rS   ru   r   r   r   r   r   r   r   r   r   r   r   r  r  r   r   r4  r<  rB  rU  r^   r0   r.   <module>rb     sc   ?  8 , + 3 7 . + < 3 + 6 . 7 + + < 9 5 4 7 = ( ) ' 2 6  ' ( NO #$0 > > 0$5== 5pIV;r]@&4@_;; @2B$N2
 BrJC2 KC2L'H66 'HT)!?!? )X"J62KY%8%8 2Kj"00r0   