
    &VfX                         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 nj ej                    dk    rd dlmZ nP 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"dS )    N)backend)utils)keras_export)Layer)map_saveable_variables)
saving_api)trainer)summary_utils)traceback_utils
tensorflow)TensorFlowTrainerjax)
JAXTrainertorch)TorchTrainernumpy)NumpyTrainerz	Backend 'z#' must implement the Trainer class.zkeras.Modelzkeras.models.Modelc                   R    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 xZS )ModelaE  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        |i |S t          j        t          t                                          |                     S Nr   
functional)	functional_init_argumentsr   keras.src.modelsr   
Functionaltypingcastsuper__new__)clsargskwargsr   	__class__s       S/var/www/html/software/conda/lib/python3.11/site-packages/keras/src/models/model.pyr    zModel.__new__   si    $T622 	:se||333333(:($9&999{5%''//#"6"6777    c                     t          j        |            ddlm} t	          ||          r,t          | j                    |j        j        | g|R i | d S t          j        | g|R i | d S r   )	Trainer__init__r   r   r   inject_functional_model_classr$   r   r   )selfr"   r#   r   s       r%   r)   zModel.__init__   s    ////// %T622 	2)$.999*J!*4A$AAA&AAAAAN41$111&11111r&   c                 <    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                 J    t          |                     dd                    S )NF)include_self	recursive)list_flatten_layers)r+   s    r%   layerszModel.layers   s#    D((eu(MMNNNr&   c                      t          d          )NzU`Model.layers` attribute is reserved and should not be used. Please use another name.)AttributeError)r+   _s     r%   r5   zModel.layers   s    '
 
 	
r&   Nc           	         ||t          d| d| d          |Mt          | j                  |k    r(t          d| dt          | j                   d          | j        |         S |K| j        D ]}|j        |k    r|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.
        Nz<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   $   K   | ]}|j         V  d S N)name).0layers     r%   	<genexpr>z"Model.get_layer.<locals>.<genexpr>   s$      <<u
<<<<<<r&   z:Provide either a layer name or layer index at `get_layer`.)
ValueErrorlenr5   r=   r3   )r+   r=   indexr?   s       r%   	get_layerzModel.get_layer   sM    !1// /'+/ / /   4;5(( E  +.t{+;+;     {5)) ! !:%% LLL &@$ @ @<<<<<<<@ @ @   H
 
 	
r&   Fc           	      <    t          j        | ||||||           dS )aH  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
                name. In such case, start predicate will be the first element
                it matches to `layer_range[0]` and the end predicate will be
                the last element it matches to `layer_range[1]`.
                By default `None` which considers all layers of 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+   rF   rG   rH   rI   rJ   rK   s          r%   summaryzModel.summary   s>    P 	##')#	
 	
 	
 	
 	
 	
r&   Tc                 *    t          j        | ||fi |S )a  Saves a model as a `.keras` file.

        Args:
            filepath: `str` or `pathlib.Path` object. Path where to save
                the model. Must end in `.keras`.
            overwrite: Whether we should overwrite any existing model at
                the target location, or instead ask the user via
                an interactive prompt.
            save_format: The `save_format` argument is deprecated in Keras 3.
                Format to use, as a string. Only the `"keras"` format is
                supported at this time.

        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))
        ```

        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.
        )r   
save_model)r+   filepath	overwriter#   s       r%   savez
Model.save
  s"    N $T8YII&IIIr&   c                 0    t          j        | ||          S )ax  Saves all layer weights to a `.weights.h5` file.

        Args:
            filepath: `str` or `pathlib.Path` object.
                Path where to save the model. Must end in `.weights.h5`.
            overwrite: Whether we should overwrite any existing model
                at the target location, or instead ask the user
                via an interactive prompt.
        )rQ   )r   save_weights)r+   rP   rQ   s      r%   rT   zModel.save_weights3  s     &tXKKKKr&   c                 0    t          j        | |fd|i| dS )a  Load weights from a file saved via `save_weights()`.

        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.

        Args:
            filepath: String, path to the weights file to load.
                It can either be a `.weights.h5` file
                or a legacy `.h5` weights file.
            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.
        skip_mismatchN)r   load_weights)r+   rP   rV   r#   s       r%   rW   zModel.load_weights@  s=    6 	(	
 	
*7	
;A	
 	
 	
 	
 	
r&   c                    ddl m} | j        st          d          ||vrt          d| d|           d}|                                 D ]}t          |                                          }t          |          dk    rQ	 |                    |           d}O# t          $ r+}t          j
        t          |                     Y d	}~d	}~ww xY w|rd	| _        d	| _        d	| _        d	S d	S )
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_MODESz:The model must be built first before calling `quantize()`.z+Invalid quantization mode. Expected one of z. Received: mode=F   TN)keras.src.dtype_policiesrY   builtrA   r4   r3   rB   quantizer-   warningswarnstrtrain_functiontest_functionpredict_function)r+   moderY   mode_changedr?   list_of_sublayerses          r%   r]   zModel.quantize_  sc    	@?????z 	L   )))O#5O OHLO O   ))++ 	* 	*E $U%:%:%<%< = =$%%***NN4(((#'LL* * * *M#a&&))))))))*	 +  	)"&D!%D$(D!!!	) 	)s   B
C%!CCc                    |sd S d|v ret          j        | j                  r|                     |d                   }n(	 |                     |d                    d}n	#  d}Y nxY w|| _        nfd|v rbt          j        | j                  r|                     |d                   }n 	  | j        d	i |d          d}n	#  d}Y nxY w|d         | _        |s!t          j        d| j         dd           d S d S )
Ninput_shapeTF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_kwargsr^   r_   r=   )r+   configstatuss      r%   build_from_configzModel.build_from_config  sb    	FF""
++ 	#>>=) #JJvm4555!FF#"FFF&,D##f$$
++ #66vm7LMM#DJ77!6777!FF#"FFF&,]&;D# 	M
($) 
( 
( 
(      	 	s   A A#(B> >Cc                 \    ddl m} |                    |           }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.savingrx   serialize_keras_objectjsondumps)r+   r#   rx   model_configs       r%   to_jsonzModel.to_json  sA     	766666(??EEz,11&111r&   tf_saved_modelc                 >    ddl m} |                    | |           dS )a  Create a TF SavedModel artifact for inference.

        **Note:** This can currently only be used with
        the TensorFlow or JAX backends.

        This method lets you export a model to a lightweight SavedModel artifact
        that contains the model's forward pass only (its `call()` method)
        and can be served via e.g. TF-Serving. The forward pass is registered
        under the name `serve()` (see example below).

        The original code of the model (including any custom layers you may
        have used) is *no longer* necessary to reload the artifact -- it is
        entirely standalone.

        Args:
            filepath: `str` or `pathlib.Path` object. Path where to save
                the artifact.

        Example:

        ```python
        # Create the artifact
        model.export("path/to/location")

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

        If you would like to customize your serving endpoints, you can
        use the lower-level `keras.export.ExportArchive` class. The
        `export()` method relies on `ExportArchive` internally.
        r   )
export_libN)keras.src.exportr   export_model)r+   rP   formatr   s       r%   exportzModel.export  s3    D 	0/////h/////r&   c                    ddl m} g d}t          fd|D                       }t          j        | j                  }t          j        |j                  j        dd          }| |t          hv p(|j        dd          |k    p|j        dk    o
|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=   r5   input_layersoutput_layersc              3       K   | ]}|v V  	d S r<   rm   )r>   keyrs   s     r%   r@   z$Model.from_config.<locals>.<genexpr>  s8       #
 #
!C6M#
 #
 #
 #
 #
 #
r&   rZ   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: rm   )keras.src.models.functionalr   allinspectgetfullargspecr)   r"   r   varargsvarkwr   	TypeErrorr.   )r!   rs   r   r   functional_config_keysis_functional_configargspecfunctional_init_argsrevivable_as_functionalr   rg   s    `         r%   from_configzModel.from_config  s   ::::::"
 "
 "
  # #
 #
 #
 #
%;#
 #
 #
  
  
 (66&5j6IJJOBB 
 J&& I|ABB#77I6)Ggmx.G 	 
   	$; 	 KJJJJJ))VN   	3====  	 	 	
A +.
A 
A  #|
A 
A $*
A 
A >?
A 
A  	s   3B; ;
C* C%%C*c                 F    i }t          | |t                                 |S )N)storevisited_saveables)r   set)r+   r   s     r%   _get_variable_mapzModel._get_variable_map!  s%    t5CEEJJJJr&   )NN)NNNFFN)T)F)r   r<   )r.   
__module____qualname____doc__r    r)   r/   propertyr5   setterr   filter_tracebackrD   rM   rR   rT   rW   r]   ru   r~   r   classmethodr   r   __classcell__)r$   s   @r%   r   r       s       f fP8 8 8 8 8
2 
2 
2
 
 
 O O XO ]
 
 ]
 %&
 &
 &
 &%&
P % /
 /
 /
 &%/
b %&J &J &J &%&JP %
L 
L 
L &%
L %
 
 
 &%
<$) $) $)L+ + +Z2 2 2$$0 $0 $0 $0L 4 4 4 [4l      r&   r   zkeras.models.model_from_jsonc                 d    ddl m} t          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   rw   r   )ry   rx   r{   loadsdeserialize_keras_object)json_stringr   rx   r}   s       r%   model_from_jsonr   '  sG    * 322222:k**L55^ 6   r&   c                 f    t          |           dk    pt          |           dk    od|v pd|v od|v S )Nrk   rZ   outputsinputs)rB   )r"   r#   s     r%   r   r   D  sG    	Ta 	8IIN2yF2	869#6r&   c                     ddl m} | t          k    r|j        S | t          k    rt          S t          d | j        D                       | _        |                     |            | S )z?Inject `Functional` into the hierarchy of this class if needed.r   r   c              3   4   K   | ]}t          |          V  d S r<   )r*   )r>   bases     r%   r@   z0inject_functional_model_class.<locals>.<genexpr>W  s<        04%d++     r&   )r   r   r   r   objecttuple	__bases__r    )r!   r   s     r%   r*   r*   L  s~    ++++++
e||$$ f}}  8;    CM
 KKJr&   r<   )#r   r{   r   r^   	keras.srcr   r   keras.src.api_exportr   keras.src.layers.layerr   !keras.src.models.variable_mappingr   ry   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   RuntimeErrorr   r   r   r*   rm   r&   r%   <module>r      sZ                   - - - - - - ( ( ( ( ( ( D D D D D D ' ' ' ' ' ' 6 6 6 6 6 6 ) ) ) ) ) ) + + + + + +7?$$       W_%CCCCCCCW_'!!GGGGGGGW_'!!GGGGGGG
,JOGO%%JJJ  
 }2344C C C C CG\)5 C C 54CL ,--   .-8      r&   