Fix deserialization issue with custom_loss function while reloading #20820
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Fix deserialization issue with
custom_loss
function while reloading saved models of <3.7v.Suppose for a model with custom loss function and saved in 3.6V, to reload in newer version we are facing an issue due to changes in appending the package name to loss function from versions 3.7v onwards.
One Workaround is to pass these custom objects explicitly to
load_model
. The reason this works is mentioned below.When we pass
custom_objects
explicitly toload_model
, For example in this case, it will be duplicated and custom_objects will become double like below,with Package name and without function names:{'MyLayers': <class '__main__.CustomLayer'>, 'MyLayers>CustomLayer': <class '__main__.CustomLayer'>, 'custom_fn': <function custom_fn at 0x0000029D776D440>, 'custom_fn>custom_fn': <function custom_fn at 0x0000029D776D440>, 'custom_fn>my_loss_fn': <function my_loss_fn at 0x0000029DA6E2C00>, 'my_loss_fn': <function my_loss_fn at 0x0000029DA6E2C00>}
This can be a workaround for loading saved model in 3.6V with custom_loss in Versions >3.7. If it is OK then documentation needs to be updated accordingly.
Alternatively this PR will resolve this issue until Keras 3.6 v become inactive for use.
Might Fix #20806