
    2VhK                         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d
       G d de             Zy)    )backend)ops)tree)keras_export)Layer)DropoutRNNCell)StackedRNNCells)serialization_lib)trackingzkeras.layers.RNNc                        e Zd ZdZ	 	 	 	 	 	 d fd	ZddZd ZddZej                  d        Z
d Zd Zd	 Zdd
Z	 	 	 ddZd Zd Z fdZedd       Z xZS )RNNaL  Base class for recurrent layers.

    Args:
        cell: A RNN cell instance or a list of RNN cell instances.
            A RNN cell is a class that has:
            - A `call(input_at_t, states_at_t)` method, returning
            `(output_at_t, states_at_t_plus_1)`. The call method of the
            cell can also take the optional argument `constants`, see
            section "Note on passing external constants" below.
            - A `state_size` attribute. This can be a single integer
            (single state) in which case it is the size of the recurrent
            state. This can also be a list/tuple of integers
            (one size per state).
            - A `output_size` attribute, a single integer.
            - A `get_initial_state(batch_size=None)`
            method that creates a tensor meant to be fed to `call()` as the
            initial state, if the user didn't specify any initial state
            via other means. The returned initial state should have
            shape `(batch_size, cell.state_size)`.
            The cell might choose to create a tensor full of zeros,
            or other values based on the cell's implementation.
            `inputs` is the input tensor to the RNN layer, with shape
            `(batch_size, timesteps, features)`.
            If this method is not implemented
            by the cell, the RNN layer will create a zero filled tensor
            with shape `(batch_size, cell.state_size)`.
            In the case that `cell` is a list of RNN cell instances, the cells
            will be stacked on top of each other in the RNN, resulting in an
            efficient stacked RNN.
        return_sequences: Boolean (default `False`). Whether to return the last
            output in the output sequence, or the full sequence.
        return_state: Boolean (default `False`).
            Whether to return the last state in addition to the output.
        go_backwards: Boolean (default `False`).
            If `True`, process the input sequence backwards and return the
            reversed sequence.
        stateful: Boolean (default `False`). If True, the last state
            for each sample at index `i` in a batch will be used as initial
            state for the sample of index `i` in the following batch.
        unroll: Boolean (default `False`).
            If True, the network will be unrolled, else a symbolic loop will be
            used. Unrolling can speed-up a RNN, although it tends to be more
            memory-intensive. Unrolling is only suitable for short sequences.
        zero_output_for_mask: Boolean (default `False`).
            Whether the output should use zeros for the masked timesteps.
            Note that this field is only used when `return_sequences`
            is `True` and `mask` is provided.
            It can useful if you want to reuse the raw output sequence of
            the RNN without interference from the masked timesteps, e.g.,
            merging bidirectional RNNs.

    Call arguments:
        sequences: A 3-D tensor with shape `(batch_size, timesteps, features)`.
        initial_state: List of initial state tensors to be passed to the first
            call of the cell.
        mask: Binary tensor of shape `[batch_size, timesteps]`
            indicating whether a given timestep should be masked.
            An individual `True` entry indicates that the corresponding
            timestep should be utilized, while a `False` entry indicates
            that the corresponding timestep should be ignored.
        training: Python boolean indicating whether the layer should behave in
            training mode or in inference mode. This argument is passed
            to the cell when calling it.
            This is for use with cells that use dropout.

    Output shape:

    - If `return_state`: a list of tensors. The first tensor is
    the output. The remaining tensors are the last states,
    each with shape `(batch_size, state_size)`, where `state_size` could
    be a high dimension tensor shape.
    - If `return_sequences`: 3D tensor with shape
    `(batch_size, timesteps, output_size)`.

    Masking:

    This layer supports masking for input data with a variable number
    of timesteps. To introduce masks to your data,
    use a `keras.layers.Embedding` layer with the `mask_zero` parameter
    set to `True`.

    Note on using statefulness in RNNs:

    You can set RNN layers to be 'stateful', which means that the states
    computed for the samples in one batch will be reused as initial states
    for the samples in the next batch. This assumes a one-to-one mapping
    between samples in different successive batches.

    To enable statefulness:

    - Specify `stateful=True` in the layer constructor.
    - Specify a fixed batch size for your model, by passing
        `batch_size=...` to the `Input` layer(s) of your model.
        Remember to also specify the same `batch_size=...` when
        calling `fit()`, or otherwise use a generator-like
        data source like a `keras.utils.PyDataset` or a
        `tf.data.Dataset`.
    - Specify `shuffle=False` when calling `fit()`, since your
        batches are expected to be temporally ordered.

    To reset the states of your model, call `.reset_state()` on either
    a specific layer, or on your entire model.

    Note on specifying the initial state of RNNs:

    You can specify the initial state of RNN layers symbolically by
    calling them with the keyword argument `initial_state`. The value of
    `initial_state` should be a tensor or list of tensors representing
    the initial state of the RNN layer.

    You can specify the initial state of RNN layers numerically by
    calling `reset_state()` with the keyword argument `states`. The value of
    `states` should be a numpy array or list of numpy arrays representing
    the initial state of the RNN layer.

    Examples:

    ```python
    from keras.layers import RNN
    from keras import ops

    # First, let's define a RNN Cell, as a layer subclass.
    class MinimalRNNCell(keras.Layer):

        def __init__(self, units, **kwargs):
            super().__init__(**kwargs)
            self.units = units
            self.state_size = units

        def build(self, input_shape):
            self.kernel = self.add_weight(shape=(input_shape[-1], self.units),
                                          initializer='uniform',
                                          name='kernel')
            self.recurrent_kernel = self.add_weight(
                shape=(self.units, self.units),
                initializer='uniform',
                name='recurrent_kernel')

        def call(self, inputs, states):
            prev_output = states[0]
            h = ops.matmul(inputs, self.kernel)
            output = h + ops.matmul(prev_output, self.recurrent_kernel)
            return output, [output]

    # Let's use this cell in a RNN layer:

    cell = MinimalRNNCell(32)
    x = keras.Input((None, 5))
    layer = RNN(cell)
    y = layer(x)

    # Here's how to use the cell to build a stacked RNN:

    cells = [MinimalRNNCell(32), MinimalRNNCell(64)]
    x = keras.Input((None, 5))
    layer = RNN(cells)
    y = layer(x)
    ```
    c                 `   t        |t        t        f      rt        |      }dt	        |      vrt        d|       dt	        |      vrt        d|       t        
|   d	i | || _        || _	        || _
        || _        || _        || _        || _        d| _        d | _        d | _        t%        | j                  dd       }	|	t        d      t        |	t        t        t&        f      st        d      t        |	t&              r|	g| _        d| _        y t        |	      | _        d| _        y )
Ncallz<Argument `cell` should have a `call` method. Received: cell=
state_sizezThe RNN cell should have a `state_size` attribute (single integer or list of integers, one integer per RNN state). Received: cell=Tz9state_size must be specified as property on the RNN cell.zWstate_size must be an integer, or a list/tuple of integers (one for each state tensor).F )
isinstancelisttupler	   dir
ValueErrorsuper__init__zero_output_for_maskcellreturn_sequencesreturn_statego_backwardsstatefulunrollsupports_masking
input_specstatesgetattrintr   single_state)selfr   r   r   r   r   r   r   kwargsr   	__class__s             H/home/dcms/DCMS/lib/python3.12/site-packages/keras/src/layers/rnn/rnn.pyr   zRNN.__init__   sN    dT5M*"4(DT"""&)  s4y(" #')  	"6"
 %9!	 0((  $TYYd;
K  *tUC&89/  j#&)lDO $D":.DO %D    c                    |d   }|d   }g }| j                   D ]^  }t        |t              r|j                  ||f       't        |t        t
        f      s>|j                  |D cg c]  }||f c}       ` t        | j                  dd       }|| j                   d   }t        |t              st        d      | j                  r|||f}	n||f}	| j                  r|	g|S |	S c c}w )Nr      output_sizezoutput_size must be an integer.)r   r   r$   appendr   r   r#   r   r   r   r   )
r&   sequences_shapeinitial_state_shape
batch_sizelengthstates_shaper   sr-   output_shapes
             r)   compute_output_shapezRNN.compute_output_shape   s    $Q'
 #// 	KJ*c*##Z$<=Ju6##j$Ij!_$IJ		K dii=//!,K+s+>??  &<L&4L.,.. %Js   &C'
c                     t        j                  |      d   }| j                  r|nd }| j                  r| j                  D cg c]  }d  }}|g|z   S |S c c}w Nr   )r   flattenr   r   r   )r&   _maskoutput_mask
state_masks        r)   compute_maskzRNN.compute_mask   s^    
 ||D!!$"33d(,81$8J8=:-- 9s   	Ac                    |d   ft        |dd        z   }t        | j                  t              rB| j                  j                  s,| j                  j                  |       d| j                  _        | j                  rE| j                  | j                          y |d   t        d|       | j                  |d          y y )Nr      TzmWhen using `stateful=True` in a RNN, the batch size must be static. Found dynamic batch size: sequence.shape=)r   r   r   r   builtbuildr   r"   reset_stater   _create_state_variables)r&   r/   r0   step_input_shapes       r)   rB   z	RNN.build  s    +A.059L3MMdii'		IIOO,-"DIIO=={{&  ""1%-$66E5FH 
 ,,_Q-?@ r*   c                      t        j                   j                         5  t        j                   fd j                  |             _        d d d        y # 1 sw Y   y xY w)N)callerc                 J    t        j                  | dj                  d      S )NF	rnn_state)	trainabledtypename)r   Variablevariable_dtype)valuer&   s    r)   <lambda>z-RNN._create_state_variables.<locals>.<lambda>#  s$    g..#--$	 r*   )r   
name_scoperL   r   map_structureget_initial_stater"   )r&   r1   s   ` r)   rD   zRNN._create_state_variables  sS    		$7 		,, &&z2DK		 		 		s   .AA#c                 "   t        | j                  dd       }|r
 ||      }nE| j                  D cg c]/  }t        j                  ||f| j                  j
                        1 c}S t        j                  |      s|g}t        |      S c c}w )NrS   r1   rK   )	r#   r   r   r   zeroscompute_dtyper   	is_nestedr   )r&   r1   get_initial_state_fn
init_stateds        r)   rS   zRNN.get_initial_state,  s    &tyy2EtL-DJ  		:q/1H1HI  ~~j)$J Js   4Bc                 $    | j                          y N)rC   )r&   s    r)   reset_stateszRNN.reset_states=  s    r*   c                     | j                   6| j                   D ]&  }|j                  t        j                  |             ( y y r^   )r"   assignr   
zeros_like)r&   vs     r)   rC   zRNN.reset_stateA  s9    ;;"[[ ,*+, #r*   c                 V    i t         j                  t              r j                  j                  r|d<    fd}t	        j
                  |      s|g}t        j                  ||| j                  | j                  |j                  d    j                   j                  	      S )Ntrainingc                     t        j                          dk(  r0j                  r$t        j                  t        j
                  |      } j                  | |fi \  }}t        j                  |      s|g}||fS )Ntorch)r   r   r   rR   r   copyr   rY   )inputsr"   output
new_statescell_kwargsr&   s       r)   stepzRNN.inner_loop.<locals>.stepK  sj    
  G+++CHHf=!*66!I[!IFJ>>*-(\
:%%r*   r,   )r   r;   r   input_lengthr   return_all_outputs)r   r   r   _call_has_training_argr   rY   r   rnnr   r   shaper   r   )r&   	sequencesinitial_stater;   re   rm   rl   s   `     @r)   
inner_loopzRNN.inner_loopF  s    dii'DII,L,L&.K
#
	& ~~m,*OM{{**;;"+!%!:!:#44

 
	
r*   c                     |j                   d   } j                  r|t        d      |A j                  r j                  }n( j                  t        j                   |      d         }t        j                  |      s|g}t        |      }t        j                   fd|      } j                   j                  |d d dd d f   |        j                  ||||      \  }}}t        j                  | j                        }t        j                  | j                        }t        j                   fd|      } j!                   j                          j                  rUt#        t        j$                   j                        t        j$                  |            D ]  \  }	}
|	j'                  |
         j(                  r|}n|} j*                  r|g|S |S )Nr,   a  Cannot unroll a RNN if the time dimension is undefined. 
- If using a Sequential model, specify the time dimension by passing an `Input()` as your first layer.
- If using the functional API, specify the time dimension by passing a `shape` or `batch_shape` argument to your `Input()`.r   rU   c                 Z    t        j                  | j                  j                        S NrV   )r   convert_to_tensorr   rX   xr&   s    r)   rP   zRNN.call.<locals>.<lambda>  s!    g//00 r*   )rs   rt   r;   re   c                 F    t        j                  | j                        S rx   )r   castrX   rz   s    r)   rP   zRNN.call.<locals>.<lambda>  s    chhq(:(:; r*   )rr   r   r   r   r"   rS   r   r   rY   r   rR   _maybe_config_dropout_masksr   ru   r}   rX   _maybe_reset_dropout_maskszipr9   ra   r   r   )r&   rs   rt   r;   re   	timestepslast_outputoutputsr"   
self_statestaterj   s   `           r)   r   zRNN.callf  s    OOA&	;;9,?	 	  }} $ $ 6 6"yy3A6 !7 ! ~~m,*OM]+
 ** 	
 	((IIyAq)=	
 (,'	 (7 (
$Wf hh{D,>,>?((7D$6$67##;V
 	''		2==%(T[[)4<<+?& )!
E !!%()
   F F?F?"r*   c                    t        |t        t        f      r|d   n|}t        |t              r"|j	                  |       |j                  |       t        |t              rt        |j                  |      D ]j  \  }}| j                  |||       t        j                  |      rt        |      n|g}t        |      r|j                  n|j                  } |||      \  }}l y y r8   )r   r   r   r   get_dropout_maskget_recurrent_dropout_maskr	   r   cellsr~   r   rY   callable__call__r   )	r&   r   input_sequenceinput_stater   cr4   cell_call_fnr:   s	            r)   r~   zRNN._maybe_config_dropout_masks  s     +e}5 N 	
 dN+!!.1++E2dO,DJJ4 D100NAF  $~~a0DGqc-5a[qzzaff$0$C!D -r*   c                     t        |t              r |j                          |j                          t        |t              r#|j
                  D ]  }| j                  |        y y r^   )r   r   reset_dropout_maskreset_recurrent_dropout_maskr	   r   r   )r&   r   r   s      r)   r   zRNN._maybe_reset_dropout_masks  sT    dN+##%--/dO,ZZ 3//23 -r*   c                     | j                   | j                  | j                  | j                  | j                  | j
                  d}t        j                  | j                        |d<   t        | )         }i ||S )N)r   r   r   r   r   r   r   )r   r   r   r   r   r   r
   serialize_keras_objectr   r   
get_config)r&   configbase_configr(   s      r)   r   zRNN.get_config  ss     $ 5 5 -- --kk$($=$=
 +AA$))Lvg(*(+(((r*   c                 d    t        j                  |j                  d      |      } | |fi |}|S )Nr   )custom_objects)r
   deserialize_keras_objectpop)clsr   r   r   layers        r)   from_configzRNN.from_config  s6     99JJv~
 D#F#r*   )FFFFFFr^   )F)NNF)__name__
__module____qualname____doc__r   r6   r>   rB   r    no_automatic_dependency_trackingrD   rS   r_   rC   ru   r   r~   r   r   classmethodr   __classcell__)r(   s   @r)   r   r      s    ^F "9&v.A$ ..
 /
 ",

F JXD$3)  r*   r   N)	keras.srcr   r   r   keras.src.api_exportr   keras.src.layers.layerr   %keras.src.layers.rnn.dropout_rnn_cellr   &keras.src.layers.rnn.stacked_rnn_cellsr	   keras.src.savingr
   keras.src.utilsr   r   r   r*   r)   <module>r      sD       - ( @ B . $  !R% R "Rr*   