
    2VhMX                        d dl 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ZdZddZddZd Zd Zd Zd Zd Z	 ddZddZd Z d Z!d Z"d Z#y# e$ r dZY 8w xY w)    N)logging)backend)
optimizers)global_state)
json_utils)saving_options)saving_utils)object_registration)io_utilsi   c                 :   t         t        d      t        |t         j                        s|s7t        j
                  j                  |      rt        j                  |      }|sy t        j
                  j                  |      }|r6t        j
                  j                  |      st	        j                  |d       t        j                  |d      }d}n|}d}	 t        j                  d      5  t        j                  | |      }|j!                         D ]q  \  }	}
t        |
t"        t$        t&        f      rBt)        j*                  |
t,        j.                        j1                  d	      |j2                  |	<   c|
|j2                  |	<   s |j5                  d
      }t7        ||        |r"t9        | d      rt;        || j<                         d d d        |j?                          |r|jA                          y y # 1 sw Y   -xY w# |r|jA                          w w xY w)NzD`save_model()` using h5 format requires h5py. Could not import h5py.T)exist_okwmodeFuse_legacy_config)defaultutf8model_weights	optimizer)!h5pyImportError
isinstanceFileospathisfiler   ask_to_proceed_with_overwritedirnameexistsmakedirsr   keras_option_scoper	   model_metadataitemsdictlisttuplejsondumpsr   get_json_typeencodeattrscreate_groupsave_weights_to_hdf5_grouphasattr$save_optimizer_weights_to_hdf5_groupr   flushclose)modelfilepath	overwriteinclude_optimizerproceeddirpathfopened_new_filer#   kvmodel_weights_groups               X/home/dcms/DCMS/lib/python3.12/site-packages/keras/src/legacy/saving/legacy_h5_format.pysave_model_to_hdf5r?      s   |
 	

 h		*RWW^^H5<<XFG''//(+277>>'2KK$/IIhS)..F 	I)88(N ',,. #1a$e!45!%:#;#;"fVn GGAJ "#AGGAJ# #$.."A&':EB !WUK%@4QH%	I( 	
	GGI -	I 	I, GGI s%   H 1CG9H 9H>H Hc                    t         t        d      |si }t        j                  }t	        j
                  di       }i |||}t        | t         j                         }|rt        j                  | d      }n| }d}	 |j                  j                  d      }|t        d|  d      t        |d	      r|j                  d
      }t        j                  |      }t        j                  d      5  t!        j"                  ||      }t%        |d   |       ddd       |rO|j                  j                  d      }	t        |	d	      r|	j                  d
      }	|	*t'        j(                  d       ||r|j+                          S S t        j                  |	      }	 |j,                  di t!        j.                  |	|       t!        j0                  |       d|v r	 t        |j2                  t4        j6                        r&|j2                  j9                  |j:                         n%|j2                  j=                  |j:                         tC        |      }
	 |j2                  jE                  |
       |r|j+                          |S # 1 sw Y   pxY w# t>        t@        f$ r t'        j(                  d       Y nw xY w# t        $ r t'        j(                  d       Y kw xY w# |r|j+                          w w xY w)ax  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.
    NzD`load_model()` using h5 format requires h5py. Could not import h5py.custom_objects_scope_dictrr   model_configz%No model config found in the file at .decodezutf-8Tr   )custom_objectsr   training_configzgNo training configuration found in the save file, so the model was *not* compiled. Compile it manually.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
   GLOBAL_CUSTOM_OBJECTSr   get_global_attributer   r   r,   get
ValueErrorr/   rE   r   r   r"   r	   model_from_configload_weights_from_hdf5_groupr   warningr2   compile!compile_args_from_training_configtry_build_compiled_argumentsr   r   	Optimizerbuild_trainable_variables_create_all_weightsNotImplementedErrorAttributeError&load_optimizer_weights_from_hdf5_groupset_weights)r4   rF   rQ   gcotlcor:   r9   r3   rC   rG   optimizer_weight_valuess              r>   load_model_from_hdf5r_   L   s   2 |
 	

 

3
3C,,-H"MD66#66N$Xtyy99OIIhS)EGww{{>27zC  <*'..w7L!((6..F 	D 22^E
 )?);UC	D ggkk*;<O1"1"8"8"A&I R GGI Q )//@O EMM @@#^
 55e< #a'!%//:3G3GH--e.H.HI;;!66 ;1= (OO//0GH GGIL{	D 	DL ,^< OO; " OO% GGI sp   >A4K" 2'JAK" AK" A/J K" J> JK" $J;8K" :J;;K" >KK" KK" "K7c           
      t   ddl m} t        | dj                  D cg c]  }|j                  j                  d       c}       t        j                         j                  d      | j                  d<   t        |      j                  d      | j                  d<   t        j                  d       D ]4  }| j                  |j                        }t        |      }t        ||       6 t        fd	j                  j                  z   D              }| j                  d
      }t        ||       yc c}w )z|Saves the weights of a list of layers to a HDF5 group.

    Args:
        f: HDF5 group.
        model: Model instance.
    r   )__version__layer_namesr   r   keras_versionc                     | j                   S Nname)xs    r>   <lambda>z,save_weights_to_hdf5_group.<locals>.<lambda>   s
    AFF     )keyc              3   >   K   | ]  }|j                   v r|  y wre   weights.0r<   r3   s     r>   	<genexpr>z-save_weights_to_hdf5_group.<locals>.<genexpr>   s%       	
   top_level_model_weightsN)	keras.srcra   save_attributes_to_hdf5_grouplayersrg   r+   r   r,   strsortedr-   _legacy_weights!save_subset_weights_to_hdf5_groupr&   rV   _non_trainable_variables)r9   r3   rc   layergrn   s    `    r>   r.   r.      s    7!	=%,,O5::,,V4O !*11&9AGGI"=188@AGGO *:; 6NN5::&!%()!W56  ++e.L.LL G
 	
01A%a1# Ps   "D5c                 ~   |D cg c]  }t        j                  |       }}|D cg c]&  }t        |j                        j	                  d      ( }}t        | d|       t        ||      D ]D  \  }}| j                  ||j                  |j                        }|j                  s||d<   @||dd F yc c}w c c}w )zSave top-level weights of a model to a HDF5 group.

    Args:
        f: HDF5 group.
        weights: List of weight variables.
    r   weight_namesdtyperI   N)
r   convert_to_numpyrw   r   r+   ru   zipcreate_datasetshaper   )r9   rn   r   weight_valuesr   rg   val
param_dsets           r>   rz   rz      s     ;BBQW--a0BMB8?@1CK&&v.@L@!!^\B}5  	c%%dCIISYY%G
yy JrNJqM  C@s
   B5+B:c                    t        |t        j                        r|j                  }nt	        |d      }|r| j                  d      }|D cg c]&  }t        |j                        j                  d      ( }}t        |d|       |D cg c]  }t        j                  |       }}t        ||      D ]D  \  }}|j                  ||j                  |j                        }	|j                  s||	d<   @||	dd F yyc c}w c c}w )zSaves optimizer weights of a optimizer to a HDF5 group.

    Args:
        hdf5_group: HDF5 group.
        optimizer: optimizer instance.
    rn   rH   r   r   r   rI   N)r   r   rT   	variablesgetattrr-   rw   r   r+   ru   r   r   r   r   r   r   )

hdf5_groupr   symbolic_weightsweights_groupr   r   r   rg   r   r   s
             r>   r0   r0      s     )Z112$.."9i8"//0CD<LMqAFF**62MM%><	
 ?OO11!4OO\=9 	$ID#&55ciisyy 6 J 99!$
2 #
1	$ M Ps   +C<	Dc                    |D cg c]  }t        |      t        kD  s| }}|rt        dt         d|       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.
    zSThe following attributes cannot be saved to HDF5 file because they are larger than z bytes:    c              3   B   K   | ]  }|j                   t        kD    y wre   )nbytesHDF5_OBJECT_HEADER_LIMIT)rp   rh   s     r>   rq   z0save_attributes_to_hdf5_group.<locals>.<genexpr>3  s     Haahh11Hs   z%s%dN)	lenr   RuntimeErrornpasarrayarray_splitany	enumerater,   )
grouprg   datarh   bad_attributesdata_npy
num_chunkschunked_datachunk_id
chunk_datas
             r>   ru   ru     s    " "&KAQ2J)JaKNK $$<#= >$%'
 	
 zz$HJ>>(J7L H<H
Ha
~~h
; H<H
H A~$-l$; 	@ Hj5?EKK$!112	@ !D1 Ls
   C$C$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 }j                  D ]!  }t	        |      }|s|j                  |       # t        | d      }g }|D ]'  }	| |	   }
t        |
d      }|s|j                  |	       ) |}t        |      t        |      k7  r$t        d	t        |       d
t        |       d      t        |      D ]  \  }}	| |	   }
||   }t	        |      }t        |
      }t        |      t        |      k7  r7t        d| d|j                   d|	 dt        |       dt        |       d      t        |||d| d|j                   d        d| v rt        fdj                  j                  z   D              }t        | d         }t        |      t        |      k7  r$t        dt        |       dt        |       d      t        ||d       yy)zImplements topological (order-based) weight loading.

    Args:
        f: A pointer to a HDF5 group.
        model: Model instance.

    Raises:
        ValueError: in case of mismatch between provided layers
            and weights file.
    rc   rE   r   1r   Nrb   r   zDLayer count mismatch when loading weights from file. Model expected z layers, found z saved layers.!Weight count mismatch for layer # (named z in the current model, z" in the save file). Layer expects  weight(s). Received  saved weight(s)layer #)rf   rs   c              3   >   K   | ]  }|j                   v r|  y wre   rm   ro   s     r>   rq   z/load_weights_from_hdf5_group.<locals>.<genexpr>  s'       
 EMM!  
rr   zZWeight count mismatch for top-level weights when loading weights from file. Model expects  top-level weight(s). Received  saved top-level weight(s)top-level model)r,   r/   rE   rv   ry   appendload_attributes_from_hdf5_groupr   rM   r   #load_subset_weights_from_hdf5_grouprg   _set_weightsr&   rV   r{   )r9   r3   original_keras_versionoriginal_backendfiltered_layersr|   rn   rb   filtered_layer_namesrg   r}   r   r;   r   r   s    `             r>   rO   rO   >  s    !''!!"!9)84%;%B%B6%J"!$AGG779-#X./66v>O *!%(""5)*
 2!]CK .dG6q.I ''-	.
 'K
;3//!/23?; 0
 	
 [) 
4dG"*51;A>}%5!663A3huzzl K&&*V ,!!$%5!6 77L}%&&68  	1#Xejj\3		

& !A%  
 //%2P2PP 
 
 <'(
 }%5!66!!$%5!6 7 8.//IK  	"		
# &rj   c                    t        |      D ]  \  }}||   j                  }|j                  }||k7  rW|r1t        j                  d| d||   j                   d| d| d       Yt        d| d||   j                   d| d|       ||   j                  |        t        | d	      r|r| j                          y
y
y
)a2  Safely set weights into a model or a layer.

    Args:
        instance: Model or layer instance,
        symbolic_weights: symbolic tensors representing
                        the weights of the variables to load,
        weight_values: values of the weights to load,
        skip_mismatch: Boolean, whether to skip loading of weights
            where there is a mismatch in the shape of the weights,
        name: name used to identify the group.

    Raises:
        ValueError: in case of mismatch between provided
            model/layer and weights.
    zSkipping loading weights for z$due to mismatch in shape for weight z. Weight expects shape z#. Received saved weight with shape    
stacklevelzShape mismatch in zfor weight finalize_stateN)	r   r   warningswarnr   rM   assignr/   r   )	instancer   r   rg   skip_mismatchiweight_valueexpected_shapereceived_shapes	            r>   r   r     s   $ %]3 1<)!,22%++^+3D6.q1667 8,,:+; <""0!13  ! $TF.q1667 8((6'7 8,-	/  	""<0-10 x)*/?! 0@*rj   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 }|j                  D ]:  }|j
                  s|j                  |j
                  g       j                  |       < t        |      D ]  \  }}	| |	   }
t        |
      }|j                  |	g       D ]  }t        |      }t        |      t        |      k7  rw|rAt        j                  d| d	|j
                   d
t        |       dt        |       d	d       ht        d| d	|j
                   dt        |       dt        |       d	      t!        ||||d| d	|j
                   d         d| v r|j"                  |j$                  z   }t        | d         }t        |      t        |      k7  rW|r1t        j                  dt        |       dt        |       dd       yt        dt        |       dt        |       d      t!        ||||d       yy)a  Implements name-based weight loading (instead of topological loading).

    Layers that have no matching name are skipped.

    Args:
        f: A pointer to a HDF5 group.
        model: Model instance.
        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.
    rc   rE   r   r   r   Nrb   z'Skipping loading of weights for layer #r   z6) due to mismatch in number of weights. Layer expects r   r   r   r   r   z). Layer expects r   r   )r   rg   rs   zaSkipping loading top-level weights for model due to mismatch in number of weights. Model expects r   r   zDWeight count mismatch for top-level weights of model. Model expects r   )r,   r/   rE   r   rv   rg   
setdefaultr   r   r   rL   ry   r   r   r   rM   r   rV   r{   )r9   r3   r   r   r   rb   indexr|   r;   rg   r}   r   r   s                r>   $load_weights_from_hdf5_group_by_namer     s     !''!!"!9)84%;%B%B6%J"!$AGG779-#X./66v> 2!]CK E ;::UZZ,33E:; [) 4dG;A>YYtR( 	E.u5=!S)9%:: MMA!H ::, ')),-=)>(? @$$'$6#77GI $%  7s ;#jj\ *%%()9%:$; <  #M 233CE   +qc%**Q7'	< !A%&&)G)GG 	 <'(
 }%5!66%%()9%:$; <  #M 233M	O
  ! !%%()9%:$; <  #M 233MO   +&5 &rj   c                 p    t        | d      }|D cg c]  }t        j                  | |          c}S c c}w )a	  Load layer weights of a model from hdf5.

    Args:
        f: A pointer to a HDF5 group.

    Returns:
        List of NumPy arrays of the weight values.

    Raises:
        ValueError: in case of mismatch between provided model
            and weights file.
    r   )r   r   r   )r9   r   weight_names      r>   r   r   ,  s1     31nEL:FG;BJJq~&GGGs   3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.
    rH   r   )r   )r   r   optimizer_weight_namesr   s       r>   rZ   rZ   =  sD     23M<~ 7M'2k"  s   %c           	         || j                   v r;| j                   |   D cg c]!  }t        |d      r|j                  d      n|# }}|S g }d}| | | j                   v re|j                  | j                   | |    D cg c]!  }t        |d      r|j                  d      n|# c}       |dz  }| | | j                   v re|S c c}w c c}w )ac  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.
    rE   r   r   r   )r,   r/   rE   extend)r   rg   nr   r   s        r>   r   r   O  s     u{{ [[&
 !(8 4AHHV!;
 
 K xj!U[[0KK #[[D6()<= )08(<AHHV$!C MH xj!U[[0 K
s   &C &Cc                 4    | j                   | j                  z   S )a3  Legacy weight order converter.

    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.

    Args:
        layer: a `Model` or `Layer` instance.

    Returns:
        A list of variables with the legacy weight order.
    )trainable_weightsnon_trainable_weights)r|   s    r>   ry   ry   p  s      ""U%@%@@@rj   )TT)NT)F)$r(   r   r   numpyr   abslr   rt   r   r   keras.src.backend.commonr   keras.src.legacy.savingr   r   r	   keras.src.savingr
   keras.src.utilsr   r   r   r   r?   r_   r.   rz   r0   ru   rO   r   r   r   rZ   r   ry   rI   rj   r>   <module>r      s     	       1 . 2 0 0 $
 ! /dup2< &$:)!XV
t DI+"\dNH"$BA{  Ds   A; ;BB