
    BVh                     4   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ZdZ ed e       d      ZddZddZ	 	 ddZ d Z!d Z"d Z#d Z$d Z%	 ddZ&d Z'd Z(d Z)y# e$ r dZY Dw xY w) z@Functions for saving and loading a Keras Model from HDF5 format.    N)backend)optimizer_v1)model_config)saving_utils)
json_utils)
LazyLoader)ask_to_proceed_with_overwrite)	variables)gfile)
tf_loggingi   sequential_libz)tensorflow.python.keras.engine.sequentialc                    t         t        d      t        | j                        t        | j                        k7  rt        j                  d       t        |t         j                        s|s-t        j                  j                  |      rt        |      }|syt        j                  j                  |      }t        j                  j                  |      st        j                   |       t        j                  |d      }d}n|}d}	 t#        j$                  | |      }|j'                         D ]q  \  }	}
t        |
t(        t*        t,        f      rBt/        j0                  |
t2        j4                        j7                  d	      |j8                  |	<   c|
|j8                  |	<   s |j;                  d
      }| j<                  }t?        ||       |rF| j@                  r:t        | j@                  tB        jD                        stG        || j@                         |jI                          |r|jK                          yy# |r|jK                          w w xY w)a  Saves a model to a HDF5 file.

  The saved model contains:
      - the model's configuration (topology)
      - the model's weights
      - the model's optimizer's state (if any)

  Thus the saved model can be reinstantiated in
  the exact same state, without any of the code
  used for model definition or training.

  Args:
      model: Keras model instance to be saved.
      filepath: One of the following:
          - String, path where to save the model
          - `h5py.File` object where to save the model
      overwrite: Whether we should overwrite any existing
          model at the target location, or instead
          ask the user with a manual prompt.
      include_optimizer: If True, save optimizer's state together.

  Raises:
      ImportError: if h5py is not available.
  Nz`save_model` requires h5py.a  Found duplicated `Variable`s in Model's `weights`. This is usually caused by `Variable`s being shared by Layers in the Model. These `Variable`s will be treated as separate `Variable`s when the Model is restored. To avoid this, please save with `save_format="tf"`.wmodeTF)defaultutf8model_weights)&h5pyImportErrorlenweights_undeduplicated_weightsloggingwarning
isinstanceFileospathisfiler	   dirnameexistsr   MakeDirsr   model_metadataitemsdictlisttuplejsondumpsr   get_json_typeencodeattrscreate_grouplayerssave_weights_to_hdf5_group	optimizerr   TFOptimizer$save_optimizer_weights_to_hdf5_groupflushclose)modelfilepath	overwriteinclude_optimizerproceeddirpathfopened_new_filer$   kvmodel_weights_groupmodel_layerss                Z/home/dcms/DCMS/lib/python3.12/site-packages/tensorflow/python/keras/saving/hdf5_format.pysave_model_to_hdf5rC   4   s   4 
\
3
44
 	3u<<==OO G H 
Hdii	(1-h7g ggooh'G77>>'"nnW		(%AOAO!008IJN$$& 1	AdE*	+ZZz//117 	

 
 ..9<<L2LA 	eoou(@(@A*1eoo>GGIggi ggi s   DH< <Ic                    t         t        d      |si }t        | t         j                         }|rt        j                  | d      }n| }d}	 |j                  j                  d      }|t        d      t        |d      r|j                  d      }t        j                  |      }t        j                  ||	      }t        |d
   |j                         |r	|j                  j                  d      }t        |d      r|j                  d      }|*t        j                  d       ||r|j!                          S S t        j                  |      } |j"                  di t%        j&                  ||      ddi t%        j(                  |       d|v rM	 |j*                  j-                  |j.                         t5        |      }	 |j*                  j7                  |       |r|j!                          |S # t0        t2        f$ r t        j                  d       Y aw xY w# t        $ r t        j                  d       Y ^w xY w# |r|j!                          w w xY w)aN  Loads a model saved via `save_model_to_hdf5`.

  Args:
      filepath: One of the following:
          - String, path to the saved model
          - `h5py.File` object from which to load the model
      custom_objects: Optional dictionary mapping names
          (strings) to custom classes or functions to be
          considered during deserialization.
      compile: Boolean, whether to compile the model
          after loading.

  Returns:
      A Keras model instance. If an optimizer was found
      as part of the saved model, the model is already
      compiled. Otherwise, the model is uncompiled and
      a warning will be displayed. When `compile` is set
      to False, the compilation is omitted without any
      warning.

  Raises:
      ImportError: if h5py is not available.
      ValueError: In case of an invalid savefile.
  Nz`load_model` requires h5py.rr   r   zNo model found in config file.decodezutf-8)custom_objectsr   training_configzgNo training configuration found in the save file, so the model was *not* compiled. Compile it manually.from_serializedToptimizer_weightszError when creating the weights of optimizer {}, making it impossible to restore the saved optimizer state. As a result, your model is starting with a freshly initialized optimizer.zuError in loading the saved optimizer state. As a result, your model is starting with a freshly initialized optimizer. )r   r   r   r   r-   get
ValueErrorhasattrrF   r   model_config_libmodel_from_configload_weights_from_hdf5_groupr/   r   r   r5   compiler   !compile_args_from_training_configtry_build_compiled_argumentsr1   _create_all_weightstrainable_variablesNotImplementedErrorAttributeError&load_optimizer_weights_from_hdf5_groupset_weights)	r7   rG   rR   r=   r<   r6   r   rH   optimizer_weight_valuess	            rB   load_model_from_hdf5r\      s=   2 
\
3
44	N"8TYY77/		(%AA
%277;;~.L788|X&!((1l$$\2L..|>LNE !?!3U\\B$56o	(	+)009		  M 	N6 ggi 5 #))/:o emm BlDD
>+ B<@B//6 
	!	N
//
-
-e.G.G
H #I"K	(
//
%
%&=
> ggi	,# $^4 	N
//MN	N  	(
// ' (	( ggi sV   CI AI %G: ?I H$ :$H!I  H!!I $II II Ic                 (
     fd} fd} fd} j                   j                  dk(  r ||      } j                   j                  dk(  r	 ||      }n  j                   j                  dv r ||      }dk(  r j                   j                  dk(  rt         j                  |      } j                   j                  dk(  r|d	   j                  }|d
d  j
                  d	   dfk7  s|d    j                  k7  rG|d	    j                  k(  r|dd
  j
                  d	   dfk(  sJ t        j                  |d	   d      |d	<   |d	   d
d
d	d
d
d
d
f   |d	<    j                   j                  dk(  r+ j                  dk(  rt        j                  |d	   d      |d	<    j                   j                  dk(  rV j                  dk(  rt        j                  |d	   d      |d	<    j                  dk(  rt        j                  |d	   d      |d	<    j                   j                  dk(  r+ j                  dk(  rt        j                  |d	   d      |d	<    j                   j                  dk(  r|t        |      dk(  rnt        j                  |d	   |d   |d   gd      }t        j                  |d   |d   |d   gd      }	t        j                  |d   |d   |d   gd      }
||	|
g} j                   j                  d k(  rt        |      d!k(  rzt        j                  |d	   |d   |d   |d   gd      }t        j                  |d   |d   |d   |d"   gd      }	t        j                  |d   |d   |d   |d#   gd      }
||	|
g} j                   j                  d$k(  rt        |      d!k(  rt        j                  |d	   |d   |d   |d   gd      }t        j                  |d   |d   |d   |d"   gd      }	t        j                  |d   |d   |d   |d#   gd      }
 j                  dk(  r,t        j                  |d      }t        j                  |	d      }	||	|
g}g d%} j                   j                  |v rt        j                   j                  d	         |d	   j                  k7  rQt        j                  |d	   d&      |d	<    j                   j                  d$k(  rt        j                  |d   d&      |d<   t         |      S )'a  Preprocess layer weights between different Keras formats.

  Converts layers weights from Keras 1 format to Keras 2 and also weights of
  CuDNN layers in Keras 2.

  Args:
      layer: Layer instance.
      weights: List of weights values (Numpy arrays).
      original_keras_version: Keras version for the weights, as a string.
      original_backend: Keras backend the weights were trained with,
          as a string.

  Returns:
      A list of weights values (Numpy arrays).
  c                     t        |       dz  }t        j                  | d|       }t        j                  | |d       }||z   S )a  Converts layers nested in `Bidirectional` wrapper.

    This function uses `preprocess_weights_for_loading()` for converting
    layers.

    Args:
        weights: List of weights values (Numpy arrays).

    Returns:
        A list of weights values (Numpy arrays).
       N)r   preprocess_weights_for_loadingforward_layerbackward_layer)r   num_weights_per_layerforward_weightsbackward_weightslayeroriginal_backendoriginal_keras_versions       rB   convert_nested_bidirectionalzDpreprocess_weights_for_loading.<locals>.convert_nested_bidirectional   sm      LA-4W%;&;< 02O 6g&;&<= 02 ---    c                 4    t        j                  |       S )a  Converts layers nested in `TimeDistributed` wrapper.

    This function uses `preprocess_weights_for_loading()` for converting nested
    layers.

    Args:
        weights: List of weights values (Numpy arrays).

    Returns:
        A list of weights values (Numpy arrays).
    )r`   rf   )r   rf   rg   rh   s    rB   convert_nested_time_distributedzGpreprocess_weights_for_loading.<locals>.convert_nested_time_distributed
  s#     *W46FH Hrj   c                    | dt        	j                         }| t        	j                        d }g }g }	j                  D ]  }t        |j                        }t        |j                        }|j                  s:t        ||d| |d| z   
      }|j                  |d|        |j                  ||d        ||d }||d } ||z   S )a  Converts layers nested in `Model` or `Sequential`.

    This function uses `preprocess_weights_for_loading()` for converting nested
    layers.

    Args:
        weights: List of weights values (Numpy arrays).

    Returns:
        A list of weights values (Numpy arrays).
    N)rf   r   rh   rg   )r   trainable_weightsr/   non_trainable_weightsr   r`   extend)r   rn   ro   new_trainable_weightsnew_non_trainable_weightssublayernum_trainable_weightsnum_non_trainable_weightspreprocessedrf   rg   rh   s            rB   convert_nested_modelz<preprocess_weights_for_loading.<locals>.convert_nested_model  s      =U%<%<!=>#C(?(?$@$AB "LL (!("<"<="%h&D&D"E			5&'=(=>*+E,EFG#9-/ 	$$\2H3H%IJ!((6K6L)MN-.C.DE 5%&!((" !#<<<rj   BidirectionalTimeDistributed)Model
Sequential
Functional1Conv1Dr   Nr_         )r_   r   r   r   Conv2Dchannels_firstConv2DTransposechannels_last)r   r   r   r_   )r_   r   r   r   Conv3D)r_   r      r   r   GRU	      axisr            LSTM   
      
ConvLSTM2D)r~   r   r   r   r   )r   r_   r   r   )	__class____name__r`   rf   shapekernel_sizefiltersnp	transposedata_formatr   concatenater   	int_shaper   _convert_rnn_weights)rf   r   rh   rg   ri   rl   rw   r   kernelrecurrent_kernelbiasconv_layerss   ` ``        rB   r`   r`      s   &.*H#=P __0*73G
__!22-g6G#HH"7+Gs"#44.
++w 68HJg 8+aje	ru((+Q/	/58u}}3L Qx5==(U12Y5;L;LQ;O;<;> .> 	> >\\'!*l;
1:aAqj)gaj8+			.	. \\'!*l;
#44			o	- \\'!*l;
			.	. \\'!*l;
8+			.	. \\'!*o>
5(	W	WQZ D2N>>QZWQZ0r;~~wqz71:wqzBL+T26)	W	 QZWQZ<2G>>QZWQZ=BH~~QZWQZ=BH+T2</	W	QZWQZ<2G>>QZWQZ=BH~~QZWQZ=BH 00 <<5&\\*:LI
+T2O+
__,q)*gaj.>.>><<
L9gaj		!	!\	1\\'!*l;
 
eW	--rj   c                   
 d d | j                   j                  }|dv r}t        |      dk(  ro|d   j                  d   }|d   j                  }d
|d|z  
z  fk(  rd	}n#||
z  fk(  rd
}nt	        dt        |      z         d
fd	}||k7  r |||d	k(        }|dv rt        |      dk(  r|d   j                  d   }|d   j                  }d
d
fd	}|d|z  
z  fk(  rd}n0|d|
z  fk(  rd}n#||
z  fk(  rd}nt	        dt        |      z         |dk(  rd}n| j                  rd}nd}||k7  r6||f}	d|	v rt	        d|	z        |dk(  r ||d      }|S |dk(  r
 ||d      }|S )aN  Converts weights for RNN layers between native and CuDNN format.

  Input kernels for each gate are transposed and converted between Fortran
  and C layout, recurrent kernels are transposed. For LSTM biases are summed/
  split in half, for GRU biases are reshaped.

  Weights can be converted in both directions between `LSTM` and`CuDNNSLTM`
  and between `CuDNNGRU` and `GRU(reset_after=True)`. Default `GRU` is not
  compatible with `CuDNNGRU`.

  For missing biases in `LSTM`/`GRU` (`use_bias=False`) no conversion is made.

  Args:
      layer: Target layer instance.
      weights: List of source weights values (input kernels, recurrent
          kernels, [biases]) (Numpy arrays).

  Returns:
      A list of converted weights values (Numpy arrays).

  Raises:
      ValueError: for incompatible GRU layer/weights or incompatible biases
  c                     t        j                  t        j                  | |      D cg c]
  } ||       c}      S c c}w )a=  Transforms kernel for each gate separately using given function.

    Args:
        kernels: Stacked array of kernels for individual gates.
        func: Function applied to kernel of each gate.
        n_gates: Number of gates (4 for LSTM, 3 for GRU).

    Returns:
        Stacked array of transformed kernels.
    )r   hstackhsplit)kernelsfuncn_gatesr>   s       rB   transform_kernelsz/_convert_rnn_weights.<locals>.transform_kernels  s0     99ryy''BC!d1gCDDCs   >c                     | rdndfd}|S )a  Makes a function that transforms input kernels from/to CuDNN format.

    It keeps the shape, but changes between the layout (Fortran/C). Eg.:

    ```
    Keras                 CuDNN
    [[0, 1, 2],  <--->  [[0, 2, 4],
     [3, 4, 5]]          [1, 3, 5]]
    ```

    It can be passed to `transform_kernels()`.

    Args:
        from_cudnn: `True` if source weights are in CuDNN format, `False`
            if they're in plain Keras format.

    Returns:
        Function that converts input kernel to the other format.
    FCc                 R    | j                   j                  | j                        S )N)order)Treshaper   )r   r   s    rB   	transformz@_convert_rnn_weights.<locals>.transpose_input.<locals>.transform  s!    XXfll%88rj   rK   )
from_cudnnr   r   s     @rB   transpose_inputz-_convert_rnn_weights.<locals>.transpose_input  s    ( C3E9 rj   )r   	CuDNNLSTMr   r   r   r_   r   r   r   zInvalid bias shape: Tc                      | d    |            } | d   d       }|r1t        j                  t        j                  | d   dd      d      }nt        j                  d| d   z  d      }|||gS )zConverts the weights between CuDNNLSTM and LSTM.

      Args:
        weights: Original weights.
        from_cudnn: Indicates whether original weights are from CuDNN layer.

      Returns:
        Updated weights compatible with LSTM.
      r   r   c                     | j                   S Nr   r>   s    rB   <lambda>zD_convert_rnn_weights.<locals>.convert_lstm_weights.<locals>.<lambda>  
    !## rj   r_   r   g      ?)r   sumsplittiler   r   r   recurrent_kernelsbiasesr   r   r   s        rB   convert_lstm_weightsz2_convert_rnn_weights.<locals>.convert_lstm_weights  s     "'!*oj.I")+g+GAJwO	QQ7a@ wqz)1-(&11rj   )r   )r   CuDNNGRUc                      | d    |            } | d   d       }t        j                  | d         j                  |rdnd      }|||gS )zConverts the weights between CuDNNGRU and GRU.

      Args:
        weights: Original weights.
        from_cudnn: Indicates whether original weights are from CuDNN layer.

      Returns:
        Updated weights compatible with GRU.
      r   r   c                     | j                   S r   r   r   s    rB   r   zC_convert_rnn_weights.<locals>.convert_gru_weights.<locals>.<lambda>"  r   rj   r_   )r_   r   r   )r   arrayr   r   s        rB   convert_gru_weightsz1_convert_rnn_weights.<locals>.convert_gru_weights  sa     "'!*oj.I")+g+GAJwOxx
#++zGrJf(&11rj   r   zGRU(reset_after=True)zGRU(reset_after=False)z%s is not compatible with %sF)T)r   r   r   r   rM   strreset_after)rf   r   target_classunits
bias_shapesourcer   r   targettypesr   r   r   s             @@@rB   r   r     s   2E6 )), **s7|q/@
 AJQE!!JGa%i')++f	)	)f-J?@@20 $W;9NOg ((S\Q->
 AJQE!!JG2" a%i')++f	57?+	+&f	)	)'f-J?@@z!f			&f'f ve	!U	*7%?@@	:	%g$? 
. ,,%g%@	.rj   c                    t        |d      }|r| j                  d      }|D cg c]&  }t        |j                        j	                  d      ( }}t        |d|       t        j                  |      }t        ||      D ]D  \  }}|j                  ||j                  |j                        }	|j                  s||	d<   @||	dd F yyc c}w )zSaves optimizer weights of a optimizer to a HDF5 group.

  Args:
      hdf5_group: HDF5 group.
      optimizer: optimizer instance.
  r   rJ   r   weight_namesdtyperK   N)getattrr.   r   namer,   save_attributes_to_hdf5_groupr   batch_get_valuezipcreate_datasetr   r   )

hdf5_groupr1   symbolic_weightsweights_groupr   r   weight_valuesr   val
param_dsets
             rB   r3   r3   C  s     Y	2++,?@M8HI1CK&&v.ILI!-N++,<=M}5 	c //
		 0 ,jYY
2
1 Is   +Cc                 T    | d   }t        |d      }|D cg c]  }||   	 c}S c c}w )zLoad optimizer weights from a HDF5 group.

  Args:
      hdf5_group: A pointer to a HDF5 group.

  Returns:
      data: List of optimizer weight names.
  rJ   r   )load_attributes_from_hdf5_group)r   r   optimizer_weight_namesweight_names       rB   rY   rY   [  s8     01-:^%8N	O-
$	OO	Os   %c           
         ddl m} t        | d|D cg c]  }|j                  j	                  d       c}       t        j
                         j	                  d      | j                  d<   t        |      j	                  d      | j                  d<   t        |d       D ]  }| j                  |j                        }t        |      }t        j                  |      }|D cg c]  }|j                  j	                  d       }}t        |d	|       t        ||      D ]D  \  }	}
|j                  |	|
j                  |
j                  
      }|
j                  s|
|d<   @|
|dd F  yc c}w c c}w )z~Saves the weights of a list of layers to a HDF5 group.

  Args:
      f: HDF5 group.
      layers: List of layer instances.
  r   )__version__layer_namesr   r   keras_versionc                     | j                   S r   )r   )xs    rB   r   z,save_weights_to_hdf5_group.<locals>.<lambda>z  s
    AFF rj   )keyr   r   rK   N)tensorflow.python.kerasr   r   r   r,   r   r-   r   sortedr.   _legacy_weightsr   r   r   r   r   )r<   r/   r   rf   gr   r   r   r   r   r   r   s               rB   r0   r0   j  s>    CGu**62GI(//7!'') /66v>!''/ f"23 e	uzz"Ae$G++G4M3:;aAFFMM&);L;!!^\B}5 	c##D#))399#EjYY
2
1 H <s   "E)""E.c           	         d| j                   v r-| j                   d   }t        |d      r|j                  d      }nd}d| j                   v r-| j                   d   }t        |d      r|j                  d      }nd}g }|D ]!  }t        |      }|s|j	                  |       # t        | d      }g }|D ]'  }	| |	   }
t        |
d      }|s|j	                  |	       ) |}t        |      t        |      k7  r;t        d	t        t        |            z   d
z   t        t        |            z   dz         g }t        |      D ]  \  }}	| |	   }
t        |
d      }|D cg c]  }t        j                  |
|          }}||   }t        |      }t        ||||      }t        |      t        |      k7  rpt        dt        |      z   dz   |j                  z   dz   |	z   dz   |j                  z   dz   t        t        |            z   dz   t        t        |            z   dz         |t        ||      z  } t        j                   |       yc c}w )zImplements topological (order-based) weight loading.

  Args:
      f: A pointer to a HDF5 group.
      layers: a list of target layers.

  Raises:
      ValueError: in case of mismatch between provided layers
          and weights file.
  r   rF   r   r}   r   Nr   r   z0You are trying to load a weight file containing z layers into a model with z layers.Layer #	 (named "z9" in the current model) was found to correspond to layer z) in the save file. However the new layer z	 expects z% weights, but the saved weights have z
 elements.)r-   rN   rF   r   appendr   r   rM   r   	enumerater   asarrayr`   r   r   r   batch_set_value)r<   r/   rh   rg   filtered_layersrf   r   r   filtered_layer_namesr   r   r   weight_value_tuplesr>   r   r   r   s                    rB   rQ   rQ     s    WW_5%x05<<VD !''wwy)*)008/ $ee$GU#$
 0=A+ (d	$A21nEL!!$'	(
 %+_--
 #%([)9%:;1247O8L4MN    ! ! ;' @ga	$A21nELCOPKRZZ+/PMPAE&u-2}46FHM
=S!122y3q6)K7%**D..045800 38**= @KK 3/01	2
 ?? 3}-./ 2>> ? ? 3/??!@" 
-. Qs   Ic                    d| j                   v r-| j                   d   }t        |d      r|j                  d      }nd}d| j                   v r-| j                   d   }t        |d      r|j                  d      }nd}t        | d      }i }|D ]:  }|j                  s|j                  |j                  g       j                  |       < g }t        |      D ]r  \  }	}
| |
   }t        |d      }|D cg c]  }t        j                  ||          }}|j                  |
g       D ]   }t        |      }t        ||||      }t        |      t        |      k7  r|rTt        j                  d	j!                  |j                        d
j!                  t        |      t        |            z          t#        dt%        |	      z   dz   |j                  z   dz   t%        t        |            z   dz   dz   t%        t        |            z   dz         t'        t        |            D ]"  }t)        j*                  ||         ||   j,                  k7  r|r\t        j                  d	j!                  |j                        dj!                  ||   j,                  ||   j,                        z          t#        dt%        |	      z   dz   |j                  z   dz   t%        ||         z   dj!                  t)        j*                  ||               z   dz   t%        ||   j,                        z   dz         |j                  ||   ||   f       % # u t)        j.                  |       yc c}w )a  Implements name-based weight loading.

  (instead of topological weight loading).

  Layers that have no matching name are skipped.

  Args:
      f: A pointer to a HDF5 group.
      layers: a list of target layers.
      skip_mismatch: Boolean, whether to skip loading of layers
          where there is a mismatch in the number of weights,
          or a mismatch in the shape of the weights.

  Raises:
      ValueError: in case of mismatch between provided layers
          and weights file and skip_match=False.
  r   rF   r   r}   r   Nr   r   z(Skipping loading of weights for layer {}z1 due to mismatch in number of weights ({} vs {}).r   r   z") expects z! weight(s), but the saved weightsz have z element(s).z% due to mismatch in shape ({} vs {}).z"), weight z has shape {}z!, but the saved weight has shape .)r-   rN   rF   r   r   
setdefaultr   r   r   r   rL   r   r`   r   r   r   formatrM   r   ranger   r   r   r   )r<   r/   skip_mismatchrh   rg   r   indexrf   r   r>   r   r   r   r   r   r   is                    rB   $load_weights_from_hdf5_group_by_namer    s   & WW_5%x05<<VD !''wwy)*)008 0=A+ % 5ezzuzz2&--e45 ;' &Nga	$A21nELCOPKRZZ+/PMP4$ !N(/4
 68HJm	]	s#34	4
// %%+VEJJ%7 ;==CV!"23S5G>II J SV+k9EJJF&'),S1A-B)CD<=?GH S/01 4BB C 	C
 S'( N!-a01]15E5K5KKOO ''-vejj'9 =<<BF 0 3 9 9 -a 0 6 6=88 9
 9s1v-{:UZZG()+./?/B+CD*11'2C2C/234 55 ?	?
 }Q/5567
 :== > > 
$
$&6q&9=;K%L
M#N!!N&NN 
-.I Qs   1M!c                    |D cg c]  }t        |      t        kD  s| }}|r#t        dt        dj                  |      fz        t	        j
                  |      }d}t	        j                  ||      }t        d |D              r.|dz  }t	        j                  ||      }t        d |D              r.|dkD  r(t        |      D ]  \  }}	|	| j                  d||fz  <    y|| j                  |<   yc c}w )a  Saves attributes (data) of the specified name into the HDF5 group.

  This method deals with an inherent problem of HDF5 file which is not
  able to store data larger than HDF5_OBJECT_HEADER_LIMIT bytes.

  Args:
      group: A pointer to a HDF5 group.
      name: A name of the attributes to save.
      data: Attributes data to store.

  Raises:
    RuntimeError: If any single attribute is too large to be saved.
  z_The following attributes cannot be saved to HDF5 file because they are larger than %d bytes: %sz, r   c              3   B   K   | ]  }|j                   t        kD    y wr   )nbytesHDF5_OBJECT_HEADER_LIMIT).0r   s     rB   	<genexpr>z0save_attributes_to_hdf5_group.<locals>.<genexpr>A  s     FAAHH//Fs   %s%dN)
r   r  RuntimeErrorjoinr   r   array_splitanyr   r-   )
groupr   datar   bad_attributesdata_npy
num_chunkschunked_datachunk_id
chunk_datas
             rB   r   r   "  s   "  $I!s1v0H'HAI.I 
 H0$))N2KLM N N ZZ(**5, 	FFF!OJ>>(J7L 	FFF !^ ), 7 :*/9ekk&D(++,: EKK- Js
   C2C2c           	         || j                   v r;| j                   |   D cg c]!  }t        |d      r|j                  d      n|# }}|S g }d}d||fz  | j                   v rg|j                  | j                   d||fz     D cg c]!  }t        |d      r|j                  d      n|# c}       |dz  }d||fz  | j                   v rg|S c c}w c c}w )aQ  Loads attributes of the specified name from the HDF5 group.

  This method deals with an inherent problem
  of HDF5 file which is not able to store
  data larger than HDF5_OBJECT_HEADER_LIMIT bytes.

  Args:
      group: A pointer to a HDF5 group.
      name: A name of the attributes to load.

  Returns:
      data: Attributes data.
  rF   r   r   r
  r   )r-   rN   rF   rp   )r  r   nr  r  s        rB   r   r   L  s     
U[[ T" $Ax0a7D  
+ DH
D(#
#u{{
2
kk;;vx(889 &a2!((6

9 	 !mh D(#
#u{{
2 
+s   &C
&Cc                     | j                   | j                  z   }t        d |D              r/t        dj	                  | j
                  j                  |            |S )a  DO NOT USE.

  For legacy reason, the layer.weights was in the order of
  [self.trainable_weights + self.non_trainable_weights], and this order was
  used for preserving the weights in h5 format. The new order of layer.weights
  are the same as layer.get_weights() which is more intuitive for user. To
  keep supporting the existing saved h5 file, this method should be used to
  save/load weights. In future version, we will delete this method and
  introduce a breaking change for h5 and stay with the new order for weights.

  Args:
    layer: a `tf.keras.Model` or `tf.keras.layers.Layer` instance.

  Returns:
    A list of variables with the order of trainable_weights, followed by
      non_trainable_weights.
  c              3   R   K   | ]  }t        |t        j                          ! y wr   )r   variables_moduleVariable)r  r   s     rB   r	  z"_legacy_weights.<locals>.<genexpr>~  s!     G!Z+445	5Gs   %'zSave or restore weights that is not an instance of `tf.Variable` is not supported in h5, use `save_format='tf'` instead. Got a model or layer {} with weights {})rn   ro   r  rW   r   r   r   )rf   r   s     rB   r   r   k  sY    $ ##e&A&AA'GwGG
	&&,fU__-E-Ew&OQ Q 
.rj   )TT)NT)NN)F)*__doc__r)   r   numpyr   r   r   r   tensorflow.python.keras.savingr   rO   r   *tensorflow.python.keras.saving.saved_modelr   +tensorflow.python.keras.utils.generic_utilsr   &tensorflow.python.keras.utils.io_utilsr	   tensorflow.python.opsr
   r  tensorflow.python.platformr   r   r   r   r  r   globalsr   rC   r\   r`   r   r3   rY   r0   rQ   r  r   r   r   rK   rj   rB   <module>r&     s     G  	  + 0 K 7 A B P ? , <" gi/1OdY| ;?48w.tdN0P>@/H #S/l'T>I  	$s   B BB