keras-team/keras · error · ValueError

Weight count mismatch for top-level weights when loading…

Error message

Weight count mismatch for top-level weights when loading weights from file. Model expects {len(symbolic_weights)} top-level weight(s). Received {len(weight_values)} saved top-level weight(s)

What it means

Error "Weight count mismatch for top-level weights when loading weights from file. Model expects {len(symbolic_weights)} top-level weight(s). Received {len(weight_values)} saved top-level weight(s)" thrown in keras-team/keras.

Solutions

  1. Ensure the saved H5 file was produced from the same model architecture (same number of top-level weights)
  2. Pass by_name=True to load weights layer-by-layer instead of top-level
  3. Pass skip_mismatch=True to skip mismatched top-level weights with a warning (partial loading)
  4. Re-save the weights from the current model to regenerate a matching file
Defensive patterns

Strategy: fallback

When it happens

Trigger: Thrown at keras/src/legacy/saving/legacy_h5_format.py:412 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/7fe1726b9df81fb4. Report an issue: GitHub.

Appendix: source

Thrown at keras/src/legacy/saving/legacy_h5_format.py:412

            layer,
            symbolic_weights,
            weight_values,
            skip_mismatch=skip_mismatch,
            name=f"layer #{k} (named {layer.name})",
        )

    if "top_level_model_weights" in group:
        symbolic_weights = list(
            # model.weights
            v
            for v in model._trainable_variables + model._non_trainable_variables
            if v in model.weights
        )
        weight_values = load_subset_weights_from_hdf5_group(
            safe_get_h5_group(group, "top_level_model_weights")
        )
        if len(weight_values) != len(symbolic_weights):
            raise ValueError(
                "Weight count mismatch for top-level weights when loading "
                "weights from file. "
                f"Model expects {len(symbolic_weights)} top-level weight(s). "
                f"Received {len(weight_values)} saved top-level weight(s)"
            )
        _set_weights(
            model,
            symbolic_weights,
            weight_values,
            skip_mismatch=skip_mismatch,
            name="top-level model",
        )


def _set_weights(
    instance, symbolic_weights, weight_values, name, skip_mismatch=False
):
    """Safely set weights into a model or a layer.

View on GitHub (pinned to 7a34a03db6)