Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4791 pages
AI and LLM integration

ImportError for TFTrainer and other TF classes in Hugging Face transformers

Your error

ImportError: cannot import name 'TFTrainer' from 'transformers'2 more lines it can show

Fix it fast

Most common cause, 1 of 3

transformers 4.37 or later no longer ships TFTrainer

Drop TFTrainer and train the TF model the Keras way: compile it and call fit() on a tf.data dataset.

Fix
from tensorflow.keras.optimizers import Adam
from transformers import AutoTokenizer, TFAutoModelForSequenceClassification

tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
model = TFAutoModelForSequenceClassification.from_pretrained("bert-base-cased")
tf_dataset = model.prepare_tf_dataset(dataset["train"], batch_size=16, shuffle=True, tokenizer=tokenizer)
model.compile(optimizer=Adam(3e-5))  # no loss argument needed
model.fit(tf_dataset, epochs=3)
Did this fix it?
Full steps for this cause: check, fix, verify

Short answer

ImportError: cannot import name 'TFTrainer' from 'transformers' means the class is gone. TFTrainer was removed in 4.37.0 after a deprecation warning, and transformers 5.0 removed TensorFlow support completely, so TFAutoModel classes fail too. Rewrite the training with Trainer and a PyTorch model on 5.x, or pin transformers 4.57.6 and train TF models with Keras fit().

  • Applies to transformers 5.23.0 (PyTorch only), transformers 4.57.6 (last release with TensorFlow classes), Python 3.11 and later
  • Updated
  • By Maaz Zindani, Senior Software Engineer

Which cause do you have?

Print which transformers release the failing script or notebook actually imports. Between 4.37 and 4.57 only TFTrainer is missing; from 5.0 on, nothing whose name starts with TF exists.

Run this first
python -c "import transformers; print(transformers.__version__)"

Then find the line you see in this list and open its fix:

  1. 1transformers 4.37 or later no longer ships TFTrainerThe version is 4.37.0 to 4.57.x, and from transformers import TFAutoModelForSequenceClassification still works
  2. 2transformers 5.x removed TensorFlow altogetherThe version starts with 5, and every import with a TF prefix fails, not only TFTrainer
  3. 3You pinned 4.x for TF and now Keras 3 is rejectedAfter installing transformers 4.57.6 the import works, but loading a TF model raises the Keras 3 ValueError

What does the error look like?

  • ImportError: cannot import name 'TFTrainer' from 'transformers'
  • ImportError: cannot import name 'TFAutoModelForSequenceClassification' from 'transformers'
  • ValueError: Your currently installed version of Keras is Keras 3, but this is not yet supported in Transformers. Please install the backwards-compatible tf-keras package with `pip install tf-keras`.

Cause 1 of 3

transformers 4.37 or later no longer ships TFTrainer

You seeThe version is 4.37.0 to 4.57.x, and from transformers import TFAutoModelForSequenceClassification still works

Check

On transformers 4.37 and newer, cannot import name 'TFTrainer' appears because the 4.37.0 release purged the class. Older releases had already warned that TFTrainer was deprecated and told users to call fit() and predict() on the Keras model directly. Tutorials and notebooks written before that still import it.

Check
grep -rn "TFTrainer" --include=*.py --include=*.ipynb .

Fix

Drop TFTrainer and train the TF model the Keras way: compile it and call fit() on a tf.data dataset. The model picks a task loss by default, so compile() needs no loss argument.

Fix
from tensorflow.keras.optimizers import Adam
from transformers import AutoTokenizer, TFAutoModelForSequenceClassification

tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
model = TFAutoModelForSequenceClassification.from_pretrained("bert-base-cased")
tf_dataset = model.prepare_tf_dataset(dataset["train"], batch_size=16, shuffle=True, tokenizer=tokenizer)
model.compile(optimizer=Adam(3e-5))  # no loss argument needed
model.fit(tf_dataset, epochs=3)

Verify

Training starts and Keras prints a loss value per epoch.

Verify
python train.py

Confirmed by github.com

Did this fix it?

Cause 2 of 3

transformers 5.x removed TensorFlow altogether

You seeThe version starts with 5, and every import with a TF prefix fails, not only TFTrainer

Check

Since 5.0 the library supports only PyTorch: the v5 migration guide lists the removal of the TensorFlow and Jax parts as a library-wide change. A fresh pip install or a notebook image that upgraded to 5.x therefore breaks any TF training script, whatever TensorFlow version is installed.

Check
pip show transformers torch tensorflow 2>/dev/null | grep -E "^(Name|Version)"

Fix

Port the script to PyTorch classes and the Trainer API. For example, TFAutoModelForSequenceClassification becomes AutoModelForSequenceClassification, and Trainer with TrainingArguments runs the loop.

Fix
pip install -U "transformers[torch]"

from transformers import AutoModelForSequenceClassification, AutoTokenizer, Trainer, TrainingArguments

tokenizer = AutoTokenizer.from_pretrained("distilbert/distilbert-base-uncased")
model = AutoModelForSequenceClassification.from_pretrained("distilbert/distilbert-base-uncased", num_labels=2)
args = TrainingArguments(output_dir="my-classifier", num_train_epochs=3)
trainer = Trainer(model=model, args=args, train_dataset=tokenized["train"],
                  eval_dataset=tokenized["test"], processing_class=tokenizer)
trainer.train()

Verify

The script runs to the end of trainer.train() and logs training loss values instead of the ImportError.

Verify
python train.py

Confirmed by raw.githubusercontent.com

Did this fix it?

Cause 3 of 3

You pinned 4.x for TF and now Keras 3 is rejected

You seeAfter installing transformers 4.57.6 the import works, but loading a TF model raises the Keras 3 ValueError

Check

Pinning the last 4.x release brings the TF classes back, but its TF code works only with Keras 2. When the installed keras package is version 3 and tf-keras is missing, transformers raises a ValueError that names the fix.

Check
python -c "import keras; print(keras.__version__)"

Fix

Install the backwards-compatible tf-keras package next to the pinned transformers release. Treat it as a bridge while you port the code to PyTorch.

Fix
pip install "transformers==4.57.6" tf-keras

Verify

The TF model loads without the ValueError.

Verify
python -c "from transformers import TFAutoModel; TFAutoModel.from_pretrained('bert-base-cased')"

Confirmed by raw.githubusercontent.com

Did this fix it?

How do I stop it coming back?

  • Pin transformers to an exact version in requirements.txt or the first notebook cell, since a hosted runtime can move to a new major release under you.
  • Search new code for imports starting with TF before adding them; on 5.x they cannot work.
  • Plan the PyTorch port now for any project held on 4.57.6: it is the newest 4.x release on PyPI, and the 5.x line has no TF classes at all.

Sources

How was this page made?

I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.

Which stack is behind this page?

Projects of mine on the same stack: stegnor.com, Menulo, ShopGo.

Next step

Want this handled for good?

I look after servers, apps and releases end to end. Tell me what keeps breaking.