C.W.K.
Stream
Lesson 04 of 08 · published

PyTorch Backend

~10 min · backend

Level 0Keras Apprentice
0 XP0/97 lessons0/20 achievements
0/120 XP to next level120 XP to go0% complete

The research and prototyping home

The PyTorch backend (PyTorch 2.1.0+) plugs Keras straight into the framework most of the research world already lives in: Hugging Face Transformers, torchvision, torchaudio, and the bulk of new pretrained models ship PyTorch-first. Eager-by-default execution means you debug with plain Python tools — set a breakpoint, inspect a tensor, no graph ceremony.

A Keras model IS a torch.nn.Module

The detail that unlocks the interop: under this backend, Keras layers and models become real torch.nn.Module instances (Code block). That's not a wrapper — it's the actual type. So a Keras model can sit inside a hand-written PyTorch training loop, register in a parent nn.Module, or hand its parameters to a torch.optim optimizer. You keep Keras's compile/fit convenience and still drop down to raw torch.autograd the moment you need it.

The one thing to watch: with KERAS_BACKEND=torch the model expects and returns torch tensors — feed it a NumPy or TF tensor and you'll hit a type error. Cross-backend code goes through keras.ops, which the next lessons cover.

Code

A Keras model is a real torch.nn.Module·python
os.environ["KERAS_BACKEND"] = "torch"
import keras
from keras import layers

model = keras.Sequential([
    layers.Dense(128, activation="relu"),
    layers.Dense(10, activation="softmax"),
])

# Keras model IS a torch.nn.Module
print(isinstance(model, torch.nn.Module))  # True

External links

Exercise

Switch your MNIST script to KERAS_BACKEND=torch. Confirm the same fit/compile path runs unchanged. Then peek under the hood with print(type(x)) on a batch — see torch.Tensor.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.