
    2Vh                     F   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  ej
                         dk(  rd dlmZ n ej
                         dk(  rd dlmZ nl ej
                         dk(  rd dlmZ nQ ej
                         dk(  rd dlmZ n6 ej
                         dk(  rd dlmZ n e d ej
                          d       eddg       G d deej.                  e
             Z! ed      dd       Z"d Z#d Z$y)     N)backend)utils)keras_export)Layer)map_saveable_variables)
saving_api)trainer)summary_utils)traceback_utils
tensorflow)TensorFlowTrainerjax)
JAXTrainertorch)TorchTrainernumpy)NumpyTraineropenvino)OpenVINOTrainerz	Backend 'z#' must implement the Trainer class.zkeras.Modelzkeras.models.Modelc                       e Zd ZdZ fdZd Zd Zed        Zej                  d        Ze
j                  dd       Ze
j                  	 	 	 	 	 	 dd       Ze
j                  dd	       Ze
j                  dd
       Ze
j                  dd       Zd Zd Zd Z	 	 	 ddZedd       Zd ZddZd Zd Zd Zd Z xZS )ModelaF  A model grouping layers into an object with training/inference features.

    There are three ways to instantiate a `Model`:

    ## With the "Functional API"

    You start from `Input`,
    you chain layer calls to specify the model's forward pass,
    and finally, you create your model from inputs and outputs:

    ```python
    inputs = keras.Input(shape=(37,))
    x = keras.layers.Dense(32, activation="relu")(inputs)
    outputs = keras.layers.Dense(5, activation="softmax")(x)
    model = keras.Model(inputs=inputs, outputs=outputs)
    ```

    Note: Only dicts, lists, and tuples of input tensors are supported. Nested
    inputs are not supported (e.g. lists of list or dicts of dict).

    A new Functional API model can also be created by using the
    intermediate tensors. This enables you to quickly extract sub-components
    of the model.

    Example:

    ```python
    inputs = keras.Input(shape=(None, None, 3))
    processed = keras.layers.RandomCrop(width=128, height=128)(inputs)
    conv = keras.layers.Conv2D(filters=32, kernel_size=3)(processed)
    pooling = keras.layers.GlobalAveragePooling2D()(conv)
    feature = keras.layers.Dense(10)(pooling)

    full_model = keras.Model(inputs, feature)
    backbone = keras.Model(processed, conv)
    activations = keras.Model(conv, feature)
    ```

    Note that the `backbone` and `activations` models are not
    created with `keras.Input` objects, but with the tensors that originate
    from `keras.Input` objects. Under the hood, the layers and weights will
    be shared across these models, so that user can train the `full_model`, and
    use `backbone` or `activations` to do feature extraction.
    The inputs and outputs of the model can be nested structures of tensors as
    well, and the created models are standard Functional API models that support
    all the existing APIs.

    ## By subclassing the `Model` class

    In that case, you should define your
    layers in `__init__()` and you should implement the model's forward pass
    in `call()`.

    ```python
    class MyModel(keras.Model):
        def __init__(self):
            super().__init__()
            self.dense1 = keras.layers.Dense(32, activation="relu")
            self.dense2 = keras.layers.Dense(5, activation="softmax")

        def call(self, inputs):
            x = self.dense1(inputs)
            return self.dense2(x)

    model = MyModel()
    ```

    If you subclass `Model`, you can optionally have
    a `training` argument (boolean) in `call()`, which you can use to specify
    a different behavior in training and inference:

    ```python
    class MyModel(keras.Model):
        def __init__(self):
            super().__init__()
            self.dense1 = keras.layers.Dense(32, activation="relu")
            self.dense2 = keras.layers.Dense(5, activation="softmax")
            self.dropout = keras.layers.Dropout(0.5)

        def call(self, inputs, training=False):
            x = self.dense1(inputs)
            x = self.dropout(x, training=training)
            return self.dense2(x)

    model = MyModel()
    ```

    Once the model is created, you can config the model with losses and metrics
    with `model.compile()`, train the model with `model.fit()`, or use the model
    to do prediction with `model.predict()`.

    ## With the `Sequential` class

    In addition, `keras.Sequential` is a special case of model where
    the model is purely a stack of single-input, single-output layers.

    ```python
    model = keras.Sequential([
        keras.Input(shape=(None, None, 3)),
        keras.layers.Conv2D(filters=32, kernel_size=3),
    ])
    ```
    c                     t        ||      r%| t        k(  rddlm}  |j                  |g|i |S t        j                  | t        |   |             S )Nr   
Functional)functional_init_argumentsr   keras.src.models.functionalr   __new__typingcastsuper)clsargskwargsr   	__class__s       F/home/dcms/DCMS/lib/python3.12/site-packages/keras/src/models/model.pyr   zModel.__new__   sM    $T62se|>%:%%jB4B6BB{{3 455    c                     t        j                  |        ddlm} t	        ||      r6t        | j                          |j                  j                  | g|i | y t        j                  | g|i | y )Nr   
functional)	Trainer__init__keras.src.modelsr)   r   inject_functional_model_classr$   r   r   )selfr"   r#   r)   s       r%   r+   zModel.__init__   sa    / %T62)$..9*J!!**4A$A&ANN41$1&1r&   c                 H    t        d| j                  j                   d      )NzModel z- does not have a `call()` method implemented.)NotImplementedErrorr$   __name__)r.   r"   r#   s      r%   callz
Model.call   s+    !T^^,,- ." "
 	
r&   c                 :    t        | j                  dd            S )NF)include_self	recursive)list_flatten_layers)r.   s    r%   layerszModel.layers   s    D((eu(MNNr&   c                     t        d      )NzU`Model.layers` attribute is reserved and should not be used. Please use another name.)AttributeError)r.   _s     r%   r8   zModel.layers   s    '
 	
r&   c           	         ||t        d| d| d      |Lt        | j                        |k  r%t        d| dt        | j                         d      | j                  |   S |P| j                  D ]  }|j                  |k(  s|c S  t        d| dt	        d	 | j                  D               d      t        d
      )ax  Retrieves a layer based on either its name (unique) or index.

        If `name` and `index` are both provided, `index` will take precedence.
        Indices are based on order of horizontal graph traversal (bottom-up).

        Args:
            name: String, name of layer.
            index: Integer, index of layer.

        Returns:
            A layer instance.
        z<Provide only a layer name or a layer index. Received: index=z, name=.z%Was asked to retrieve layer at index z but model only has z layers.zNo such layer: z. Existing layers are: c              3   4   K   | ]  }|j                     y wN)name).0layers     r%   	<genexpr>z"Model.get_layer.<locals>.<genexpr>   s     <u

<s   z:Provide either a layer name or layer index at `get_layer`.)
ValueErrorlenr8   r@   r6   )r.   r@   indexrB   s       r%   	get_layerzModel.get_layer   s     !1wtfA/  4;;5( ;E7*3t{{+;*<  {{5)) !::% L! !$'><<<=Q@  H
 	
r&   c           	      <    t        j                  | ||||||       y)aY  Prints a string summary of the network.

        Args:
            line_length: Total length of printed lines
                (e.g. set this to adapt the display to different
                terminal window sizes).
            positions: Relative or absolute positions of log elements
                in each line. If not provided, becomes
                `[0.3, 0.6, 0.70, 1.]`. Defaults to `None`.
            print_fn: Print function to use. By default, prints to `stdout`.
                If `stdout` doesn't work in your environment, change to `print`.
                It will be called on each line of the summary.
                You can set it to a custom function
                in order to capture the string summary.
            expand_nested: Whether to expand the nested models.
                Defaults to `False`.
            show_trainable: Whether to show if a layer is trainable.
                Defaults to `False`.
            layer_range: a list or tuple of 2 strings,
                which is the starting layer name and ending layer name
                (both inclusive) indicating the range of layers to be printed
                in summary. It also accepts regex patterns instead of exact
                names. In this case, the start predicate will be
                the first element that matches `layer_range[0]`
                and the end predicate will be the last element
                that matches `layer_range[1]`.
                By default `None` considers all layers of the model.

        Raises:
            ValueError: if `summary()` is called before the model is built.
        )line_length	positionsprint_fnexpand_nestedshow_trainablelayer_rangeN)r
   print_summary)r.   rI   rJ   rK   rL   rM   rN   s          r%   summaryzModel.summary   s(    R 	###')#	
r&   c                 6    t        j                  | |f||d|S )a  Saves a model as a `.keras` file.

        Note that `model.save()` is an alias for `keras.saving.save_model()`.

        The saved `.keras` file contains:

        - The model's configuration (architecture)
        - The model's weights
        - The model's optimizer's state (if any)

        Thus models can be reinstantiated in the exact same state.

        Args:
            filepath: `str` or `pathlib.Path` object.
                The path where to save the model. Must end in `.keras`
                (unless saving the model as an unzipped directory
                via `zipped=False`).
            overwrite: Whether we should overwrite any existing model at
                the target location, or instead ask the user via
                an interactive prompt.
            zipped: Whether to save the model as a zipped `.keras`
                archive (default when saving locally), or as an
                unzipped directory (default when saving on the
                Hugging Face Hub).

        Example:

        ```python
        model = keras.Sequential(
            [
                keras.layers.Dense(5, input_shape=(3,)),
                keras.layers.Softmax(),
            ],
        )
        model.save("model.keras")
        loaded_model = keras.saving.load_model("model.keras")
        x = keras.random.uniform((10, 3))
        assert np.allclose(model.predict(x), loaded_model.predict(x))
        ```
        )	overwritezipped)r   
save_model)r.   filepathrR   rS   r#   s        r%   savez
Model.save  s/    T $$(
&/
BH
 	
r&   c                 4    t        j                  | |||      S )aU	  Saves all weights to a single file or sharded files.

        By default, the weights will be saved in a single `.weights.h5` file.
        If sharding is enabled (`max_shard_size` is not `None`), the weights
        will be saved in multiple files, each with a size at most
        `max_shard_size` (in GB). Additionally, a configuration file
        `.weights.json` will contain the metadata for the sharded files.

        The saved sharded files contain:

        - `*.weights.json`: The configuration file containing 'metadata' and
            'weight_map'.
        - `*_xxxxxx.weights.h5`: The sharded files containing only the
            weights.

        Args:
            filepath: `str` or `pathlib.Path` object. Path where the weights
                will be saved.  When sharding, the filepath must end in
                `.weights.json`. If `.weights.h5` is provided, it will be
                overridden.
            overwrite: Whether to overwrite any existing weights at the target
                location or instead ask the user via an interactive prompt.
            max_shard_size: `int` or `float`. Maximum size in GB for each
                sharded file. If `None`, no sharding will be done. Defaults to
                `None`.

        Example:

        ```python
        # Instantiate a EfficientNetV2L model with about 454MB of weights.
        model = keras.applications.EfficientNetV2L(weights=None)

        # Save the weights in a single file.
        model.save_weights("model.weights.h5")

        # Save the weights in sharded files. Use `max_shard_size=0.25` means
        # each sharded file will be at most ~250MB.
        model.save_weights("model.weights.json", max_shard_size=0.25)

        # Load the weights in a new model with the same architecture.
        loaded_model = keras.applications.EfficientNetV2L(weights=None)
        loaded_model.load_weights("model.weights.h5")
        x = keras.random.uniform((1, 480, 480, 3))
        assert np.allclose(model.predict(x), loaded_model.predict(x))

        # Load the sharded weights in a new model with the same architecture.
        loaded_model = keras.applications.EfficientNetV2L(weights=None)
        loaded_model.load_weights("model.weights.json")
        x = keras.random.uniform((1, 480, 480, 3))
        assert np.allclose(model.predict(x), loaded_model.predict(x))
        ```
        )rR   max_shard_size)r   save_weights)r.   rU   rR   rX   s       r%   rY   zModel.save_weights;  s!    l &&(i
 	
r&   c                 6    t        j                  | |fd|i| y)a  Load the weights from a single file or sharded files.

        Weights are loaded based on the network's topology. This means the
        architecture should be the same as when the weights were saved. Note
        that layers that don't have weights are not taken into account in the
        topological ordering, so adding or removing layers is fine as long as
        they don't have weights.

        **Partial weight loading**

        If you have modified your model, for instance by adding a new layer
        (with weights) or by changing the shape of the weights of a layer, you
        can choose to ignore errors and continue loading by setting
        `skip_mismatch=True`. In this case any layer with mismatching weights
        will be skipped. A warning will be displayed for each skipped layer.

        **Sharding**

        When loading sharded weights, it is important to specify `filepath` that
        ends with `*.weights.json` which is used as the configuration file.
        Additionally, the sharded files `*_xxxxx.weights.h5` must be in the same
        directory as the configuration file.

        Args:
            filepath: `str` or `pathlib.Path` object. Path where the weights
                will be saved.  When sharding, the filepath must end in
                `.weights.json`.
            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.

        Example:

        ```python
        # Load the weights in a single file.
        model.load_weights("model.weights.h5")

        # Load the weights in sharded files.
        model.load_weights("model.weights.json")
        ```
        skip_mismatchN)r   load_weights)r.   rU   r[   r#   s       r%   r\   zModel.load_weightsu  s-    V 		
 (	
 		
r&   c                    ddl m} |j                  dd      }|r%t        d| j                  j
                   d|       ||vrt        d| d|       d	}| j                         D ]@  }t        |j                               }t        |      d
k(  s+	 |j                  ||       d}B |rd| _        d| _        d| _        yy# t        $ r(}t        j                  t        |             Y d}~d}~ww xY w)a  Quantize the weights of the model.

        Note that the model must be built first before calling this method.
        `quantize` will recursively call `quantize(mode)` in all layers and
        will be skipped if the layer doesn't implement the function.

        Args:
            mode: The mode of the quantization. Only 'int8' is supported at this
                time.
        r   )QUANTIZATION_MODES
type_checkTz)Unrecognized keyword arguments passed to z: z+Invalid quantization mode. Expected one of z. Received: mode=F   )r_   N)keras.src.dtype_policiesr^   poprD   r$   r1   r7   r6   rE   quantizer0   warningswarnstrtrain_functiontest_functionpredict_function)	r.   moder#   r^   r_   mode_changedrB   list_of_sublayerses	            r%   rc   zModel.quantize  s    	@ZZd3
!^^445RxA  ))##5"66GvO  ))+ 	*E $U%:%:%< =$%**NN4JN?#'L	* "&D!%D$(D! 	 + *MM#a&))*s   C	C4C//C4c                    |sy d}d|v rSt        j                  | j                        r| j                  |d         }n	 | j                  |d          d}|| _        nZd|v rVt        j                  | j                        r| j                  |d         }n	  | j                  d	i |d    d}|d   | _        |s&t        j                  d| j                   dd       y y #  Y xY w#  Y >xY w)
NFinput_shapeTshapes_dictzModel 'a  ' had a build config, but the model cannot be built automatically in `build_from_config(config)`. You should implement `def build_from_config(self, config)`, and you might also want to implement the method  that generates the config at saving time, `def get_build_config(self)`. The method `build_from_config()` is meant to create the state of the model (i.e. its variables) upon deserialization.   )
stacklevel )	r   
is_defaultbuild _build_by_run_for_single_pos_arg_build_shapes_dict_build_by_run_for_kwargsrd   re   r@   )r.   configstatuss      r%   build_from_configzModel.build_from_config  s   F"

+>>=)JJvm45!F '-D#f$

+66vm7LMDJJ7!67!F '-]&;D#MM$)) 
%( 
(  !s   C  C'  C$'C+c                 \    ddl m} |j                  |       }t        j                  |fi |S )ad  Returns a JSON string containing the network configuration.

        To load a network from a JSON save file, use
        `keras.models.model_from_json(json_string, custom_objects={...})`.

        Args:
            **kwargs: Additional keyword arguments to be passed to
                `json.dumps()`.

        Returns:
            A JSON string.
        r   serialization_lib)keras.src.savingr~   serialize_keras_objectjsondumps)r.   r#   r~   model_configs       r%   to_jsonzModel.to_json  s+     	7(??Ezz,1&11r&   c                     ddl m} ddl m} d}||vrt        d| dt	        |       d      |dk(  r || ||fd	|i| y|d
k(  r || ||fd	|i| yy)a   Export the model as an artifact for inference.

        Args:
            filepath: `str` or `pathlib.Path` object. The path to save the
                artifact.
            format: `str`. The export format. Supported values:
                `"tf_saved_model"` and `"onnx"`.  Defaults to
                `"tf_saved_model"`.
            verbose: `bool`. Whether to print a message during export. Defaults
                to `None`, which uses the default value set by different
                backends and formats.
            input_signature: Optional. Specifies the shape and dtype of the
                model inputs. Can be a structure of `keras.InputSpec`,
                `tf.TensorSpec`, `backend.KerasTensor`, or backend tensor. If
                not provided, it will be automatically computed. Defaults to
                `None`.
            **kwargs: Additional keyword arguments:
                - Specific to the JAX backend and `format="tf_saved_model"`:
                    - `is_static`: Optional `bool`. Indicates whether `fn` is
                        static. Set to `False` if `fn` involves state updates
                        (e.g., RNG seeds and counters).
                    - `jax2tf_kwargs`: Optional `dict`. Arguments for
                        `jax2tf.convert`. See the documentation for
                        [`jax2tf.convert`](
                            https://github.com/google/jax/blob/main/jax/experimental/jax2tf/README.md).
                        If `native_serialization` and `polymorphic_shapes` are
                        not provided, they will be automatically computed.

        **Note:** This feature is currently supported only with TensorFlow, JAX
        and Torch backends.

        **Note:** Be aware that the exported artifact may contain information
        from the local file system when using `format="onnx"`, `verbose=True`
        and Torch backend.

        Examples:

        Here's how to export a TensorFlow SavedModel for inference.

        ```python
        # Export the model as a TensorFlow SavedModel artifact
        model.export("path/to/location", format="tf_saved_model")

        # Load the artifact in a different process/environment
        reloaded_artifact = tf.saved_model.load("path/to/location")
        predictions = reloaded_artifact.serve(input_data)
        ```

        Here's how to export an ONNX for inference.

        ```python
        # Export the model as a ONNX artifact
        model.export("path/to/location", format="onnx")

        # Load the artifact in a different process/environment
        ort_session = onnxruntime.InferenceSession("path/to/location")
        ort_inputs = {
            k.name: v for k, v in zip(ort_session.get_inputs(), input_data)
        }
        predictions = ort_session.run(None, ort_inputs)
        ```
        r   )export_onnx)export_saved_model)tf_saved_modelonnxzUnrecognized format=z. Supported formats are: r=   r   input_signaturer   N)keras.src.exportr   r   rD   r6   )	r.   rU   formatverboser   r#   r   r   available_formatss	            r%   exportzModel.export  s    L 	176**&vh.G)*+1. 
 %% !0	
  v !0	
  r&   c                    ddl m} g d}t        fd|D              }t        j                  | j
                        }t        j                  |j
                        j                  dd  }| |t        hv xs4 |j                  dd  |k(  xs  |j                  dk(  xr |j                  dk(  }|r|rddl m
}	  |	| |	      S 	  | di S # t        $ r&}
t        d
|  d| j                   d d|
       d }
~
ww xY w)Nr   r   )r@   r8   input_layersoutput_layersc              3   &   K   | ]  }|v  
 y wr?   rs   )rA   keyry   s     r%   rC   z$Model.from_config.<locals>.<genexpr>z  s      #
!C6M#
s   r`   r"   r#   )functional_from_configcustom_objectszUnable to revive model from config. When overriding the `get_config()` method, make sure that the returned config contains all items used as arguments in the  constructor to z, which is the default behavior. You can override this default behavior by defining a `from_config(cls, config)` class method to specify how to create an instance of z# from its config.

Received config=z,

Error encountered during deserialization: rs   )r   r   allinspectgetfullargspecr+   r"   r   varargsvarkwr   	TypeErrorr1   )r!   ry   r   r   functional_config_keysis_functional_configargspecfunctional_init_argsrevivable_as_functionalr   rm   s    `         r%   from_configzModel.from_configp  s9   :"
  # #
%;#
  
 ((6&55j6I6IJOOB 
 J&& I||AB#77I6)Ggmmx.G 	 
  $; K)VN 	==  	* +. /
  #||n -##)( +==>C
A 	s   C	 		C8!C33C8c                 6    i }t        | |t                      |S )N)storevisited_saveables)r   set)r.   r   s     r%   _get_variable_mapzModel._get_variable_map  s    t5CEJr&   c                    i }| j                  | j                  |      |d<   | j                  | j                  |      |d<   | j                  | j                  j                  |      |d<   | j                  | j
                  |      |d<   |S )a3	  Retrieves tree-like structure of model variables.

        This method allows retrieval of different model variables (trainable,
        non-trainable, optimizer, and metrics). The variables are returned in a
        nested dictionary format, where the keys correspond to the variable
        names and the values are the nested representations of the variables.

        Returns:
            dict: A dictionary containing the nested representations of the
                requested variables. The keys are the variable names, and the
                values are the corresponding nested dictionaries.
            value_format: One of `"backend_tensor"`, `"numpy_array"`.
                The kind of array to return as the leaves of the nested
                    state tree.

        Example:

        ```python
        model = keras.Sequential([
            keras.Input(shape=(1,), name="my_input"),
            keras.layers.Dense(1, activation="sigmoid", name="my_dense"),
        ], name="my_sequential")
        model.compile(optimizer="adam", loss="mse", metrics=["mae"])
        model.fit(np.array([[1.0]]), np.array([[1.0]]))
        state_tree = model.get_state_tree()
        ```

        The `state_tree` dictionary returned looks like:

        ```
        {
            'metrics_variables': {
                'loss': {
                    'count': ...,
                    'total': ...,
                },
                'mean_absolute_error': {
                    'count': ...,
                    'total': ...,
                }
            },
            'trainable_variables': {
                'my_sequential': {
                    'my_dense': {
                        'bias': ...,
                        'kernel': ...,
                    }
                }
            },
            'non_trainable_variables': {},
            'optimizer_variables': {
                'adam': {
                        'iteration': ...,
                        'learning_rate': ...,
                        'my_sequential_my_dense_bias_momentum': ...,
                        'my_sequential_my_dense_bias_velocity': ...,
                        'my_sequential_my_dense_kernel_momentum': ...,
                        'my_sequential_my_dense_kernel_velocity': ...,
                    }
                }
            }
        }
        ```
        trainable_variablesnon_trainable_variablesoptimizer_variablesmetrics_variables)_create_nested_dictr   r   	optimizer	variablesr   )r.   value_formatr   s      r%   get_state_treezModel.get_state_tree  s    B 	+/+C+C$$l,
	'( 04/G/G((,0
	+, ,0+C+CNN$$l,
	'( *.)A)A""L*
	%& r&   c                    i }|D ]x  }|j                   |v rt        d|j                    d      |dk(  r|j                  ||j                   <   I|dk(  r|j                         ||j                   <   lt        d|        i }|j	                         D ]8  \  }}|j                  d      }|}	|d d D ]  }
|
|	vri |	|
<   |	|
   }	 ||	|d   <   : |S )Nz:The following variable path is found twice in the model: 'z'. `get_state_tree()` can only be called when all variable paths are unique. Make sure to give unique names to your layers (and other objects).backend_tensornumpy_arrayzkInvalid `value_format` argument. Expected one of {'numpy_array', 'backend_tensor'}. Received: value_format=/)pathrD   valuer   itemssplit)r.   r   r   	flat_dictvnested_dictr   r   partscurrent_dictparts              r%   r   zModel._create_nested_dict  s   	 	Avv" x  @@  //$%GG	!&&!.$%GGI	!&&! $$0>3 	& $??, 	,KD%JJsOE&Lcr
 2|+)+L&+D12 ',Lr#	, r&   c                    |j                         D ]  \  }}| j                  |      }|dk(  r| j                  | j                  |       9|dk(  r| j                  | j                  |       [|dk(  r'| j                  | j
                  j                  |       |dk(  r| j                  | j                  |       t        d|        y)a  Assigns values to variables of the model.

        This method takes a dictionary of nested variable values, which
        represents the state tree of the model, and assigns them to the
        corresponding variables of the model. The dictionary keys represent the
        variable names (e.g., `'trainable_variables'`, `'optimizer_variables'`),
        and the values are nested dictionaries containing the variable
        paths and their corresponding values.

        Args:
            state_tree: A dictionary representing the state tree of the model.
                The keys are the variable names, and the values are nested
                dictionaries representing the variable paths and their values.
        r   r   r   r   zUnknown variable name: N)	r   _flatten_nested_dict_assign_variable_valuesr   r   r   r   r   rD   )r.   
state_treekr   path_value_dicts        r%   set_state_treezModel.set_state_tree  s     $$& 	@DAq"77:O)),,,,o //,,00/ ++,,NN,,o )),,**O !#:1#!>??'	@r&   c                     |j                         D ]-  \  }}|D ]#  }|j                  |k(  s|j                  |       % / y r?   )r   r   assign)r.   r   r   r   r   variables         r%   r   zModel._assign_variable_valuesA  sE    *002 	+KD%% +==D(OOE*+	+r&   c                 ,    i dfd	 |       S )Nc                     | j                         D ]-  \  }}t        |t              r |||z   dz          &|||z   <   / y )Nr   )r   
isinstancedict)r   prefixr   r   _flattenr   s       r%   r   z,Model._flatten_nested_dict.<locals>._flattenJ  sJ    *002 4
UeT*UFSL3$67.3Ifsl+	4r&   ) rs   )r.   r   r   r   s     @@r%   r   zModel._flatten_nested_dictG  s    		4 	r&   )NN)NNNFFN)TN)F)r   NNr?   )r   )r1   
__module____qualname____doc__r   r+   r2   propertyr8   setterr   filter_tracebackrG   rP   rV   rY   r\   rc   r{   r   r   classmethodr   r   r   r   r   r   r   __classcell__)r$   s   @r%   r   r   "   s=   fP6
2
 O O ]]
 
 %%&
 &&
P %% 0
 &0
d %%+
 &+
Z %%7
 &7
r %%/
 &/
b&)P,\2*  _B 4 4l
N`B"@H+r&   r   zkeras.models.model_from_jsonc                 ^    ddl m} t        j                  |       }|j	                  ||      S )a_  Parses a JSON model configuration string and returns a model instance.

    Example:

    >>> model = keras.Sequential([
    ...     keras.layers.Dense(5, input_shape=(3,)),
    ...     keras.layers.Softmax()])
    >>> config = model.to_json()
    >>> loaded_model = keras.models.model_from_json(config)

    Args:
        json_string: JSON string encoding a model configuration.
        custom_objects: Optional dictionary mapping names
            (strings) to custom classes or functions to be
            considered during deserialization.

    Returns:
        A Keras model instance (uncompiled).
    r   r}   r   )r   r~   r   loadsdeserialize_keras_object)json_stringr   r~   r   s       r%   model_from_jsonr   U  s2    * 3::k*L55^ 6  r&   c                 b    t        |       dk(  xs  t        |       dk(  xr d|v xs
 d|v xr d|v S )Nrq   r`   outputsinputs)rE   )r"   r#   s     r%   r   r   r  sC    	Ta 	8IN2yF2	869#6r&   c                     ddl m} | t        u r|j                  S | t        u rt        S t        d | j                  D              | _        | j                  |        | S )z?Inject `Functional` into the hierarchy of this class if needed.r   r(   c              3   2   K   | ]  }t        |        y wr?   )r-   )rA   bases     r%   rC   z0inject_functional_model_class.<locals>.<genexpr>  s      04%d+s   )r,   r)   r   r   objecttuple	__bases__r   )r!   r)   s     r%   r-   r-   z  sV    +
e|$$$ f} 8; CM
 KKJr&   r?   )%r   r   r   rd   	keras.srcr   r   keras.src.api_exportr   keras.src.layers.layerr   !keras.src.models.variable_mappingr   r   r   keras.src.trainersr	   base_trainerkeras.src.utilsr
   r   $keras.src.backend.tensorflow.trainerr   r*   keras.src.backend.jax.trainerr   keras.src.backend.torch.trainerr   keras.src.backend.numpy.trainerr   "keras.src.backend.openvino.trainerr   RuntimeErrorr   r   r   r-   rs   r&   r%   <module>r      s         - ( D ' 6 ) +7??$ W__%CW__'!GW__'!GW__*$M

OGOO%&&IJ 
 }234oG\))5 o 5od ,- .8r&   