keras-team/keras · error · ValueError

Layer '{self.name}' was never built and thus it doesn't have

Error message

Layer '{self.name}' was never built and thus it doesn't have any variables. However the weights file lists {len(store.keys())} variables for this layer.
In most cases, this error indicates that either:

1. The layer is owned by a parent layer that implements a `build()` method, but calling the parent's `build()` method did NOT create the state of the child layer '{self.name}'. A `build()` method must create ALL state for the layer, including the state of any children layers.

2. You need to implement the `def build_from_config(self, config)` method on layer '{self.name}', to specify how to rebuild it during loading. In this case, you might also want to implement the method that generates the build config at saving time, `def get_build_config(self)`. The method `build_from_config()` is meant to create the state of the layer (i.e. its variables) upon deserialization.

What it means

When loading a weights file, the layer has zero variables because it was never built, yet the file lists variables for it. Keras explains the two usual causes: a parent's build() did not create the child layer's state, or the layer lacks build_from_config()/get_build_config() so loading cannot reconstruct its state.

Source

Thrown at keras/src/layers/layer.py:1477

    def save_own_variables(self, store):
        """Saves the state of the layer.

        You can override this method to take full control of how the state of
        the layer is saved upon calling `model.save()`.

        Args:
            store: Dict where the state of the model will be saved.
        """
        all_vars = self._trainable_variables + self._non_trainable_variables
        for i, v in enumerate(all_vars):
            store[f"{i}"] = v

    def _check_load_own_variables(self, store):
        all_vars = self._trainable_variables + self._non_trainable_variables
        if len(store.keys()) != len(all_vars):
            if len(all_vars) == 0 and not self.built:
                raise ValueError(
                    f"Layer '{self.name}' was never built "
                    "and thus it doesn't have any variables. "
                    f"However the weights file lists {len(store.keys())} "
                    "variables for this layer.\n"
                    "In most cases, this error indicates that either:\n\n"
                    "1. The layer is owned by a parent layer that "
                    "implements a `build()` method, but calling the "
                    "parent's `build()` method did NOT create the state of "
                    f"the child layer '{self.name}'. A `build()` method "
                    "must create ALL state for the layer, including "
                    "the state of any children layers.\n\n"
                    "2. You need to implement "
                    "the `def build_from_config(self, config)` method "
                    f"on layer '{self.name}', to specify how to rebuild "
                    "it during loading. "
                    "In this case, you might also want to implement the "
                    "method that generates the build config at saving time, "
                    "`def get_build_config(self)`. "

View on GitHub (pinned to 7a34a03db6)

Solutions

  1. In the parent's build(), ensure every child layer's build() is invoked (or children created in __init__) so their variables exist
  2. Implement get_build_config() and build_from_config(self, config) on custom layers so loading rebuilds state
  3. Create child layers in __init__ rather than lazily inside call()

Example fix

# before
class Parent(keras.layers.Layer):
    def call(self, x):
        if not hasattr(self, 'dense'):
            self.dense = keras.layers.Dense(4)(x)
        return self.dense(x)
# after
class Parent(keras.layers.Layer):
    def build(self, input_shape):
        self.dense = keras.layers.Dense(4)
        self.dense.build(input_shape)
    def call(self, x):
        return self.dense(x)
Defensive patterns

Strategy: validation

Validate before calling

assert layer.built or not saving, f'{layer.name} unbuilt while saving'

Try / catch

try:
    keras.saving.load_model(path)
except ValueError as e:
    if 'never built' in str(e):
        fix_parent_build(); keras.saving.load_model(path)

Prevention

When it happens

Trigger: Loading a saved model where a custom parent layer's build() instantiates children lazily (e.g. only creates them in call()); custom layers overriding build but relying on call-time construction; deserializing layers without build config.

Common situations: Keras 3 custom subclassed models with nested layers; models saved after Keras upgrades; layers whose build depends on data-dependent logic.

Related errors


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