Comparison

PyTorch vs TensorFlow: Which to Learn in 2026

Learn PyTorch first if you want to write and debug the training loop yourself, or if you are following this curriculum, which builds a framework by hand and then teaches PyTorch. Learn TensorFlow with Keras first if your team already ships TensorFlow models or you want fit() and SavedModel export. The core ideas transfer either way.

Last updated · By Rohit Ghumare

PyTorch vs TensorFlow at a glance

PyTorchTensorFlow
Default executionEager. The autograd graph is built as the code runs and re-created after each .backward() callEager. Code inside @tf.function is traced and run as a graph
Automatic differentiationTensors with requires_grad=True; call loss.backward(), read .gradRecord inside with tf.GradientTape() as tape, then tape.gradient(loss, variables)
Model buildingSubclass nn.Module, define forward()Keras Sequential, functional API or subclassing; tf.Module underneath
Training loopYou write it: zero gradients, forward, loss, backward, stepmodel.compile(...) then model.fit(...); a custom loop with GradientTape is also possible
Graph compilationtorch.compile, which uses TorchDynamo and the inductor backend by defaulttf.function, which captures a tf.Graph per input signature
Exporttorch.export produces an ahead-of-time traced graph that can be serializedtf.saved_model writes a SavedModel that runs with no Python installation
Server-side servingServing engines built on PyTorch, such as vLLM for language modelsTensorFlow Serving loads SavedModels
On-device runtimeExecuTorchLiteRT (the .tflite format), which also accepts PyTorch and JAX models
Relationship to KerasKeras 3 can run on PyTorch as a backendKeras is TensorFlow's high-level API
In this curriculumA full lesson, after you build a mini framework by handNo dedicated lesson

Rows come from the official PyTorch, TensorFlow, Keras and LiteRT documentation listed in this page's sources, read on 2026-12-04. This page gives no speed comparison: speed depends on the model, the hardware and whether the graph is compiled.

When to choose each

Choose PyTorch when

  • You want the training loop in front of you. The loop is five lines, and they are the same five lines for a two-layer network and a large language model.
  • You need to debug with ordinary Python tools. Because the graph is built as the code runs, you can put a print or a breakpoint between any two operations.
  • The code you need to read or extend is already in PyTorch. In this curriculum, PyTorch is the only deep learning framework on the list of allowed dependencies.
  • You are going on to serve language models. The vLLM install docs select a PyTorch backend, for example.

Choose TensorFlow when

  • Your team already has TensorFlow models, data pipelines or a TensorFlow Serving deployment. Staying on one stack is usually worth more than any framework difference.
  • You want the least code between data and a trained model. Keras fit, evaluate and predict cover the standard workflow.
  • You need a model artifact that runs without Python. A SavedModel can be loaded from other language bindings and from TensorFlow Serving.
  • Your target is a phone or another small device and your tooling is already built around .tflite.

Check the platform notes first

The TensorFlow install page says there is currently no official GPU support on macOS, and that GPU on native Windows ended after TensorFlow 2.10, so newer versions need WSL2 for GPU. For supported Python versions, check PyPI: on 2026-12-04, tensorflow 2.22.0 required Python 3.10 or newer, while the install page still listed 3.9 to 3.12. PyTorch's install page is a selector by operating system, package manager and compute platform; on the same day it said PyTorch is supported on macOS 10.15 or above, and its selector listed CUDA, ROCm and CPU builds. Read the current page for either before you buy or configure hardware.

Code: one example per side

Both scripts fit the line y = 3x + 2 with gradient descent. We ran both on 2026-12-04; each prints 3.0 2.0.

PyTorch. You write the loop.

python
import torch

torch.manual_seed(0)
x = torch.linspace(-1, 1, 100).unsqueeze(1)
y = 3 * x + 2

model = torch.nn.Linear(1, 1)
optimizer = torch.optim.SGD(model.parameters(), lr=0.1)
criterion = torch.nn.MSELoss()

for step in range(200):
    optimizer.zero_grad()
    loss = criterion(model(x), y)
    loss.backward()
    optimizer.step()

print(round(model.weight.item(), 2), round(model.bias.item(), 2))

TensorFlow with Keras. fit runs the loop.

python
import tensorflow as tf

tf.keras.utils.set_random_seed(0)
x = tf.reshape(tf.linspace(-1.0, 1.0, 100), (100, 1))
y = 3 * x + 2

model = tf.keras.Sequential([tf.keras.Input(shape=(1,)), tf.keras.layers.Dense(1)])
model.compile(optimizer=tf.keras.optimizers.SGD(learning_rate=0.1), loss="mse")
model.fit(x, y, epochs=200, batch_size=100, verbose=0)

weight, bias = model.layers[0].get_weights()
print(round(float(weight[0][0]), 2), round(float(bias[0]), 2))

Output of each:

output
3.0 2.0

The lower-level view is the same in both. In PyTorch, x = torch.tensor(1.0, requires_grad=True), then y = x**2 + 2*x - 5 and y.backward() leaves 4.0 in x.grad. In TensorFlow, the same expression inside tf.GradientTape gives 4.0 from tape.gradient(y, x).

Common mistakes

  • Forgetting optimizer.zero_grad() in PyTorch. Gradients accumulate by default, so each step adds to the last one's gradients.
  • Evaluating with gradient tracking on. Wrap PyTorch evaluation in torch.no_grad() and call model.eval().
  • Saving the PyTorch model object. Save model.state_dict() instead; pickled model objects break when you refactor the class.
  • Expecting Python side effects inside tf.function. A print runs when the function is traced, not on every call. Later calls execute the captured graph only.
  • Retracing by accident. tf.function builds a new graph for each new input signature (shape and dtype). Feeding ever-changing signatures means repeated tracing.
  • Writing low-level TensorFlow when Keras would do. The TensorFlow docs reserve the Core APIs for cases such as building tools on top of TensorFlow.
  • Assuming Keras means TensorFlow. Keras 3 runs on JAX, TensorFlow or PyTorch.
  • Choosing by a benchmark from another machine. Speed depends on the model, the hardware and whether you compiled the graph. Measure your own workload.

Frequently asked questions

Is PyTorch or TensorFlow easier to learn?

It depends on what you want to see. Keras on TensorFlow trains a model in three calls (compile, fit, predict), which is the shortest path to a result. PyTorch makes you write the training loop yourself, which is more typing but shows every step: forward pass, loss, backward pass, optimizer step.

Should I learn both PyTorch and TensorFlow?

Learn one well first. Tensors, automatic differentiation, layers, losses, optimizers and the training loop are the same ideas in both, so the second framework is mostly new names for things you already understand. Pick the one your team, your course or the code you need to read already uses.

What is the difference between Keras and TensorFlow?

TensorFlow is the platform: tensors, automatic differentiation, graphs and export. Keras is the high-level API for layers, models and training, and the TensorFlow docs say every TensorFlow user should use it by default. Keras 3 is also a separate multi-framework library that runs on JAX, TensorFlow or PyTorch.

Can I move a PyTorch model to a TensorFlow Lite runtime?

Google's on-device runtime, LiteRT, documents direct export from PyTorch, TensorFlow and JAX into the .tflite format, and has a migration guide for TensorFlow Lite apps. PyTorch also has its own on-device runtime, ExecuTorch, for phones and embedded systems. Check each converter's supported operators before committing to a path.

Does PyTorch build a graph like TensorFlow does?

Yes, but at a different moment. PyTorch records operations into a graph while your code runs and rebuilds it after every backward call, so ordinary Python control flow works. TensorFlow runs eagerly too, and a function decorated with tf.function is traced into a reusable graph for each input signature.

Learn it by building

These free lessons build the pieces by hand and then map them to the framework:

  1. Chain Rule & Automatic Differentiation: what backward() and GradientTape compute.
  2. Build Your Own Mini Framework: modules, layers, optimizers and a training loop in plain Python.
  3. Introduction to PyTorch: the same design with tensors, autograd, nn.Module and GPU training.
  4. Introduction to JAX: the third style, pure functions that are traced and compiled.

Sources

More comparisons

All comparisons · All how-to guides · Course catalog