keras-team/keras · error · ValueError

When using `stateful=True` in a RNN, the batch size must be…

Error message

When using `stateful=True` in a RNN, the batch size must be static. Found dynamic batch size: sequence.shape={sequences_shape}

What it means

Raised in RNN.build when stateful=True but the batch-size dimension of the input sequences is dynamic (None). A stateful RNN keeps state buffers keyed to a fixed batch size, so it requires a static batch dimension to allocate and reuse states across batches.

Solutions

  1. Fix the batch size in your Input, e.g. Input(batch_shape=(32, timesteps, features)) or Input(batch_size=32, ...)
  2. Or use stateful=False so the RNN creates fresh state each batch
  3. Use a fixed-batch-size tf.data pipeline (e.g. .batch(32, drop_remainder=True))
Defensive patterns

Strategy: validation

When it happens

Trigger: Thrown at keras/src/layers/rnn/rnn.py:281 when the library encounters an invalid state.

Common situations: See trigger scenarios.


AI-assisted analysis of keras-team/keras@7a34a03db6 (2026-08-25). Data as JSON: /api/errors/d8290f5c3922691b. Report an issue: GitHub.

Appendix: source

Thrown at keras/src/layers/rnn/rnn.py:281

        output_mask = mask if self.return_sequences else None
        if self.return_state:
            state_mask = [None for _ in self.state_size]
            return [output_mask] + state_mask
        else:
            return output_mask

    def build(self, sequences_shape, initial_state_shape=None):
        # Build cell (if layer).
        step_input_shape = (sequences_shape[0],) + tuple(sequences_shape[2:])
        if isinstance(self.cell, Layer) and not self.cell.built:
            self.cell.build(step_input_shape)
            self.cell.built = True
        if self.stateful:
            if self.states is not None:
                self.reset_state()
            else:
                if sequences_shape[0] is None:
                    raise ValueError(
                        "When using `stateful=True` in a RNN, the "
                        "batch size must be static. Found dynamic "
                        f"batch size: sequence.shape={sequences_shape}"
                    )
                self._create_state_variables(sequences_shape[0])
                self._expected_batch_size = ops.shape(
                    tree.flatten(self.states)[0]
                )[0]

    @tracking.no_automatic_dependency_tracking
    def _create_state_variables(self, batch_size):
        with backend.name_scope(self.name, caller=self):
            self.states = tree.map_structure(
                lambda value: backend.Variable(
                    value,
                    trainable=False,
                    dtype=self.variable_dtype,
                    name="rnn_state",

View on GitHub (pinned to 7a34a03db6)