keras-team/keras · error · AttributeError

`Sequential.layers` attribute is reserved and should not be…

Error message

`Sequential.layers` attribute is reserved and should not be used. Use `add()` and `pop()` to change the layers in this model.

What it means

Raised when assigning to Sequential.layers. 'layers' is a reserved read-only property on Sequential; the layer stack must be modified only through add() and pop() so internal graph and variable bookkeeping stays consistent.

Solutions

  1. Use model.add(layer) to append and model.pop() to remove
  2. Build a new Sequential from the desired layer list
  3. Modify _layers only if you fully own lifecycle and rebuild via _functional

Example fix

# before
model.layers = [dense1, dense2]

# after
model = keras.Sequential([dense1, dense2])
# or: model.add(dense1); model.add(dense2)
Defensive patterns

Strategy: try-catch

Try / catch

try:
    model.layers = new_layers
except AttributeError:
    model = keras.Sequential(new_layers)

Prevention

When it happens

Trigger: model.layers = [l1, l2] on a keras.Sequential instance

Common situations: Porting PyTorch-style code or attempting layer surgery on a trained model

Related errors


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

Appendix: source

Thrown at keras/src/models/sequential.py:269

                outputs = layer(inputs)
            inputs = outputs

            mask = tree.map_structure(backend.get_keras_mask, outputs)
        return outputs

    @property
    def layers(self):
        # Historically, `sequential.layers` only returns layers that were added
        # via `add`, and omits the auto-generated `InputLayer` that comes at the
        # bottom of the stack.
        layers = self._layers
        if layers and isinstance(layers[0], InputLayer):
            return layers[1:]
        return layers[:]

    @layers.setter
    def layers(self, _):
        raise AttributeError(
            "`Sequential.layers` attribute is reserved and should not be used. "
            "Use `add()` and `pop()` to change the layers in this model."
        )

    def compute_output_spec(self, inputs, training=None, mask=None, **kwargs):
        if self._functional:
            return self._functional.compute_output_spec(
                inputs, training=training, mask=mask, **kwargs
            )
        # Direct application
        for layer in self.layers:
            outputs = layer.compute_output_spec(
                inputs,
                training=training,
                **kwargs,
            )  # Ignore mask
            inputs = outputs
        return outputs

View on GitHub (pinned to 7a34a03db6)