Error AttributeError: module 'tensorflow.compat.v2.__internal__' has no attribute register_load_context_function

Hello

I have just learned deep learning models. So I tried to install the Tensorflow as per the instructions in the link:- Install TensorFlow 2

After installing, when I am doing import keras. System is giving me following errors :-1:

import keras
Traceback (most recent call last):
File “”, line 1, in
File “C:\Users\ragha\AppData\Local\Programs\Python\Python39\lib\site-packages\keras_init_.py”, line 21, in
from keras import models
File “C:\Users\ragha\AppData\Local\Programs\Python\Python39\lib\site-packages\keras\models_init_.py”, line 18, in
from keras.engine.functional import Functional
File “C:\Users\ragha\AppData\Local\Programs\Python\Python39\lib\site-packages\keras\engine\functional.py”, line 34, in
from keras.engine import training as training_lib
File “C:\Users\ragha\AppData\Local\Programs\Python\Python39\lib\site-packages\keras\engine\training.py”, line 45, in
from keras.saving.legacy import save
File “C:\Users\ragha\AppData\Local\Programs\Python\Python39\lib\site-packages\keras\saving\legacy\save.py”, line 24, in
from keras.saving.legacy.saved_model import load_context
File “C:\Users\ragha\AppData\Local\Programs\Python\Python39\lib\site-packages\keras\saving\legacy\saved_model\load_context.py”, line 68, in
tf.internal.register_load_context_function(in_load_context)
AttributeError: module ‘tensorflow.compat.v2.internal’ has no attribute ‘register_load_context_function’

So I need help in resolving this error. So that I can work on Tensor Flow models.

can you share you code here? and which verison of keras and tensorflow you are using

To use Keras, you will need to have the TensorFlow package installed. See detailed instructions.

Once TensorFlow is installed, just import Keras via:

from tensorflow import keras

Please try as suggested above and let us know if the problem continues? Thank you

Thanks for your help.

I have removed the tf conda environment completely and then installed the environment again.

I have then again installed all the libraries as mentioned in the detailed instructions link.

But after installing, I was again getting some different errors of module not found for keras. So I then installed tensorflow in the main environment too (Without conda tf environment). Post this I was able to run the tensorflow code

I found that problem is from Keras packages
so I execute these commands

pip uninstall keras
pip install tensorflow
2 Likes

I found this error. I trying to resolve it but still not resolved.
I already installed tensorflow and keras with both version have 2.12.0

Exception has occurred: ModuleNotFoundError
No module named ‘tensorflow.compat’
File “C:\Users\Nida\Desktop\With Batch Size 30\testcode.py”, line 1, in
from keras.models import load_model
ModuleNotFoundError: No module named ‘tensorflow.compat’

@NIDA_FATIMA,

Welcome to the Tensorflow Forum!

Can you rename your python (.py) script to another name and let us know?

Thank you!

Traceback (most recent call last):
File “mySite.py”, line 5, in
from keras.models import Sequential, Model, model_from_json
File “C:\Users\admin\AppData\Local\Programs\Python\Python38\lib\site-packages\keras_init_.py”, line 21, in
from keras import models
File “C:\Users\admin\AppData\Local\Programs\Python\Python38\lib\site-packages\keras\models_init_.py”, line 18, in
from keras.engine.functional import Functional
File “C:\Users\admin\AppData\Local\Programs\Python\Python38\lib\site-packages\keras\engine\functional.py”, line 26, in
from keras import backend
File “C:\Users\admin\AppData\Local\Programs\Python\Python38\lib\site-packages\keras\backend.py”, line 32, in
from keras import backend_config
File “C:\Users\admin\AppData\Local\Programs\Python\Python38\lib\site-packages\keras\backend_config.py”, line 33, in
@tf.internal.dispatch.add_dispatch_support
AttributeError: module ‘tensorflow.compat.v2.internal’ has no attribute ‘dispatch’

I found this error can any one please try to give me solution of this…

@komal_ghogare,

Welcome to the Tensorflow Forum!

It seems version mismatch between the Tensorflow and Keras that you are using.

Could you please import keras from Tensorflow and let us know?

pip uninstall keras
pip install tensorflow
from tensorflow import keras

Thank you!

1 Like

Hi, I’m having issues using transformers. I’m not familiar with it, I really need help on this.
So this is my code:

from transformers import pipeline, set_seed

import numpy as np
import textwrap
import matplotlib.pyplot as plt


from pprint import pprint

This is the error:

AttributeError                            Traceback (most recent call last)
File ~\anaconda3\envs\Asiwajuflow\lib\site-packages\transformers\utils\import_utils.py:1126, in _LazyModule._get_module(self, module_name)
   1125 try:
-> 1126     return importlib.import_module("." + module_name, self.__name__)
   1127 except Exception as e:

File ~\anaconda3\envs\Asiwajuflow\lib\importlib\__init__.py:127, in import_module(name, package)
    126         level += 1
--> 127 return _bootstrap._gcd_import(name[level:], package, level)

File <frozen importlib._bootstrap>:1030, in _gcd_import(name, package, level)

File <frozen importlib._bootstrap>:1007, in _find_and_load(name, import_)

File <frozen importlib._bootstrap>:986, in _find_and_load_unlocked(name, import_)

File <frozen importlib._bootstrap>:680, in _load_unlocked(spec)

File <frozen importlib._bootstrap_external>:850, in exec_module(self, module)

File <frozen importlib._bootstrap>:228, in _call_with_frames_removed(f, *args, **kwds)

File ~\anaconda3\envs\Asiwajuflow\lib\site-packages\transformers\pipelines\__init__.py:45
     36 from ..utils import (
     37     HUGGINGFACE_CO_RESOLVE_ENDPOINT,
     38     is_kenlm_available,
   (...)
     43     logging,
     44 )
---> 45 from .audio_classification import AudioClassificationPipeline
     46 from .automatic_speech_recognition import AutomaticSpeechRecognitionPipeline

File ~\anaconda3\envs\Asiwajuflow\lib\site-packages\transformers\pipelines\audio_classification.py:21
     20 from ..utils import add_end_docstrings, is_torch_available, logging
---> 21 from .base import PIPELINE_INIT_ARGS, Pipeline
     24 if is_torch_available():

File ~\anaconda3\envs\Asiwajuflow\lib\site-packages\transformers\pipelines\base.py:36
     35 from ..image_processing_utils import BaseImageProcessor
---> 36 from ..modelcard import ModelCard
     37 from ..models.auto.configuration_auto import AutoConfig

File ~\anaconda3\envs\Asiwajuflow\lib\site-packages\transformers\modelcard.py:48
     32 from .models.auto.modeling_auto import (
     33     MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES,
     34     MODEL_FOR_CAUSAL_LM_MAPPING_NAMES,
   (...)
     46     MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING_NAMES,
     47 )
---> 48 from .training_args import ParallelMode
     49 from .utils import (
     50     MODEL_CARD_NAME,
     51     cached_file,
   (...)
     57     logging,
     58 )

File ~\anaconda3\envs\Asiwajuflow\lib\site-packages\transformers\training_args.py:30
     29 from .debug_utils import DebugOption
---> 30 from .trainer_utils import (
     31     EvaluationStrategy,
     32     FSDPOption,
     33     HubStrategy,
     34     IntervalStrategy,
     35     SchedulerType,
     36     ShardedDDPOption,
     37 )
     38 from .utils import (
     39     ExplicitEnum,
     40     cached_property,
   (...)
     54     requires_backends,
     55 )

File ~\anaconda3\envs\Asiwajuflow\lib\site-packages\transformers\trainer_utils.py:47
     46 if is_tf_available():
---> 47     import tensorflow as tf
     50 def seed_worker(_):

File ~\anaconda3\envs\Asiwajuflow\lib\site-packages\tensorflow\__init__.py:469
    468 try:
--> 469   _keras._load()
    470 except ImportError:

File ~\anaconda3\envs\Asiwajuflow\lib\site-packages\tensorflow\python\util\lazy_loader.py:41, in LazyLoader._load(self)
     40 # Import the target module and insert it into the parent's namespace
---> 41 module = importlib.import_module(self.__name__)
     42 self._parent_module_globals[self._local_name] = module

File ~\anaconda3\envs\Asiwajuflow\lib\importlib\__init__.py:127, in import_module(name, package)
    126         level += 1
--> 127 return _bootstrap._gcd_import(name[level:], package, level)

File ~\anaconda3\envs\Asiwajuflow\lib\site-packages\keras\__init__.py:20
     15 """Implementation of the Keras API, the high-level API of TensorFlow.
     16 
     17 Detailed documentation and user guides are available at
     18 [keras.io](https://keras.io).
     19 """
---> 20 from keras import distribute
     21 from keras import models

File ~\anaconda3\envs\Asiwajuflow\lib\site-packages\keras\distribute\__init__.py:18
     15 """Keras' Distribution Strategy library."""
---> 18 from keras.distribute import sidecar_evaluator

File ~\anaconda3\envs\Asiwajuflow\lib\site-packages\keras\distribute\sidecar_evaluator.py:22
     21 from tensorflow.python.util import deprecation
---> 22 from keras.optimizers.optimizer_experimental import (
     23     optimizer as optimizer_experimental,
     24 )
     25 from tensorflow.python.util.tf_export import keras_export

File ~\anaconda3\envs\Asiwajuflow\lib\site-packages\keras\optimizers\__init__.py:25
     24 # Imports needed for deserialization.
---> 25 from keras import backend
     26 from keras.optimizers.legacy import adadelta as adadelta_legacy

File ~\anaconda3\envs\Asiwajuflow\lib\site-packages\keras\backend\__init__.py:3
      1 """AUTOGENERATED. DO NOT EDIT."""
----> 3 from keras.backend import experimental
      4 from keras.src.backend import abs

File ~\anaconda3\envs\Asiwajuflow\lib\site-packages\keras\backend\experimental\__init__.py:3
      1 """AUTOGENERATED. DO NOT EDIT."""
----> 3 from keras.src.backend import disable_tf_random_generator
      4 from keras.src.backend import enable_tf_random_generator

File ~\anaconda3\envs\Asiwajuflow\lib\site-packages\keras\src\__init__.py:21
     20 from keras.src import distribute
---> 21 from keras.src import models
     22 from keras.src.engine.input_layer import Input

File ~\anaconda3\envs\Asiwajuflow\lib\site-packages\keras\src\models\__init__.py:18
     15 """Keras models API."""
---> 18 from keras.src.engine.functional import Functional
     19 from keras.src.engine.sequential import Sequential

File ~\anaconda3\envs\Asiwajuflow\lib\site-packages\keras\src\engine\functional.py:33
     32 from keras.src.engine import node as node_module
---> 33 from keras.src.engine import training as training_lib
     34 from keras.src.engine import training_utils

File ~\anaconda3\envs\Asiwajuflow\lib\site-packages\keras\src\engine\training.py:41
     40 from keras.src.saving import pickle_utils
---> 41 from keras.src.saving import saving_api
     42 from keras.src.saving import saving_lib

File ~\anaconda3\envs\Asiwajuflow\lib\site-packages\keras\src\saving\saving_api.py:25
     24 from keras.src.saving import saving_lib
---> 25 from keras.src.saving.legacy import save as legacy_sm_saving_lib
     26 from keras.src.utils import io_utils

File ~\anaconda3\envs\Asiwajuflow\lib\site-packages\keras\src\saving\legacy\save.py:27
     26 from keras.src.saving.legacy.saved_model import load as saved_model_load
---> 27 from keras.src.saving.legacy.saved_model import load_context
     28 from keras.src.saving.legacy.saved_model import save as saved_model_save

File ~\anaconda3\envs\Asiwajuflow\lib\site-packages\keras\src\saving\legacy\saved_model\load_context.py:68
     65     return _load_context.in_load_context()
---> 68 tf.__internal__.register_load_context_function(in_load_context)

AttributeError: module 'tensorflow.compat.v2.__internal__' has no attribute 'register_load_context_function'

The above exception was the direct cause of the following exception:

RuntimeError                              Traceback (most recent call last)
Cell In[1], line 1
----> 1 from transformers import pipeline, set_seed
      3 import numpy as np
      4 import textwrap

File <frozen importlib._bootstrap>:1055, in _handle_fromlist(module, fromlist, import_, recursive)

File ~\anaconda3\envs\Asiwajuflow\lib\site-packages\transformers\utils\import_utils.py:1116, in _LazyModule.__getattr__(self, name)
   1114     value = self._get_module(name)
   1115 elif name in self._class_to_module.keys():
-> 1116     module = self._get_module(self._class_to_module[name])
   1117     value = getattr(module, name)
   1118 else:

File ~\anaconda3\envs\Asiwajuflow\lib\site-packages\transformers\utils\import_utils.py:1128, in _LazyModule._get_module(self, module_name)
   1126     return importlib.import_module("." + module_name, self.__name__)
   1127 except Exception as e:
-> 1128     raise RuntimeError(
   1129         f"Failed to import {self.__name__}.{module_name} because of the following error (look up to see its"
   1130         f" traceback):\n{e}"
   1131     ) from e

RuntimeError: Failed to import transformers.pipelines because of the following error (look up to see its traceback):
module 'tensorflow.compat.v2.__internal__' has no attribute 'register_load_context_function'


1 Like

Did you find any solution for it

I am getting this error:
RuntimeError: Failed to import transformers.models.distilbert.modeling_tf_distilbert because of the following error (look up to see its traceback):
module ‘tensorflow._api.v2.compat.v2.internal’ has no attribute ‘register_load_context_function’

I can see that this is something that has occurred to others as well. Looking at other replies, I also tried uninstalling keras, and importing it through tensorflow, I am still getting these errors. Please suggest some way to go about this. Thanks in advance !