
    &Vf~                     b   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 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!  G d dee          Z"d"dZ#d Z$d Z%d Z&d#dZ'd Z(d Z)d Z*d Z+d  Z,d! Z-dS )$    N)backend)ops)tree)global_state)Input)
InputLayer)	InputSpec)Layer)saving_utils)serialization)Model)Function
_build_map)make_node_key)KerasHistory)Node)serialization_lib)trackingc                   >    e Zd ZdZ fdZej        dd            Zd Zd Z	e
d             ZddZd fd		Zd
 Ze
d             Ze
d             Z fdZddZd Zd Zd Ze
d             Ze
d             Zd Ze
d             Zej        d             Zd Z xZS )
Functionala?
  A `Functional` model is a `Model` defined as a directed graph of layers.

    Three types of `Model` exist: subclassed `Model`, `Functional` model,
    and `Sequential` (a special case of `Functional`).

    A `Functional` model can be instantiated by passing two arguments to
    `__init__()`. The first argument is the `keras.Input` objects
    that represent the inputs to the model.
    The second argument specifies the output tensors that represent
    the outputs of this model. Both arguments can be a nested structure
    of tensors.

    Example:

    ```
    inputs = {'x1': keras.Input(shape=(10,), name='x1'),
              'x2': keras.Input(shape=(1,), name='x2')}
    t = keras.layers.Dense(1, activation='relu')(inputs['x1'])
    outputs = keras.layers.Add()([t, inputs['x2']])
    model = keras.Model(inputs, outputs)
    ```

    A `Functional` model constructed using the Functional API can also
    include raw Keras 3 ops.

    Example:

    ```python
    inputs = keras.Input(shape=(10,))
    x = keras.layers.Dense(1)(inputs)
    outputs = ops.nn.relu(x)
    model = keras.Model(inputs, outputs)
    ```

    A new `Functional` 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=32, height=32)(inputs)
    conv = keras.layers.Conv2D(filters=2, 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 are originated 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` model that support
    all the existing API.

    Args:
        inputs: List of input tensors (must be created via `keras.Input()`
            or originated from `keras.Input()`).
        outputs: List of output tensors.
        name: String, optional. Name of the model.
        trainable: Boolean, optional. If the model's variables should be
            trainable.
    c                 v    t          j        t          t                                          |                     S N)typingcastr   super__new__)clsargskwargs	__class__s      X/var/www/html/software/conda/lib/python3.11/site-packages/keras/src/models/functional.pyr   zFunctional.__new__b   s%    {:uwws';';<<<    Nc                 *   t          |t                    r|                                D ]x\  }}t          |t          j                  s%t          d| d| dt          |                     ||j        k    r)t          j	        d| d| d|j         d| d| d	           ynt          |t          t          f          rE|D ]A}t          |t          j                  s%t          d
| d| dt          |                     Bn=t          |t          j                  s#t          d| dt          |           d          t          |t                    rZ|                                D ]D\  }}t          |t          j                  s%t          d| d| dt          |                     Ent          |t          t          f          rE|D ]A}t          |t          j                  s%t          d| d| dt          |                     Bn=t          |t          j                  s#t          d| dt          |           d          |                    dd           }t          d t          j        |          D                       st!          ||          \  }}t#          j        | ||fd|i| ||| _        | j        | _        |                     d            d| _        d| _        d | j        D             }	d |	D             | _        d S )NzaWhen providing `inputs` as a dict, all values in the dict must be KerasTensors. Received: inputs=z including invalid value z	 of type zyWhen providing `inputs` as a dict, all keys in the dict must match the names of the corresponding tensors. Received key 'z' mapping to value z which has name 'z'. Change the tensor name to 'z' (via `Input(..., name='z')`)zmWhen providing `inputs` as a list/tuple, all values in the list/tuple must be KerasTensors. Received: inputs=z Unrecognized type for `inputs`: z
 (of type )zcWhen providing `outputs` as a dict, all values in the dict must be KerasTensors. Received: outputs=zoWhen providing `outputs` as a list/tuple, all values in the list/tuple must be KerasTensors. Received: outputs=z!Unrecognized type for `outputs`: 	trainablec                 ,    g | ]}t          |          S  )is_input_keras_tensor).0ts     r"   
<listcomp>z'Functional.__init__.<locals>.<listcomp>   s!    KKK)!,,KKKr#   nameFTc                 (    g | ]}|j         d          S )r   )_keras_historyr*   xs     r"   r,   z'Functional.__init__.<locals>.<listcomp>   s     CCC)!,CCCr#   c                     g | ]	}|j         
S r(   )r-   r0   s     r"   r,   z'Functional.__init__.<locals>.<listcomp>   s    ;;;QV;;;r#   )
isinstancedictitemsr   KerasTensor
ValueErrortyper-   warningswarnlisttuplepopallr   flattenclone_graph_nodesr   __init__r&   layers_layersbuild_convert_input_args!_allow_non_tensor_positional_argsoutputsoutput_names)
selfinputsrG   r-   r    kvr1   r&   output_layerss
             r"   rA   zFunctional.__init__e   sB   fd## 	  1!!W%899 $IGMI I34I I?CAwwI I  
 ;;M@23@ @HI@ @ ,-6@ @ 	@ @ 9:	@ @ @   u.. 	  !!W%899 $%"(% %CD% %  77% %   FG$788 	,6 , , LL, , ,   gt$$ 	  1!!W%899 $*#** *EF* * !%Q* *   $// 	  !!W%899 $*#** *EF* * !%Q* *   GW%899 	-G - - MM- - -  
 JJ{D11	KKdl66J6JKKKLL 	A/@@OFG$EEdEfEEE &DN{

4#( 15.CCdlCCC;;];;;r#   c                     d S r   r(   rI   s    r"   _lock_statezFunctional._lock_state   s	     	r#   c                     dS )Nr   r(   rO   s    r"   	_obj_typezFunctional._obj_type   s    |r#   c                 r    g }| j         D ],}t          |t                    r|                    |           -|S r   )_operationsr3   r
   append)rI   rB   	operations      r"   rB   zFunctional.layers   sC    ) 	) 	)I)U++ )i(((r#   c                    |                      |          }|d gt          |          z  }n4|                     |          }t          ||          D ]\  }}|||_        |                     |fd          }t          |          S )Nc                 &    t          |           S )N)trainingoperation_fn)oprY   s    r"   <lambda>z!Functional.call.<locals>.<lambda>   s    Lh,O,O,O r#   rZ   )_standardize_inputslen_flatten_to_reference_inputszip_keras_mask_run_through_graphunpack_singleton)rI   rJ   rY   maskmasksr1   rG   s     `    r"   callzFunctional.call   s    ))&11<FS[[(EE55d;;Evu-- ) )4#$(AM))!O!O!O!O * 
 
  (((r#   c                 F    t                                          |          S r   )r   compute_output_spec)rI   rJ   rY   re   r!   s       r"   ri   zFunctional.compute_output_spec   s    ww**6222r#   c                     d| _         d S )NT)built)rI   input_shapes     r"   rD   zFunctional.build   s    


r#   c                     t          j        d | j                  }t          |t                    rt          |          dk    r|d         S |S )Nc                     | j         S r   shaper1   s    r"   r]   z(Functional.input_shape.<locals>.<lambda>   s    AG r#      r   )r   map_structurerJ   r3   r;   r_   )rI   input_shapess     r"   rl   zFunctional.input_shape   sN    )*;*;T[IIlD)) 	#c,.?.?1.D.D?"r#   c                     t          j        d | j                  }t          |t                    rt          |          dk    r|d         S |S )Nc                     | j         S r   ro   rq   s    r"   r]   z)Functional.output_shape.<locals>.<lambda>   s    QW r#   rr   r   )r   rs   rG   r3   r;   r_   )rI   output_shapess     r"   output_shapezFunctional.output_shape   sO    *+<+<dlKKmT** 	$s=/A/AQ/F/F ##r#   c                 >     t          t          |           j        | S r   )r   r   _assert_input_compatibility)rI   r   r!   s     r"   rz   z&Functional._assert_input_compatibility   s    =uUD!!=tDDr#   Tc                    t          t                    r| j        }t          j        |          s| j        g}t          |t                    r"t          |                                          nd |D             |sgt                    t                    k    rGt          j	        d
                    fd                                D                       d           fdD             S t          j                  S )Nc                 0    g | ]}|j         j        j        S r(   )r/   rV   r-   )r*   inps     r"   r,   z;Functional._flatten_to_reference_inputs.<locals>.<listcomp>   s.     # # #:=C&05# # #r#   zdInput dict contained keys {} which did not match any model input. They will be ignored by the model.c                     g | ]}|v|	S r(   r(   )r*   nref_input_namess     r"   r,   z;Functional._flatten_to_reference_inputs.<locals>.<listcomp>   s#    NNNqQo5M5M5M5M5Mr#      )
stacklevelc                      g | ]
}|         S r(   r(   )r*   r   rJ   s     r"   r,   z;Functional._flatten_to_reference_inputs.<locals>.<listcomp>  s    777!F1I777r#   )r3   r4   _inputs_structr   	is_nestedsortedkeysr_   r9   r:   formatr?   )rI   rJ   allow_extra_keys
ref_inputsr   s    `  @r"   r`   z'Functional._flatten_to_reference_inputs   s(   fd## 	8,J>*-- 3"12
*d++ 
 #)):):";";# #AK# # #
 $ Fc/6J6J(J(JFFLfNNNNFKKMMNNNG G  !    87777777|F###r#   c                     g }t          || j                  D ]9\  }}|                    t          j        ||j        |j                             :|S )N)dtypesparse)ra   _inputsrU   r   convert_to_tensorr   r   )rI   flat_inputs	convertedr1   inputs        r"   _convert_inputs_to_tensorsz%Functional._convert_inputs_to_tensors  sd    	K66 	 	HAu%au{5<PPP    r#   c           	      
   d | j         D             }g }t          ||          D ]\  }}t          |j                  }t          |          }||k    r|                    |           D||dz   k    r;|j        d         dk    r*|                    t          j        |d                     ||dz
  k    r6|d         dk    r*|                    t          j        |d                     t          d| d| d|j                   t          t          |                    D ]^}t          ||         d          r||         j        ||         _        t          ||         d	          r||         j        ||         _        _|S )
Nc                     g | ]	}|j         
S r(   ro   r0   s     r"   r,   z1Functional._adjust_input_rank.<locals>.<listcomp>  s    999q17999r#   rr   )axiszInvalid input shape for input z. Expected shape z#, but input has incompatible shape r/   rb   )r   ra   r_   rp   rU   r   squeezeexpand_dimsr7   rangehasattrr/   rb   )	rI   r   flat_ref_shapesadjustedr1   	ref_shapex_rankref_rankis	            r"   _adjust_input_rankzFunctional._adjust_input_rank  s   99DL999_== 	 	LAy\\F9~~H!!"""A%%72;!##OOCK$;$;$;<<<A%%R=A%%OOCOAB$?$?$?@@@K K KK KABK K  
 s;''(( 	E 	EA{1~'788 K-8^-J*{1~}55 E*5a.*D'r#   c                     |                      |          }|                     |          }|                     |          S r   )r`   r   r   )rI   rJ   r   s      r"   r^   zFunctional._standardize_inputs,  s<    77??55kBB&&{333r#   c                     | j         S r   )r   rO   s    r"   r   zFunctional.input1  s    
 ""r#   c                     | j         S r   )_outputs_structrO   s    r"   outputzFunctional.output8  s    ##r#   c                     t           r   )NotImplementedError)rI   losss     r"   add_losszFunctional.add_loss<  s    !!r#   c                      t           d          r j        S d t           j        t                    r5t           j                                                  } fd|D             S fd j        D             S )N_manual_input_specc                 L    t          |           } | rd | d<   t          |           S )Nr   )r;   r<   rq   s    r"   shape_with_no_batch_sizez7Functional.input_spec.<locals>.shape_with_no_batch_sizeE  s)    QA !88Or#   c                 f    g | ]-}t           j        |         j                  d |          .S )Trp   allow_last_axis_squeezer-   )r	   r   rp   )r*   r-   rI   r   s     r"   r,   z)Functional.input_spec.<locals>.<listcomp>N  s`     	 	 	  22+D17  -1  	 	 	r#   c                 p    g | ]2}t           |j                  d |j        d         j                  3S )Tr   r   )r	   rp   r/   r-   )r*   r1   r   s     r"   r,   z)Functional.input_spec.<locals>.<listcomp>[  s[         2217;;,0)!,1    r#   )r   r   r3   r   r4   r   r   r   )rI   namesr   s   ` @r"   
input_speczFunctional.input_spec@  s    4-.. 	+**	 	 	 d)400 	4.335566E	 	 	 	 	 "	 	 	 	       r#   c                     || _         d S r   )r   )rI   values     r"   r   zFunctional.input_specd  s    "'r#   c                 n    t           j                  st          j                   S  j         j        d}i  j        D ]^}t          |j        t                    rd}nd}t          |j
                  D ](\  }}t          ||          }| j        v r
||<   |dz  })_g } j        D ]}g }t          |j
                  D ]K\  }}t          ||          }| j        v r-t          | j                  }	|	|                    |	           Lt          j        }
t#          j        dd          rt&          j        }
 |
|          }|j        |d<   ||d<   |                    |           ||d	<    fd
fd} | j                  |d<    | j                  |d<   t-          j        |          S )N)r-   r&   rr   r   )	own_nodesuse_legacy_configFr-   inbound_nodesrB   c                     | j         d         }| j         d         }| j         d         }t          ||          }|j        v sJ |         }|j        ||gS )Nr   rr   r   )r/   r   _nodesr-   )tensorrV   
node_indextensor_indexnode_keynew_node_indexnode_reindexing_maprI   s         r"   get_tensor_configz0Functional.get_config.<locals>.get_tensor_config  se    -a0I.q1J!03L$Y
;;Ht{****0:NNNLAAr#   c                     t          | t                    r fd|                                 D             S t          | t          t          f          rfd| D             S  |           gS )Nc                 .    i | ]\  }}| |          S r(   r(   )r*   rK   rL   r   s      r"   
<dictcomp>z>Functional.get_config.<locals>.map_tensors.<locals>.<dictcomp>  s+    LLLDAq,,Q//LLLr#   c                 &    g | ]} |          S r(   r(   )r*   rL   r   s     r"   r,   z>Functional.get_config.<locals>.map_tensors.<locals>.<listcomp>  s%    >>>))!,,>>>r#   )r3   r4   r5   r;   r<   )tensorsr   s    r"   map_tensorsz*Functional.get_config.<locals>.map_tensors  s|    '4(( MLLLLGMMOOLLLL'D%=11 4>>>>g>>>>))'2233r#   input_layersrM   )functional_like_constructorr!   r   
get_configr-   r&   
operations
issubclassr   	enumerate_inbound_nodesr   r   serialize_noderU   r   serialize_keras_objectr   get_global_attributelegacy_serializationr   r   copydeepcopy)rI   configrV   
kept_nodesoriginal_node_indexnoder   layer_configsfiltered_inbound_nodes	node_dataserialize_obj_fnlayer_configr   r   r   s   `            @@r"   r   zFunctional.get_configh  s^   *4>:: 	* #D))) I
 
 ! 	$ 	$I)-z::  


-6(. . $ $)#T )4GHHt{**4>'1!OJ$  	/ 	/I%'"-6(. . 	A 	A)#T )4GHHt{** !/tt{ K K KI ,.55i@@@0G01DeLL O#7#N ++I66L#,>L ,BL)  ....(x	B 	B 	B 	B 	B 	B	4 	4 	4 	4 	4 "-T-@!A!A~"-+d.B"C"C}V$$$r#   r   )NN)T)__name__
__module____qualname____doc__r   r    no_automatic_dependency_trackingrA   rP   rR   propertyrB   rg   ri   rD   rl   rx   rz   r`   r   r   r^   r   r   r   r   setterr   __classcell__)r!   s   @r"   r   r      s       E EN= = = = = .G< G< G< /.G<R       X) ) ) )3 3 3 3 3 3     X   XE E E E E$ $ $ $@    :4 4 4
 # # X# $ $ X$" " " ! ! X!F ( ( (L% L% L% L% L% L% L%r#   r   c                 l   i i fdfd}fd}|d         D ]} ||           r|d         D ]}|d                  }|v r|         }d}|t          |          k     r>||         }		  |||	           n# t          $ r Y nw xY w|dz  }|t          |          k     >|t          |          k     r||d         |<   |= |                    d          }
|                    d	          }fd
fd} ||d                   } ||d                   } | |||
|          S )aI  Instantiates a Functional model from its config (from `get_config()`).

    Args:
        cls: Class of the model, e.g. a custom subclass of `Model`.
        config: Output of `get_config()` for the original model instance.
        custom_objects: Optional dict of custom objects.

    Returns:
        An instance of `cls`.
    c                 V    | vr|g| <   dS |                               |           dS )zAdd node to layer list

        Arg:
            layer: layer object
            node_data: Node data specifying layer call
        N)rU   )layerr   unprocessed_nodess     r"   add_unprocessed_nodez4functional_from_config.<locals>.add_unprocessed_node  sC     )))(1{e$$$e$++I66666r#   c                 >    t          |          \  }} | |i | dS )zReconstruct node by linking to inbound layers

        Args:
            layer: Layer to process
            node_data: List of layer configs
        N)deserialize_node)r   r   r   r    created_layerss       r"   process_nodez,functional_from_config.<locals>.process_node  s5     (	>BBf 	tvr#   c                     | d         }d| vrt          j        |           }nt          j        |           }||<   | d         }|D ]} ||           dS )ztDeserializes a layer and index its inbound nodes.

        Args:
            layer_data: layer config dict.
        r-   module)custom_objectsr   N)r   model_from_configr   deserialize_keras_object)
layer_data
layer_namer   inbound_nodes_datar   r   r   r   s        r"   process_layerz-functional_from_config.<locals>.process_layer  s      '
 :%% !2>  EE &>>  E &+z" (8+ 	3 	3I
 ! 	2222	3 	3r#   rB   r-   r   rr   Nr&   c                     | v sJ |          }t          |t                    r|dz  }|j        |         j        }||         S )Nrr   )r3   r   r   output_tensors)r   r   r   r   layer_output_tensorsr   s        r"   
get_tensorz*functional_from_config.<locals>.get_tensor,  sU    ^++++z*eZ(( 	!OJ$3J?N#L11r#   c                     t          | t                    r fd|                                 D             S fd| D             }t          |          dk    r|d         S |S )Nc                 "    i | ]\  }}| | S r(   r(   )r*   rK   rL   r   s      r"   r   z?functional_from_config.<locals>.map_tensors.<locals>.<dictcomp>7  s%    BBB$!QAzz1~BBBr#   c                     g | ]} | S r(   r(   )r*   rL   r   s     r"   r,   z?functional_from_config.<locals>.map_tensors.<locals>.<listcomp>9  s    ;;;a::q>;;;r#   rr   r   )r3   r4   r5   r_   )r   tensor_listr   s     r"   r   z+functional_from_config.<locals>.map_tensors5  ss    gt$$ 	BBBB'--//BBBB;;;;7;;;K;1$$"1~%r#   r   rM   )rJ   rG   r-   r&   )r_   
IndexErrorget)r   r   r   r   r   r   r   node_data_listr   r   r-   r&   r   input_tensorsr   r   r   r   r   s     `            @@@@r"   functional_from_configr    s?    N 
7 
7 
7 
7 
7
 
 
 
 
3 3 3 3 3 3 3> X& " "
j!!!!  1 * 	1 	1J":f#56E )))!25!9 
 3~#6#666 .z :I$UI6666 &    !OJ !3~#6#666 N 3 333/=jkk/J%e,, *%07  1< ::fD

;''I2 2 2 2 2      K~ 677M [!899N3	   s   5B
BBc                       fd}|S )Nc                  P    t          d          rj        r|d<    | i |S )N_call_has_training_argrY   )r   r
  )r   r    rV   rY   s     r"   rg   zoperation_fn.<locals>.callI  sH    I788	*0	* $!)F:y$)&)))r#   r(   )rV   rY   rg   s   `` r"   r[   r[   H  s)    * * * * * * Kr#   c                     t          j        | j                  j        dd          }t          j        t          j                  j        dd          }||k    rdS dS )Nrr   TF)inspectgetfullargspecrA   r   r   )r   	init_argsfunctional_init_argss      r"   r   r   U  sV    &s|449!""=I"1*2EFFKABBO(((t5r#   c                 t    t          | t          t          f          rt          |           dk    r| d         S | S )Nrr   r   )r3   r;   r<   r_   rq   s    r"   rd   rd   ]  s4    !dE]## A!tHr#   r(   c                     | j         sd S fd}| j        j        }| j        j        }t	          j        ||          }t	          j        ||          }t          j        |          t          j        |          dS )Nc                 V   t          | t          j                  r| j        \  }}}d}t	          |j        d |                   D ]\  }}t          ||          }|	vr|dz  }t          |||z
  |          | _        t          j	        |           }t          |||          | _        |S | S )Nr   rr   )
r3   r   r6   r/   r   r   r   r   r   r   )
r1   rV   r   r   irrelevant_node_countr   r   r   
serializedr   s
            r"   serialize_keras_tensorz.serialize_node.<locals>.serialize_keras_tensorh  s     a,-- 	232B/Iz<$%!$Y%=kzk%JKK / /4(A669,,)Q.)+:(==|   A +A!DDJ+Iz<PPAr#   )r   r    )r  	argumentsr   r    r   rs   r   r   )r   r   r  r   r    s    `   r"   r   r   c  s         $ >D^"F4d;;D 6??F!8>>#:6BB  r#   c           	         | sg i fS t          | t                    rg }| D ]}|d         }|d         }|d         }t          |          dk    ri }n+t          |          dk    r	|d         }nt          d          |         }t          |j                  |k    rt          d| d|j         d	|           |j        |         }	|                    |	j        |                    t          |          g|fS t          j
        | d
                   }
t          j
        | d                   }fd}t          j        ||
          }
t          j        ||          }|
|fS )z1Return (args, kwargs) for calling the node layer.r   rr   r         z3Cannot deserialize the model (invalid config data?)0Layer node index out of bounds.
inbound_layer =  
inbound_layer._inbound_nodes = 
inbound_node_index = r   r    c                 |   t          | t          j                  r| j        }|| S                     |d         d           }|t          d|d                    |d         }|d         }t          |j                  |k    rt          d| d|j         d|           |j        |         }|j        |         S | S )Nr   zUnknown layer: rr   r   r  r  r  )	r3   r   r6    _pre_serialization_keras_historyr  r7   r_   r   r   )r1   historyr   inbound_node_indexinbound_tensor_indexinbound_noder   s         r"   convert_revived_tensorz0deserialize_node.<locals>.convert_revived_tensor  s    a,-- 	E8G"&&wqz488E} !?71:!?!?@@@!(#*1: 5'((,>>> A',A A6;6JA A -?A A   !/0BCL./CDDr#   )r3   r;   r_   r7   r   r  rU   r   rd   r   r   r   rs   )r   r   r  
input_datainbound_layer_namer   r!  r    inbound_layerr"  r   r#  s    `          r"   r   r     s    2v)T"" 9# 	 	J!+A!+A#-a= :!##ZA%%#A I   ++=>M =/004FFF A'4A A %3A A -?	A A   )78JKL  +,@A    !//0&885i6GHHD7	(8KLLF    * 4d;;D 6??F<r#   c                 @    | j         \  }}}|j        |         }|j        S r   )r/   r   is_input)r1   rV   r   _r   s        r"   r)   r)     s-    
 	
		#J/D=r#   c                 `    t          j        | j        | j        | j        | j        dz             S )N_clone)rp   r   r   r-   )r   r6   rp   r   r   r-   rq   s    r"   clone_single_keras_tensorr,    s2    gQWQXAFX<M   r#   c                 8    fd}t          j        ||           S )Nc                     t          | t          j                  s| S t          |           v rt          |                    S t	          |           }|t          |           <   |S r   )r3   r   r6   idr,  )r1   new_xkt_id_mappings     r"   swapz!clone_keras_tensors.<locals>.swap  sa    !W011 	Ha55M!! A'')!,,$beer#   )r   rs   )r   r1  r2  s    ` r"   clone_keras_tensorsr3    s1         dG,,,r#   c                 ,    t          | |          \  }}|S r   r   )rJ   rG   nodesr)  s       r"    find_nodes_by_inputs_and_outputsr6    s    &'**HE1Lr#   c                 4   t          | |          }g }g }i }i }t          j        |           D ]}t          |          r(|                    |           ||t          |          <   9t          |j        |j        |j	        |j
        dz             }|                    |           ||t          |          <   |j        d         |t          |j        d                   <   t          j        | |          }t          j        |          D ]D}	t          |	          }
|	j        |
_        |                    |
           |
|t          |	          <   Et          j        ||          }|D ]}t          |j                  |v r|t          |j                           }n|j        }t          |j        |          }t#          |t$                    s5t          |j        j        |          }t          |j        j        |          }nd}i }t-          ||||           ||fS )a  Clone the `Node` between the inputs and output tensors.

    This function is used to create a new functional model from any intermediate
    Keras tensors. The clone of the nodes mimic the behavior of reconstructing
    the functional graph network by re-executing all the `__call__()` methods.
    The cloned nodes will be appended to the layers.

    Note that a new `keras.Input` will be created for any items in the
    `inputs`

    Args:
    inputs: A nested structure of `KerasTensor` instances.
    outputs: A nested structure of `KerasTensor` instances.

    Returns:
        A pair of inputs and outputs, with cloned `KerasTensor` instances.
        They can be used to create a new functional model.
    CLONE)batch_shaper   r   r-   r   r(   )	call_argscall_kwargsrG   )r6  r   r?   r)   rU   r/  r   rp   r   r   r-   r/   pack_sequence_asr,  rV   r3  r   r3   r   r  r   r    r   )rJ   rG   nodes_to_clonecloned_inputscloned_outputsr1  op_id_mappingkt_inputcloned_input	kt_outputcpyr   rV   output_copycall_args_copycall_kwargs_copys                   r"   r@   r@     sW   & 6fgFFNMN MML((   ** 	  ****2M"X,,'' !$Nn]W,	  L   ...*6M"X,,'+A. "X4Q78899 )&-@@M\'** + +	'	22&5c"""'*bmm$$*7NCCN 
 
dn..%b&8&89III *$*=}MM)Z00 		"0#] N  3%}     N! 	$(		
 	
 	
 	
 	
 .((r#   r   )r(   ).r   r  r   r9   	keras.srcr   r   r   keras.src.backend.commonr   !keras.src.layers.core.input_layerr   r   keras.src.layers.input_specr	   keras.src.layers.layerr
   keras.src.legacy.savingr   r   r   keras.src.models.modelr   keras.src.ops.functionr   r   r   keras.src.ops.noder   r   keras.src.savingr   keras.src.utilsr   r   r  r[   r   rd   r   r   r)   r,  r3  r6  r@   r(   r#   r"   <module>rS     sj                         1 1 1 1 1 1 3 3 3 3 3 3 8 8 8 8 8 8 1 1 1 1 1 1 ( ( ( ( ( ( 0 0 0 0 0 0 I I I I I I ( ( ( ( ( ( + + + + + + - - - - - - 0 0 0 0 0 0 + + + + + + # # # # # # . . . . . . $ $ $ $ $ $Z% Z% Z% Z% Z%5 Z% Z% Z%zN N N Nb
 
 
       D@ @ @F    
- 
- 
-  
W) W) W) W) W)r#   