Fix lazy init to stop hiding errors in import #14124
Merged
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.
What does this PR do?
The problem
As was pointed out in #13007 and reported more recently in the internal slack, the lazy init used in Transformers hide the error messages one get at import time. A reproducer showed is:
pyenv virtualenv 3.8.9 test-bug pyenv activate 3.8.9 pip install datasets huggingface_hub pip install torch transformers==4.9.2 python -c "from transformers import pipeline"
This will only return
ImportError: cannot import name 'pipeline' from 'transformers'
with no other information. The underlying error comes from a mismatch between Datasets and huggingface-hub in this env (for all details, pipeline tries to import AutoModel which tries to import rag which tries to import Dataset), but Transformers hides it. If one doespython -c "from datasets import Dataset"
one will see the full error message
That particular problem is fixed in later versions of Transformers since we decoupled the auto module from the others, but it's still a general bug in the lazy init.
The solution
The underlying problem comes from the fact that there are some errors being silently ignored in the import machinery of Python. @aphedges gave a preliminary report in #13007 which helped me pinpoint the problem to the
_get_module
private function which errors when we try to import thepipelines
module in the env mentioned above, but that error is then discarded and no good error message is sent.Changing that error to a
RuntimeError
sovles the issue, and with the modifications suggested in this PR, the linepython -c "from transformers import pipeline"
then gives the more informative
Fixes #13007