keras-tuner icon indicating copy to clipboard operation
keras-tuner copied to clipboard

keras-tuner doesn't seem to support legacy keras (tf_keras), when using tf 2.16+ and TF_USE_LEGACY_KERAS="1"

Open juanmirocks opened this issue 8 months ago • 1 comments

Describe the bug

keras_tuner.src.errors.FatalTypeError: Expected the model-building function, or HyperModel.build() to return a valid Keras Model instance. Received: <tf_keras.src.engine.functional.Functional object at 0x7fe49809f8d0> of type <class 'tf_keras.src.engine.functional.Functional'>

To Reproduce

I get the error when trying to do a tuner.search().

I'm using tensorflow==2.18.0 with os.environ["TF_USE_LEGACY_KERAS"] = "1" and also install tf_keras==2.18.0, as described in: https://keras.io/getting_started/#tensorflow--keras-2-backwards-compatibility

I'm not ready to move to keras v3, because I'm also using tf-gnn, which does not support Keras v3 yet: https://github.com/tensorflow/gnn/blob/v1.0.3/tensorflow_gnn/docs/guide/keras_version.md#for-tensorflow-216-and-up

Expected behavior Tuner works with legacy keras (tf_keras)

Additional context I think one of the problems is:

https://github.com/keras-team/keras-tuner/blob/417e5b5e8df924d428a3c64007f3ed47bd4c7026/keras_tuner/backend/config.py#L15

It always import keras, which will import keras v3 when tensorflow 2.16+ is installed.

Would you like to help us fix it? Yes.

juanmirocks avatar Mar 27 '25 11:03 juanmirocks

Something like this should work, PR: https://github.com/keras-team/keras-tuner/pull/1040

juanmirocks avatar Mar 27 '25 16:03 juanmirocks

I also am in this situation receiving the same error. Is it possible to get this PR merged to a release? I have checked with OP's pr in my local setup and it also resolves the issue for me.

bglowney avatar Aug 29 '25 08:08 bglowney