
    ij                     v   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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)Callable)backend)utils)keras_export)Layer)map_saveable_variables)awq_quantize)gptq_quantize)should_quantize_layer)
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dZ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       k/var/www/html/emotional.easysim.app/public_html/venv/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__)r2   r&   r'   s      r)   callz
Model.call   s+    !T^^,,- ." "
 	
r*   c                 :    t        | j                  dd            S )NF)include_self	recursive)list_flatten_layers)r2   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)r2   _s     r)   r<   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lenr<   rD   r:   )r2   rD   indexrF   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)r2   rM   rN   rO   rP   rQ   rR   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)r2   filepathrV   rW   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))
        ```
        )rV   max_shard_size)r   save_weights)r2   rY   rV   r\   s       r)   r]   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)r2   rY   r_   r'   s       r)   r`   zModel.load_weightsy  s-    V 		
 (	
 		
r*   c                      ~y)a/  Returns the quantization structure for the model.

        This method is intended to be overridden by model authors to provide
        topology information required for structure-aware quantization modes
        like 'gptq'.

        Args:
            mode: The quantization mode.

        Returns:
            A dictionary describing the topology, e.g.:
            `{'pre_block_layers': [list], 'sequential_blocks': [list]}`
            or `None` if the mode does not require structure or is not
            supported. `'pre_block_layers'` is a list of layers that
            the inputs should be passed through, before being passed to
            the sequential blocks. For example, inputs to an LLM must
            first be passed through an embedding layer, followed by
            the transformer.
        N )r2   modes     r)    get_quantization_layer_structurez&Model.get_quantization_layer_structure  s
    ( r*   c                 6   |j                  dd      }|r%t        d| j                  j                   d|       |7t	        |t
        t        t        t        f      st        dt        |             d}| j                         D ]L  }t        ||      st        t        |j                                     dk(  s6	 |j                  |||	       d}N |d
v rW|j$                  }	|	| j'                  |      }	|	t        d|d      |dk(  rt)        ||	|       n|dk(  rt+        ||	|       |r)d| _        d| _        d| _         | j2                  |fi | yy# t        $ r)}t        j                   t        |             Y d}~d}~wt"        $ r Y 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(...)` in all layers and
        will be skipped if the layer doesn't implement the function.

        This method can be called by passing a `mode` string, which uses the
        default configuration for that mode. Alternatively, a `config` object
        can be passed to customize the behavior of the quantization (e.g. to
        use specific quantizers for weights or activations).

        Args:
            mode: The mode of the quantization. Supported modes are:
                `"int8"`, `"int4"`, `"float8"`, `"gptq"`. This is
                optional if `config` is provided.
            config: The configuration object specifying additional
                quantization options. This argument allows to configure
                the weight and activation quantizers. be an instance of
                `keras.quantizers.QuantizationConfig`.
            filters: Optional filters to apply to the quantization. Can be a
                regex string, a list of regex strings, or a callable. Only the
                layers which match the filter conditions will be quantized.
            **kwargs: Additional keyword arguments.

        Example:

        Quantize a model to int8 with default configuration:

        ```python
        # Build the model
        model = keras.Sequential([
            keras.Input(shape=(10,)),
            keras.layers.Dense(10),
        ])
        model.build((None, 10))

        # Quantize with default int8 config
        model.quantize("int8")
        ```

        Quantize a model to int8 with a custom configuration:

        ```python
        from keras.quantizers import Int8QuantizationConfig
        from keras.quantizers import AbsMaxQuantizer

        # Build the model
        model = keras.Sequential([
            keras.Input(shape=(10,)),
            keras.layers.Dense(10),
        ])
        model.build((None, 10))

        # Create a custom config
        config = Int8QuantizationConfig(
            weight_quantizer=AbsMaxQuantizer(
                axis=0,
                value_range=(-127, 127)
            ),
            activation_quantizer=AbsMaxQuantizer(
                axis=-1,
                value_range=(-127, 127)
            ),
        )

        # Quantize with custom config
        model.quantize(config=config)
        ```
        
type_checkTz)Unrecognized keyword arguments passed to z: NzaThe `filters` argument must be a regex string, a list of regex strings, or a callable. Received: F   )rf   config)gptqawqz	For mode=z, a valid quantization structure must be provided either via `config.quantization_layer_structure` or by overriding `model.get_quantization_layer_structure(mode)`. The structure should be a dictionary with keys 'pre_block_layers' and 'sequential_blocks'.ri   )filtersrj   )poprH   r(   r5   
isinstancestrr   r:   tupletyper;   r   rI   quantizer4   warningswarnr>   quantization_layer_structurerd   r
   r	   train_functiontest_functionpredict_function_post_quantize)
r2   rc   rh   rk   r'   rf   graph_modifiedrF   e	structures
             r)   rq   zModel.quantize  s   N ZZd3
!^^445RxA 
 gXtU'CD ?G}o'  ))+ 	E(84--/01Q6NN4JvNN%)N	 ?" ;;I   AA$G	   4' "B B  v~fiAVY@ "&D!%D$(D!D//	 = + *MM#a&))% s   <E	F$FFFc                 ~    t        j                          dk(  r&| j                         D ]  }|j                           y y )Nr   )r   r;   _track_variables)r2   rc   r'   rF   s       r)   rx   zModel._post_quantizeF  s<    ??' --/ )&&()	 (r*   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.   )
stacklevelrb   )	r   
is_defaultbuild _build_by_run_for_single_pos_arg_build_shapes_dict_build_by_run_for_kwargsrr   rs   rD   )r2   rh   statuss      r)   build_from_configzModel.build_from_configN  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)r2   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dl m} ddl m}	 ddl m}
 d}||vrt        d| d	t        |       d
      |dk(  r!t        j                         dvrt        d      |dk(  r"t        j                         dk7  rt        d      |dk(  r |	| ||fd|i| y|dk(  r || ||fd|i| y|dk(  r || ||fd|i| y|dk(  r || |f||d| y|dk(  r |
| |f||d| 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"`, `"onnx"`, `"openvino"`, `"litert"`,
                and `"torch"`. 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`.
                Note: With `format="litert"` and the PyTorch backend, dynamic
                input shapes are not supported. Any dynamic dimensions (i.e.,
                `None` in input shapes) will be automatically replaced with `1`
                during export, which may cause runtime failures for other
                shapes. You must explicitly pass a fixed static
                `input_signature` matching your maximum runtime shape.
            **kwargs: Additional keyword arguments.
                - `is_static`: Optional `bool`. Specific to the JAX backend and
                    `format="tf_saved_model"`. Indicates whether `fn` is static.
                    Set to `False` if `fn` involves state updates (e.g., RNG
                    seeds and counters).
                - `jax2tf_kwargs`: Optional `dict`. Specific to the JAX backend
                    and `format="tf_saved_model"`. 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.
                - `opset_version`: Optional `int`. Specific to `format="onnx"`.
                    An integer value that specifies the ONNX opset version.
                - LiteRT-specific options: Optional keyword arguments specific
                    to `format="litert"`. These are passed directly to the
                    TensorFlow Lite converter on the TensorFlow backend and
                    include options like `optimizations`,
                    `representative_dataset`, `experimental_new_quantizer`,
                    `allow_custom_ops`, `enable_select_tf_ops`, etc. On the
                    PyTorch backend, LiteRT export accepts `optimizations`
                    plus the installed `litert_torch.convert()` keyword
                    arguments such as `strict_export`, `dynamic_shapes` (note
                    that standard ops do not support dynamic shapes, as noted
                    below), `lightweight_conversion`, `enable_x64`,
                    `runtime_constant_folding`, and `quant_config`.
                - PyTorch export options: Optional keyword arguments specific
                    to `format="torch"`. These are passed directly to
                    `torch.export.export` and include `strict`,
                    `dynamic_shapes`,
                    `prefer_deferred_runtime_asserts_over_guards`, and
                    `preserve_module_call_signature`.

        **Note on LiteRT (TFLite) Export with PyTorch Backend:**
        With the PyTorch backend, LiteRT export (`format="litert"`) does not
        support dynamic input shapes. If no static signature is provided,
        any dynamic dimensions (represented as `None`) are automatically
        replaced with `1` during export. This can lead to runtime failures
        for other shapes. You must explicitly specify a fixed static
        `input_signature` (matching your maximum runtime dimensions) and pad
        your inputs to this static shape at runtime.

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

        Here's how to export a LiteRT (TFLite) for inference.

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

        # Load the artifact in a different process/environment
        interpreter = tf.lite.Interpreter(model_path="path/to/location")
        interpreter.allocate_tensors()
        interpreter.set_tensor(
            interpreter.get_input_details()[0]['index'], input_data
        )
        interpreter.invoke()
        output_data = interpreter.get_tensor(
            interpreter.get_output_details()[0]['index']
        )
        ```

        Here's how to export a PyTorch ExportedProgram for inference.

        ```python
        # Export the model as a PyTorch ExportedProgram artifact
        model.export("path/to/model.pt2", format="torch")

        # Load the artifact in a different process/environment
        import torch
        loaded_program = torch.export.load("path/to/model.pt2")
        predictions = loaded_program.module()(input_tensor)
        ```
        r   )export_litert)export_onnx)export_openvino)export_saved_model)export_torch)tf_saved_modelonnxr   litertr   zUnrecognized format=z. Supported formats are: rA   r   )r   r   z5LiteRT export requires TensorFlow or PyTorch backend.r   z&Torch export requires PyTorch backend.r   input_signaturer   r   )verboser   N)	keras.src.exportr   r   r   r   r   rH   r:   r   )r2   rY   formatr   r   r'   r   r   r   r   r   available_formatss               r)   exportzModel.export  s   P 	30471
 **&vh.G)*+1.  X'//"3 <
 #
 G 
 W!2g!=EFF%% !0	
  v !0	
  z! !0	
  x   /	
  w   /	
  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   )rD   r<   input_layersoutput_layersc              3   &   K   | ]  }|v  
 y wrC   rb   )rE   keyrh   s     r)   rG   z$Model.from_config.<locals>.<genexpr>j  s      #
!C6M#
s   rg   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: rb   )r    r   allinspectgetfullargspecr/   r&   r   varargsvarkwr   	TypeErrorr5   )r%   rh   r   r   functional_config_keysis_functional_configargspecfunctional_init_argsrevivable_as_functionalr   rz   s    `         r)   from_configzModel.from_config`  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)r2   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   )r2   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=/)pathrH   valuer   itemssplit)r2   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(  rAt        | d      sm| j                  z| j                  | j                  j                  |       |dk(  r7t        | d      s| j                  s| 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   Nr   zUnknown variable name: )
r   _flatten_nested_dict_assign_variable_valuesr   r   hasattrr   r   r   rH   )r2   
state_treekr   path_value_dicts        r)   set_state_treezModel.set_state_tree  s     $$& 	@DAq"77:O)),,,,o //,,00/ ++4-$..2L0000/ ))D"56..00.. !#:1#!>??1	@r*   c                     |j                         D ]-  \  }}|D ]#  }|j                  |k(  s|j                  |       % / y rC   )r   r   assign)r2   r   r   r   r   variables         r)   r   zModel._assign_variable_values6  sE    *002 	+KD%% +==D(OOE*+	+r*   c                 ,    i dfd	 |       S )Nc                     | j                         D ]-  \  }}t        |t              r || | d       %|| | <   / y )Nr   )r   rm   dict)r   prefixr   r   _flattenr   s       r)   r   z,Model._flatten_nested_dict.<locals>._flatten?  sQ    *002 8
UeT*Uvhse1$5627I./	8r*   ) rb   )r2   r   r   r   s     @@r)   r   zModel._flatten_nested_dict<  s    		8 	r*   )NN)NNNFFN)TN)FrC   )NNN)r   NN)r   ) r5   
__module____qualname____doc__r!   r/   r6   propertyr<   setterr   filter_tracebackrK   rT   rZ   r]   r`   rd   rq   rx   r   r   r   classmethodr   r   r   r   r   r   r   __classcell__)r(   s   @r)   r   r   &   sH   fP6
2
 O O ]]
 
 %%&
 &&
P %% 0
 &0
d %%+
 &+
Z %%7
 &7
r %%/
 &/
b.B0H),\2*  Pd 4 4l
N`B'@R+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   J  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 )Nr   rg   outputsinputs)rI   )r&   r'   s     r)   r   r   g  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rC   )r1   )rE   bases     r)   rG   z0inject_functional_model_class.<locals>.<genexpr>z  s      04%d+s   )r0   r-   r   r   objectro   	__bases__r!   )r%   r-   s     r)   r1   r1   o  sV    +
e|$$$ f} 8; CM
 KKJr*   rC   )-r   r   r"   rr   collections.abcr   	keras.srcr   r   keras.src.api_exportr   keras.src.layers.layerr   !keras.src.models.variable_mappingr   keras.src.quantizers.awq_corer	   keras.src.quantizers.gptq_corer
   keras.src.quantizers.utilsr   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   r1   rb   r*   r)   <module>r     s       $   - ( D 6 8 < ' 6 ) +7??$ W__%CW__'!GW__'!GW__*$M

OGOO%&&IJ 
 }234`G\))5 ` 5`F! ,- .8r*   