{"record":{"id":"44b8eed25fe7225f","repo":"keras-team/keras","slug":"layer-count-mismatch-when-loading-weights-from-fil","errorCode":null,"errorMessage":"Layer count mismatch when loading weights from file. Model expected {len(filtered_layers)} layers, found {len(layer_names)} saved layers.","messagePattern":"Layer count mismatch when loading weights from file\\. Model expected (.+?) layers, found (.+?) saved layers\\.","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"keras/src/legacy/saving/legacy_h5_format.py","lineNumber":375,"sourceCode":"\n    filtered_layers = []\n    for layer in model.layers:\n        weights = _legacy_weights(layer)\n        if weights:\n            filtered_layers.append(layer)\n\n    layer_names = load_attributes_from_hdf5_group(group, \"layer_names\")\n    filtered_layer_names = []\n    for name in layer_names:\n        layer_group = safe_get_h5_group(group, name)\n        weight_names = load_attributes_from_hdf5_group(\n            layer_group, \"weight_names\"\n        )\n        if weight_names:\n            filtered_layer_names.append(name)\n    layer_names = filtered_layer_names\n    if len(layer_names) != len(filtered_layers):\n        raise ValueError(\n            \"Layer count mismatch when loading weights from file. \"\n            f\"Model expected {len(filtered_layers)} layers, found \"\n            f\"{len(layer_names)} saved layers.\"\n        )\n\n    for k, name in enumerate(layer_names):\n        layer_group = safe_get_h5_group(group, name)\n        layer = filtered_layers[k]\n        symbolic_weights = _legacy_weights(layer)\n        weight_values = load_subset_weights_from_hdf5_group(layer_group)\n        if len(weight_values) != len(symbolic_weights):\n            raise ValueError(\n                f\"Weight count mismatch for layer #{k} (named {layer.name} in \"\n                f\"the current model, {name} in the save file). \"\n                f\"Layer expects {len(symbolic_weights)} weight(s). Received \"\n                f\"{len(weight_values)} saved weight(s)\"\n            )\n        _set_weights(","sourceCodeStart":357,"sourceCodeEnd":393,"githubUrl":"https://github.com/keras-team/keras/blob/7a34a03db60bf60042242d6a556fc3be119046a5/keras/src/legacy/saving/legacy_h5_format.py#L357-L393","documentation":"load_weights_from_hdf5_group matches saved layer groups to the model's layers that have weights. After filtering both sides to weight-bearing layers, a count mismatch raises this ValueError: the file and the model disagree on how many weight-bearing layers exist.","triggerScenarios":"model.load_weights('w.h5') where the file was saved from a different architecture: layers added/removed, or layers switched between weight-bearing and weightless, loaded with by_name=False onto a mismatched model.","commonSituations":"Evolving a model architecture between training runs; loading old checkpoints into a refactored model; loading a Sequential checkpoint into a Functional model with extra layers.","solutions":["Load with by_name=True so layers are matched by name instead of by order","Make the architecture match the checkpoint exactly before load_weights","Re-save the weights from the exact current architecture, or regenerate the checkpoint"],"exampleFix":"# before\nmodel.load_weights('old.h5')\n# after\nmodel.load_weights('old.h5', by_name=True)","handlingStrategy":"validation","validationCode":"file_layers = len([g for g in f['layer_weights'] if 'weight_names' in g.attrs and len(g.attrs['weight_names'])])\nmodel_layers = len([l for l in model.layers if l.weights])\nassert file_layers == model_layers, (file_layers, model_layers)","typeGuard":null,"tryCatchPattern":"try:\n    model.load_weights(p)\nexcept ValueError as e:\n    if 'Layer count mismatch' not in str(e):\n        raise\n    model.load_weights(p, by_name=True)","preventionTips":["Load checkpoints with by_name=True when architecture may drift","Version checkpoints together with the code that built the model"],"tags":["keras","loading","hdf5","weights","architecture-mismatch"],"backgroundTag":"checkpoint-architecture-mismatch","analyzedSha":"7a34a03db60bf60042242d6a556fc3be119046a5","analyzedAt":"2026-08-25T21:25:25.994Z","schemaVersion":2},"datasetVersion":"2026-08-26T02:17:13.382Z"}