Repository: keras-team/keras
Issue category: Bug Report

Issue:
BUG in load_weights_from_hdf5_group_by_name
https://github.com/keras-team/keras/blob/5d36ee1f219bb650dd108c35b257c783cd034ffd/keras/src/legacy/saving/legacy_h5_format.py#L521-L525

model.trainable_weights + model.non_trainable_weights references all weights instead of top-level


Hints:

Patch:
diff --git a/keras/src/legacy/saving/legacy_h5_format.py b/keras/src/legacy/saving/legacy_h5_format.py
index 0e284f5a9db..cc5ef63d97a 100644
--- a/keras/src/legacy/saving/legacy_h5_format.py
+++ b/keras/src/legacy/saving/legacy_h5_format.py
@@ -519,7 +519,7 @@ def load_weights_from_hdf5_group_by_name(f, model, skip_mismatch=False):
             )
 
     if "top_level_model_weights" in f:
-        symbolic_weights = model.trainable_weights + model.non_trainable_weights
+        symbolic_weights = model._trainable_variables + model._non_trainable_variables
         weight_values = load_subset_weights_from_hdf5_group(
             f["top_level_model_weights"]
         )


Test patch:
diff --git a/keras/src/legacy/saving/legacy_h5_format_test.py b/keras/src/legacy/saving/legacy_h5_format_test.py
index 6909e79a4ca..52d6ad11a9c 100644
--- a/keras/src/legacy/saving/legacy_h5_format_test.py
+++ b/keras/src/legacy/saving/legacy_h5_format_test.py
@@ -53,8 +53,21 @@ def __init__(self, **kwargs):
             self.dense_1 = keras.layers.Dense(3, activation="relu")
             self.dense_2 = keras.layers.Dense(1, activation="sigmoid")
 
+            # top_level_model_weights
+            self.bias = self.add_weight(
+                name="bias",
+                shape=[1],
+                trainable=True,
+                initializer=keras.initializers.Zeros(),
+            )
+
         def call(self, x):
-            return self.dense_2(self.dense_1(x))
+            x = self.dense_1(x)
+            x = self.dense_2(x)
+
+            # top_level_model_weights
+            x += ops.cast(self.bias, x.dtype)
+
 
     model = MyModel()
     model(np.random.random((2, 3)))