Repository navigation
Do not let a broken TensorFlow install break the Unsloth import - #8124
Conversation
|
Verified on the machine that produced the failure, not just in tests. Same notebook (
Nothing else changed between the two, so the opt-out is the whole difference. The second run reproduces exactly what this PR does from inside Worth being precise about the scope: this does not repair the protobuf downgrade, which is still there and still prints its twenty |
Transformers 4.x imports TensorFlow and Flax merely because they are installed: image_transforms.py does if is_tf_available(): import tensorflow and that module is reached from processing_utils, which is on Unsloth's own import path. So a broken optional backend breaks Unsloth, which uses neither. Hit on Colab running Qwen2.5_Coder_(1.5B)-Tool_Calling. The install cell moves protobuf 5.29.6 down to 3.20.3, Colab's preinstalled TensorFlow then raises ImportError: cannot import name 'runtime_version' from 'google.protobuf' and that is what the user sees at the first `from unsloth import ...`, with nothing in the traceback explaining why a torch library is importing TensorFlow. USE_TF and USE_FLAX are set to 0 with setdefault, so an explicit choice still wins, and only when transformers has not already been imported, since it reads them once at import and an already-loaded transformers has settled the question. 5.x dropped both backends and ignores the variables.
cc48eda to
e10918f
Compare
|
Codex Review: Didn't find any major issues. Delightful! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
…ported The USE_TF/USE_FLAX opt-out only lands when Transformers has not been imported yet. Once it has, the variables are spent, but the answer they feed is not: Transformers decided _tf_available from find_spec plus the installed version, without importing TensorFlow, so a broken backend is still waiting to load in image_transforms on Unsloth's own import path. Clear the cached flags in that case, unless the backend is already imported or the user opted in with USE_TF / FORCE_TF_AVAILABLE, and tolerate their absence on Transformers 5.x.
|
Codex Review: Didn't find any major issues. Can't wait for the next one! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
Transformers reads USE_TF, FORCE_TF_AVAILABLE and USE_FLAX once, at its own import, and keeps the answer in module constants. The already-imported branch consulted only the live os.environ, so a caller that set one of those, let Transformers consume it, then put the environment back -- a patch.dict around the import, a launcher that tidies up after itself -- looked like a caller who never opted in, and the flag was cleared despite Transformers having honoured it. Read what Transformers actually used, alongside the environment. Note the spelling: the variable is USE_FLAX, the constant it lands in is USE_JAX, so looking for a cached USE_FLAX would find nothing and keep the bug. Only true values count. All three constants default to "AUTO" when unset, and accepting AUTO would preserve every flag on every machine that never set anything, turning the guard into a no-op that still looks like a fix.
setdefault keeps whatever is already in the environment, and "whatever is already there" includes AUTO. Transformers reads AUTO as "enable if installed", which is exactly the state this guard exists to prevent, so a launcher or notebook that mirrors Transformers' own defaults into the environment disabled the guard without anyone noticing. Verified with a broken TensorFlow on the path: USE_TF=AUTO plus the old setdefault leaves _tf_available True, and the import Unsloth was protecting is reachable again. Overwrite unless the value is a real opt-in, which also makes this branch agree with the already-imported one below: same true-value set, same FORCE_TF_AVAILABLE handling, same hands-off rule for a backend already in sys.modules. Anything Transformers does not read as true already means off, so writing "0" over it changes nothing else. The two tests that pinned the old spelling now pin the behaviour instead. Asserting "the source says setdefault" tracked how the guarantee happened to be written rather than the guarantee, and setdefault was not even a correct way to get it.
…modules Python publishes a module object before running its body, so a thread part-way through `import transformers` makes `"transformers" in sys.modules` true while `transformers.utils.import_utils` does not exist yet and has not read the environment. The else branch then found no cached flag to clear, did nothing, and Transformers went on to set `_tf_available = True`. Write the variables in that branch as well: inert once Transformers has read them, decisive inside the window. Also drop USE_TORCH from the subprocess test environment. Transformers gates `_tf_available` on `USE_TORCH not in ENV_VARS_TRUE_VALUES`, so a runner with USE_TORCH=1 made the "BEFORE True" cases fail for an unrelated reason.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 0709857829
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if getattr(_import_utils, _flag, False): | ||
| setattr(_import_utils, _flag, False) |
There was a problem hiding this comment.
Prevent the availability computation from overwriting the opt-out
When another thread is inside Transformers 4.57.6's availability calculation, _tf_available already exists as False before find_spec("tensorflow") and metadata lookup later assign it True. If Unsloth runs during either lookup, this condition leaves the flag false and changes USE_TF, but the importing thread has already evaluated the USE_TF branch and subsequently overwrites _tf_available with True, so the broken TensorFlow can still be imported. Fresh evidence beyond the prior review is this later window where the flag exists but its final assignment is still pending; the new constant write only covers the earlier pre-branch window.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
The window is described accurately, but there is nothing to do about it, so this is not a change I want to make.
Reading 4.57.6: _tf_available = False (line 260), the USE_TF branch is evaluated (line 264), then _tf_available = importlib.util.find_spec("tensorflow") is not None (line 266). Landing between 264 and 266 means the branch is spent and the flag is about to be assigned by the other thread. Every lever is gone: the environment was read at line 102, the constant was read at 264, and the flag we write is overwritten microseconds later by an assignment already in flight. The only remedies are blocking until the other thread's import finishes, which deadlocks from module scope, or intercepting __setattr__ on Transformers' module object, which permanently changes third-party module semantics and would also swallow a legitimate FORCE_TF_AVAILABLE or a later re-enable. Neither is worth a two-instruction window.
That is why the previous round's fix stops where it does: the pre-branch window is closable, this one is not, and no remedy was proposed here either. Note also that the thread doing the importing loses on its own terms - it is the one that goes on to load image_transforms against the broken TensorFlow - so this is not a hole Unsloth opens, only one it cannot close from the outside.
The guard is best effort against a concurrent import by construction, and the comment in the else branch already says so.
|
Codex Review: Didn't find any major issues. 🚀 Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 7b89fe3368
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| continue | ||
| if any(os.environ.get(_v, "").upper() in _TRUE for _v in _opt_ins): | ||
| continue | ||
| os.environ[_var] = "0" |
There was a problem hiding this comment.
Preserve
from_tf=True checkpoint loads
When a user imports Unsloth normally and then calls FastLlamaModel.from_pretrained(..., from_tf=True) with a healthy TensorFlow installation, this assignment disables TensorFlow before Transformers initializes. That flow is supported in unsloth/models/llama.py, which explicitly handles from_tf during prefetch and forwards it to AutoModelForCausalLM.from_pretrained; however, Transformers 4.x only publishes its TF model classes when is_tf_available() was true at import time, so TF2 .h5 conversion subsequently fails unless the user knew to set an environment variable or import TensorFlow before Unsloth. Preserve or explicitly re-enable the backend for this conversion path rather than permanently opting it out.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
The behaviour change is real, but it is the deliberate trade this PR makes, and the remedy suggested here does not work.
Re-enabling at conversion time is not possible. Transformers builds _import_structure from is_tf_available() at its own import, so the TF names are already bound to _LazyModule placeholders by the time from_pretrained runs. Verified on 4.57.6 with USE_TF=0: after import, setting import_utils._tf_available = True and then getattr(transformers, "TFMistralForCausalLM") still returns _LazyModule.__getattr__.<locals>.Placeholder, which raises ImportError: TFMistralForCausalLM requires the TensorFlow library but it was not found in your environment on instantiation - the exact call load_tf2_checkpoint_in_pytorch_model makes. So the decision can only be taken before transformers is imported, which is where this guard already is.
Preserving the backend unconditionally is the bug being fixed: a broken TensorFlow on the path makes processing_utils -> image_transforms fail, so every from unsloth import ... on that Colab dies. Weighing an import that breaks for everyone with a broken TF against a TF2 .h5 conversion, the guard already keeps three ways to opt back in, all honoured on this path: USE_TF=1, FORCE_TF_AVAILABLE=1, or importing tensorflow before Unsloth. The comment at line 35 states the trade in those terms, and the "already imported backend" skip exists precisely so a working from_tf = True flow is not stranded.
Worth noting the scope too: from_tf in _utils.py only widens the prefetch allow-patterns to keep *.h5, and Transformers 4.57.6 ships no TF class for Llama, Qwen, Gemma, Phi or Granite, so there is no reachable conversion for most of what Unsloth loads. Leaving as is.
|
Codex Review: Didn't find any major issues. Can't wait for the next one! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
* Do not let a broken TensorFlow install break the Unsloth import Transformers 4.x imports TensorFlow and Flax merely because they are installed: image_transforms.py does if is_tf_available(): import tensorflow and that module is reached from processing_utils, which is on Unsloth's own import path. So a broken optional backend breaks Unsloth, which uses neither. Hit on Colab running Qwen2.5_Coder_(1.5B)-Tool_Calling. The install cell moves protobuf 5.29.6 down to 3.20.3, Colab's preinstalled TensorFlow then raises ImportError: cannot import name 'runtime_version' from 'google.protobuf' and that is what the user sees at the first `from unsloth import ...`, with nothing in the traceback explaining why a torch library is importing TensorFlow. USE_TF and USE_FLAX are set to 0 with setdefault, so an explicit choice still wins, and only when transformers has not already been imported, since it reads them once at import and an already-loaded transformers has settled the question. 5.x dropped both backends and ignores the variables. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Shorten the TF opt-out comments * Tighten the TF opt-out comments * Clear the cached TF/Flax availability when Transformers is already imported The USE_TF/USE_FLAX opt-out only lands when Transformers has not been imported yet. Once it has, the variables are spent, but the answer they feed is not: Transformers decided _tf_available from find_spec plus the installed version, without importing TensorFlow, so a broken backend is still waiting to load in image_transforms on Unsloth's own import path. Clear the cached flags in that case, unless the backend is already imported or the user opted in with USE_TF / FORCE_TF_AVAILABLE, and tolerate their absence on Transformers 5.x. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Keep an already imported backend when Transformers loads later * Honor a backend opt-in Transformers already consumed Transformers reads USE_TF, FORCE_TF_AVAILABLE and USE_FLAX once, at its own import, and keeps the answer in module constants. The already-imported branch consulted only the live os.environ, so a caller that set one of those, let Transformers consume it, then put the environment back -- a patch.dict around the import, a launcher that tidies up after itself -- looked like a caller who never opted in, and the flag was cleared despite Transformers having honoured it. Read what Transformers actually used, alongside the environment. Note the spelling: the variable is USE_FLAX, the constant it lands in is USE_JAX, so looking for a cached USE_FLAX would find nothing and keep the bug. Only true values count. All three constants default to "AUTO" when unset, and accepting AUTO would preserve every flag on every machine that never set anything, turning the guard into a no-op that still looks like a fix. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Treat AUTO as unset when opting the backends out setdefault keeps whatever is already in the environment, and "whatever is already there" includes AUTO. Transformers reads AUTO as "enable if installed", which is exactly the state this guard exists to prevent, so a launcher or notebook that mirrors Transformers' own defaults into the environment disabled the guard without anyone noticing. Verified with a broken TensorFlow on the path: USE_TF=AUTO plus the old setdefault leaves _tf_available True, and the import Unsloth was protecting is reachable again. Overwrite unless the value is a real opt-in, which also makes this branch agree with the already-imported one below: same true-value set, same FORCE_TF_AVAILABLE handling, same hands-off rule for a backend already in sys.modules. Anything Transformers does not read as true already means off, so writing "0" over it changes nothing else. The two tests that pinned the old spelling now pin the behaviour instead. Asserting "the source says setdefault" tracked how the guarantee happened to be written rather than the guarantee, and setdefault was not even a correct way to get it. * Write the opt-out variables even when Transformers is already in sys.modules Python publishes a module object before running its body, so a thread part-way through `import transformers` makes `"transformers" in sys.modules` true while `transformers.utils.import_utils` does not exist yet and has not read the environment. The else branch then found no cached flag to clear, did nothing, and Transformers went on to set `_tf_available = True`. Write the variables in that branch as well: inert once Transformers has read them, decisive inside the window. Also drop USE_TORCH from the subprocess test environment. Transformers gates `_tf_available` on `USE_TORCH not in ENV_VARS_TRUE_VALUES`, so a runner with USE_TORCH=1 made the "BEFORE True" cases fail for an unrelated reason. * Overwrite the cached backend constants while import_utils is mid-body * Skip the cached flag probe on a runner without transformers * Tighten the backend opt-out comments * Trim the backend opt-out comments further * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Tighten comments in the TensorFlow opt-out guard --------- Co-authored-by: danielhanchen <[email protected]> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
What happens today
Transformers 4.x imports TensorFlow and Flax merely because they are installed.
transformers/image_transforms.py:and that module is reached from
processing_utils, which is on Unsloth's own import path (unsloth_zoo/temporary_patches/utils.pyprobesfrom transformers.processing_utils import Unpack). So a broken optional backend breaks Unsloth, which uses neither.Hit while running
Qwen2.5_Coder_(1.5B)-Tool_Calling.ipynbon a Colab T4. Colab ships protobuf 5.29.6 and TensorFlow preinstalled; the notebook's install cell moves protobuf down to 3.20.3 (pip prints twenty "which is incompatible" lines on the way), and TF then cannot import, becausegoogle.protobuf.runtime_versiononly exists from protobuf 5.27:That is what the user sees at the first
from unsloth import .... Nothing in the traceback explains why a torch library is importing TensorFlow, and the notebook dies on its first real cell.The change
USE_TFandUSE_FLAXare set to"0"at the top ofunsloth/__init__.py.setdefault, so an explicitUSE_TF=1still wins for anyone who wants those classes in the same process.transformersis not already insys.modules. Transformers reads these once at import, so this only bites if it lands first, which is the documented order ("import Unsloth before Transformers"). If it does not land first there is nothing to fix: an already-imported Transformers has settled the question, and rewriting the variable would only mislead.The protobuf downgrade in that notebook is a separate question for
unslothai/notebooks, and worth asking on its own. But no notebook pin should be able to makeimport unslothfail through a backend Unsloth does not use.Tests
tests/test_broken_tf_does_not_break_import.py, five of them:transformersimport in the file, which is the whole contractsetdefault, not assignment, so a user's explicit choice survivestransformersis loadedUSE_TFfrom the environment, checked in a subprocess against whichever version is installed, for both0and1. Without that half the opt-out would be inert.Three of the five fail on
main.1475 passed, 187 skippedacrosstests/version_compat/; the single failure there istest_sft_trains_on_cpu, which is unrelated and fixed separately in #8123.