Skip to content

Commit 0e43f09

Browse files
nkovela1mattdangerw
authored andcommitted
Add in-place modification of file keys for backwards compatibility (keras-team#1369)
1 parent ddfca77 commit 0e43f09

File tree

1 file changed

+16
-0
lines changed

1 file changed

+16
-0
lines changed

keras_nlp/utils/preset_utils.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,9 @@
1717
import json
1818
import os
1919

20+
import h5py
21+
22+
from keras_nlp.backend import config as backend_config
2023
from keras_nlp.backend import keras
2124

2225
try:
@@ -171,6 +174,19 @@ def legacy_load_weights(layer, weights_path):
171174
functional_cls = cls
172175
property = functional_cls._layer_checkpoint_dependencies
173176
functional_cls._layer_checkpoint_dependencies = []
177+
178+
from keras_nlp.models.backbone import Backbone
179+
180+
if not backend_config.keras_3() and isinstance(layer, Backbone):
181+
# Hacky fix for Keras 2 backwards compatibility. Keras 2 traverses loading
182+
# weights in the reverse order, causing a naming mismatch when loading
183+
# Kaggle weights saved from Keras 3.
184+
f = h5py.File(weights_path, "r+")
185+
if "_token_embedding" in f.keys():
186+
data = f["_token_embedding"]
187+
f["token_embedding"] = data
188+
f.close()
189+
174190
layer.load_weights(weights_path)
175191
functional_cls._layer_checkpoint_dependencies = property
176192

0 commit comments

Comments
 (0)