o
    i eY                     @   s  d Z ddlZddlm  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ZeddG dd dejZ dd Z!dd Z"dd Z#dd Z$dS )zHome of the `Sequential` model.    N)layers)
base_layer)
functional)input_layer)training)training_utils)serialization_lib)serialization)model_serialization)generic_utils)layer_utils)
tf_inspect)tf_utils)traceback_utils)keras_exportzuAll layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.zkeras.Sequentialzkeras.models.Sequentialc                       s  e Zd ZdZejjjej	d" fdd	Z
e fddZejjjej	dd Zejjjej	d	d
 Zejjj	d#ddZejd# fdd	Zd" fdd	Zdd Zdd Z fddZed#ddZe fddZejdd Zedd Zdd Z fd d!Z  ZS )$
Sequentiala  `Sequential` groups a linear stack of layers into a `tf.keras.Model`.

    `Sequential` provides training and inference features on this model.

    Examples:

    ```python
    model = tf.keras.Sequential()
    model.add(tf.keras.Input(shape=(16,)))
    model.add(tf.keras.layers.Dense(8))

    # Note that you can also omit the initial `Input`.
    # In that case the model doesn't have any weights until the first call
    # to a training/evaluation method (since it isn't yet built):
    model = tf.keras.Sequential()
    model.add(tf.keras.layers.Dense(8))
    model.add(tf.keras.layers.Dense(4))
    # model.weights not created yet

    # Whereas if you specify an `Input`, the model gets built
    # continuously as you are adding layers:
    model = tf.keras.Sequential()
    model.add(tf.keras.Input(shape=(16,)))
    model.add(tf.keras.layers.Dense(4))
    len(model.weights)
    # Returns "2"

    # When using the delayed-build pattern (no input shape specified), you can
    # choose to manually build your model by calling
    # `build(batch_input_shape)`:
    model = tf.keras.Sequential()
    model.add(tf.keras.layers.Dense(8))
    model.add(tf.keras.layers.Dense(4))
    model.build((None, 16))
    len(model.weights)
    # Returns "4"

    # Note that when using the delayed-build pattern (no input shape specified),
    # the model gets built the first time you call `fit`, `eval`, or `predict`,
    # or the first time you call the model on some input data.
    model = tf.keras.Sequential()
    model.add(tf.keras.layers.Dense(8))
    model.add(tf.keras.layers.Dense(1))
    model.compile(optimizer='sgd', loss='mse')
    # This builds the model for the first time:
    model.fit(x, y, batch_size=32, epochs=10)
    ```
    Nc                    s   t tj| j|dd tjdd d| _d| _	d| _
d| _d| _d| _i | _t | _d| _d| _|rIt|ttfs?|g}|D ]	}| | qAdS dS )zCreates a `Sequential` model instance.

        Args:
          layers: Optional list of layers to add to the model.
          name: Optional name for the model.
        F)nameautocastr   TN)superr   
Functional__init__r   keras_api_gaugeget_cellsetsupports_masking _compute_output_and_mask_jointly_auto_track_sub_layers_inferred_input_shape_has_explicit_input_shape_input_dtype_layer_call_argspecs_created_nodes_graph_initialized_use_legacy_deferred_behavior
isinstancelisttupleadd)selfr   r   layer	__class__ J/var/www/myenv/lib/python3.10/site-packages/keras/src/engine/sequential.pyr   b   s&   zSequential.__init__c                    s4   t  j}|rt|d tjr|dd  S |d d  S )Nr      )r   r   r$   r   
InputLayer)r(   r   r*   r,   r-   r      s   zSequential.layersc           	      C   s  t |dr|jd }t|tjr|}t|tjr$t|tjs#t	
|}ntd| dt| dt|g | |sEtd|j dd| _d}| d	g  | jst|tjr\d
}nt|\}}|rvtj|||jd d}|| d
}|rtj|jd j}t|dkrtt|| _t| jd | _ d
| _d
| _!n| jr|| jd }ttj|dkrtt|g| _d
| _|s| j"r| #| j | j d
| _"n| j$| | %|g t&'|j(| j)|< dS )a  Adds a layer instance on top of the layer stack.

        Args:
            layer: layer instance.

        Raises:
            TypeError: If `layer` is not a layer instance.
            ValueError: In case the `layer` argument does not
                know its input shape.
            ValueError: In case the `layer` argument has
                multiple output tensors, or is already connected
                somewhere else (forbidden in `Sequential` models).
        _keras_historyr   zDThe added layer must be an instance of class Layer. Received: layer=z	 of type .zGAll layers added to a Sequential model should have unique names. Name "za" is already the name of a layer in this model. Update the `name` argument to pass a unique name.F_self_tracked_trackablesT_inputbatch_shapedtyper   r.   N)*hasattrr0   r$   r   r/   tfModuler   Layerr   ModuleWrapper	TypeErrortyper   assert_no_legacy_layers_is_layer_name_unique
ValueErrorr   built_maybe_create_attributer2   r   get_input_shape_and_dtypeInputnestflatten_inbound_nodesoutputslenSINGLE_LAYER_OUTPUT_ERROR_MSGr   get_source_inputsinputsr   r"   _init_graph_networkappend#_handle_deferred_layer_dependenciesr   getfullargspeccallr    )	r(   r)   origin_layer
set_inputsr5   r6   xrI   output_tensorr,   r,   r-   r'      sx   




zSequential.addc                 C   s   | j std| j }| j| | j s)d| _d| _d| _d| _d| _	d| _
dS | j
rGg | j d _| j d jg| _| | j| j d| _dS dS )zzRemoves the last layer in the model.

        Raises:
            TypeError: if there are no layers in the model.
        z!There are no layers in the model.NFr7   T)r   r=   r2   popr    rI   rM   rB   r   r   r"   _outbound_nodesoutputrN   )r(   r)   r,   r,   r-   rW      s"   


zSequential.popc           
      C   sx  |d u s| j s	d S tjj rtjj sd S | js| j	st
|}| jd u r)|}nt| j|}|d ur|| jkrt k tj||| j d jd d}|}t }| j D ]6}t|| j z||}W n   d| _	Y  W d    d S ttj|dkrttt|| |}|}	qS|| _z| ||	 d| _W n   d| _	Y W d    n1 sw   Y  || _d S d S d S d S d S )Nr   r3   r4   Tr.   )r   r9   __internal__tf2enabledcompatv1#executing_eagerly_outside_functionsr   r#   r&   r   relax_input_shape
init_scoper   rE   r   r   clear_previously_created_nodesr!   rJ   rF   rG   rA   rK    track_nodes_created_by_last_callrN   r"   )
r(   input_shapeinput_dtype	new_shaperM   layer_inputcreated_nodesr)   layer_outputrI   r,   r,   r-   '_build_graph_network_for_inferred_shape  sl   






)
	

=z2Sequential._build_graph_network_for_inferred_shapec                    s\   | j r| | j| j n|d u rtd| | | js)t|}|| _t	 
| d| _d S )Nz+You must provide an `input_shape` argument.T)r"   rN   rM   rI   rA   rj   rB   r&   _build_input_shaper   build)r(   rd   r*   r,   r-   rl   m  s   

zSequential.buildc           	         s   | j s"t|st|tjsd| _tjt|| _	n| 
|j|j | jr9| js0| | j| j t j|||dS |}| jD ]/}i }| j| j}d|v rP||d< d|v rX||d< ||fi |}|}dd }tj||}q>|S )NT)r   maskrm   r   c                 S   s   t | dd S )N_keras_mask)getattr)ktr,   r,   r-   _get_mask_from_keras_tensor  s   z4Sequential.call.<locals>._get_mask_from_keras_tensor)r   r9   	is_tensorr$   Tensorr#   rF   map_structure_get_shape_tuplerk   rj   shaper6   r"   rB   rN   rM   rI   r   rR   r   r    args)	r(   rM   r   rm   rI   r)   kwargsargspecrq   r*   r,   r-   rR   {  s4   
zSequential.callc                 C   s   |}| j D ]}||}q|S N)r   compute_output_shape)r(   rd   rv   r)   r,   r,   r-   r{     s   
zSequential.compute_output_shapec                 C   s   | j ||d}t|dd S )N)rm   rn   )rR   ro   )r(   rM   rm   rI   r,   r,   r-   compute_mask  s   zSequential.compute_maskc                    sz   g }t j}t| dd rtj}t jD ]	}||| qtj	| }| j
|d< t||d< | js;| jd ur;| j|d< |S )Nuse_legacy_configr   r   build_input_shape)r   serialize_keras_objectro   legacy_serializationr   r   rO   r   Model
get_configr   copydeepcopy_is_graph_networkrk   )r(   layer_configsserialize_obj_fnr)   configr*   r,   r-   r     s   

zSequential.get_configc           
      C   s   d|v r|d }| d}|d }nd }|}| |d}|D ]}d|v}tj|||d}	||	 q|jsB|rBt|ttfrB|| |S )Nr   r~   r   )r   module)custom_objectsuse_legacy_format)	getlayer_moduledeserializer'   rM   r$   r&   r%   rl   )
clsr   r   r   r~   r   modellayer_configr   r)   r,   r,   r-   from_config  s.   



zSequential.from_configc                    s"   t | dr| jS | jrt jS d S )N_manual_input_spec)r8   r   r   r   
input_specr(   r*   r,   r-   r     s
   
zSequential.input_specc                 C   s
   || _ d S rz   )r   )r(   valuer,   r,   r-   r        
c                 C   s
   t | S rz   )r
   SequentialSavedModelSaverr   r,   r,   r-   _trackable_saved_model_saver  r   z'Sequential._trackable_saved_model_saverc                 C   s*   | j D ]}|j|jkr||ur dS qdS )NFT)r   r   )r(   r)   	ref_layerr,   r,   r-   r@     s
   
z Sequential._is_layer_name_uniquec                    s   | j rd S ttj|   d S rz   )r"   r   r   r   _assert_weights_createdr   r*   r,   r-   r     s   z"Sequential._assert_weights_created)NNrz   )__name__
__module____qualname____doc__r9   rZ   tracking no_automatic_dependency_trackingr   filter_tracebackr   propertyr   r'   rW   rj   r   defaultrl   rR   r{   r|   r   classmethodr   r   setterr   r@   r   __classcell__r,   r,   r*   r-   r   /   s@    1%]^,

r   c                 C   s<   t | dr| j}t|tr|S |jd urt| S d S d S )Nrv   )r8   rv   r$   r&   rankas_list)trv   r,   r,   r-   ru      s   


ru   c                 C   s@   | d u s|d u r
d S t | t |krd S tdd t| |D S )Nc                 s   s$    | ]\}}||krd n|V  qd S rz   r,   ).0d1d2r,   r,   r-   	<genexpr>  s   " z$relax_input_shape.<locals>.<genexpr>)rJ   r&   zip)shape_1shape_2r,   r,   r-   r`     s
   r`   c                    sT   | j D ]}|j}tj|D ]} fdd|jD |_qq fdd| j D | _ dS )zARemove nodes from `created_nodes` from the layer's inbound_nodes.c                       g | ]}| vr|qS r,   r,   r   nrh   r,   r-   
<listcomp>      z2clear_previously_created_nodes.<locals>.<listcomp>c                    r   r,   r,   r   r   r,   r-   r     r   N)rH   inbound_layersr9   rF   rG   rX   )r)   rh   nodeprev_layers
prev_layerr,   r   r-   rb     s   



rb   c                 C   sR   | j sdS || j d  | j d j}tj|D ]}|jr&||jd  qdS )zFAdds to `created_nodes` the nodes created by the last call to `layer`.Nr7   )rH   r'   r   r9   rF   rG   rX   )r)   rh   r   r   r,   r,   r-   rc      s   rc   )%r   r   tensorflow.compat.v2r]   v2r9   	keras.srcr   r   keras.src.enginer   r   r   r   r   keras.src.savingr   keras.src.saving.legacyr	   r   #keras.src.saving.legacy.saved_modelr
   keras.src.utilsr   r   r   r   r    tensorflow.python.util.tf_exportr   rK   r   r   ru   r`   rb   rc   r,   r,   r,   r-   <module>   s:      S