Skip to content

Do not let a broken TensorFlow install break the Unsloth import - #8124

Merged
danielhanchen merged 19 commits into
unslothai:mainfrom
danielhanchen:fix/broken-tf-breaks-import
Aug 9, 2026
Merged

danielhanchen merged 19 commits into
unslothai:mainfrom
danielhanchen:fix/broken-tf-breaks-import

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

What happens today

Transformers 4.x imports TensorFlow and Flax merely because they are installed. transformers/image_transforms.py:

if is_tf_available():
    import tensorflow as tf

and that module is reached from processing_utils, which is on Unsloth's own import path (unsloth_zoo/temporary_patches/utils.py probes from 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.ipynb on 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, because google.protobuf.runtime_version only exists from protobuf 5.27:

ImportError: cannot import name 'runtime_version' from 'google.protobuf'

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_TF and USE_FLAX are set to "0" at the top of unsloth/__init__.py.

  • setdefault, so an explicit USE_TF=1 still wins for anyone who wants those classes in the same process.
  • Only when transformers is not already in sys.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.
  • Transformers 5.x dropped both backends and ignores the variables, so this is a no-op there.

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 make import unsloth fail through a backend Unsloth does not use.

Tests

tests/test_broken_tf_does_not_break_import.py, five of them:

  • the opt-out exists and sits above every transformers import in the file, which is the whole contract
  • it uses setdefault, not assignment, so a user's explicit choice survives
  • the guard is skipped once transformers is loaded
  • Transformers really does read USE_TF from the environment, checked in a subprocess against whichever version is installed, for both 0 and 1. Without that half the opt-out would be inert.

Three of the five fail on main. 1475 passed, 187 skipped across tests/version_compat/; the single failure there is test_sft_trains_on_cpu, which is unrelated and fixed separately in #8123.

@danielhanchen

Copy link
Copy Markdown
Member Author

Verified on the machine that produced the failure, not just in tests.

Same notebook (Qwen2.5_Coder_(1.5B)-Tool_Calling.ipynb), same Colab T4 lane, same unpatched install cell, run twice:

run result
as shipped CONFIRMED_REGRESSION at the first from unsloth import ..., ImportError: cannot import name 'runtime_version' from 'google.protobuf'
with USE_TF=0 / USE_FLAX=0 set before any import PASS

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 unsloth/__init__.py.

Worth being precise about the scope: this does not repair the protobuf downgrade, which is still there and still prints its twenty which is incompatible lines. It stops that downgrade from being able to break import unsloth through a backend Unsloth never uses. The pin itself belongs in unslothai/notebooks and I will raise it there separately.

danielhanchen and others added 3 commits August 8, 2026 03:21
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.
@danielhanchen
danielhanchen force-pushed the fix/broken-tf-breaks-import branch from cc48eda to e10918f Compare August 8, 2026 03:21
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 8, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Delightful!

Reviewed commit: e10918fcaf

ℹ️ 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".

chatgpt-codex-connector[bot]

This comment was marked as resolved.

…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.
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Can't wait for the next one!

Reviewed commit: f155eedda2

ℹ️ 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".

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

danielhanchen and others added 2 commits August 9, 2026 02:59
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.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

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.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…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.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 9, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 9, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 9, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 9, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 9, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 9, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 9, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Aug 9, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread unsloth/__init__.py
Comment on lines +115 to +116
if getattr(_import_utils, _flag, False):
setattr(_import_utils, _flag, False)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Aug 9, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 9, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🚀

Reviewed commit: 8258c8b84a

ℹ️ 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".

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread unsloth/__init__.py
continue
if any(os.environ.get(_v, "").upper() in _TRUE for _v in _opt_ins):
continue
os.environ[_var] = "0"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Can't wait for the next one!

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".

@danielhanchen
danielhanchen merged commit 57339b4 into unslothai:main Aug 9, 2026
47 of 51 checks passed
danielhanchen added a commit that referenced this pull request Aug 9, 2026
* 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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant