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

Sequential overrides the layers setter to raise AttributeError because layer management must go through add()/pop() to keep the internal functional graph and tracking consistent.

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)

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.