PyTorch vs TensorFlow/Keras vs MLX for Training a Classifier — Day 46

TensorFlow with Keras, PyTorch, and Apple MLX can train the same classifier. The main differences in this example are who controls the training loop, how gradients are represented, and when the device performs the computation.

Which framework should you use on an Apple silicon Mac?

Choose TensorFlow with Keras when you want a built-in training loop. Choose PyTorch when you want to inspect or change each training step, especially if your project already uses PyTorch models. Choose Apple MLX when you want a small, explicit training loop and want to experiment with lazy execution on Apple silicon. Each can train the classifier below. The difference is who runs the training steps, where the arrays live, and when the computation takes place.

A shared classifier and data set

Day 46 uses the same model in all three Python examples. It accepts 32 features, passes them through 64 hidden units with ReLU, and predicts one of ten classes. Each example uses SGD with a learning rate of 0.01, ten epochs, a batch size of 32, and global gradient clipping at 1.0.

Run the NumPy setup below once, then run the section for the framework installed in your Python environment. It creates 256 synthetic examples with a fixed labeling rule. The small data set lets you trace the shapes and training steps without downloading files. For a real model, evaluate on a separate validation set.

import numpy as np

rng = np.random.default_rng(46)
X_train = rng.normal(size=(256, 32)).astype(np.float32)
# One fixed rule maps each input to a class.
teacher = rng.normal(size=(32, 10)).astype(np.float32)
y_train = (X_train @ teacher).argmax(axis=1).astype(np.int32)
batch_size = 32

def batches():
    for start in range(0, len(X_train), batch_size):
        stop = start + batch_size
        yield X_train[start:stop], y_train[start:stop]

1. Train the classifier in PyTorch

PyTorch exposes the individual operations in a training step. In this example, nn.Linear(32, 64) maps the 32 inputs to 64 hidden values. ReLU keeps positive values, and the final layer returns ten raw class scores, or logits. The layer definitions live in __init__, while their order is set in forward.

PyTorch example

import torch
from torch import nn

class SimpleModel(nn.Module):
    def __init__(self):
        super().__init__()
        self.fc1 = nn.Linear(32, 64)
        self.fc2 = nn.Linear(64, 10)

    def forward(self, x):
        return self.fc2(torch.relu(self.fc1(x)))

torch.manual_seed(46)
model = SimpleModel()
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)
criterion = nn.CrossEntropyLoss()

for epoch in range(10):
    for features, classes in batches():
        inputs = torch.from_numpy(features)
        labels = torch.from_numpy(classes).long()
        optimizer.zero_grad()
        logits = model(inputs)
        loss = criterion(logits, labels)
        loss.backward()
        nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
        optimizer.step()

print("Last batch loss:", loss.item())

What happens during a PyTorch update?

Follow one batch of 32 examples through the loop. Three calls connect the output of the model to the next set of weights.

  • Forward pass. Calling model(inputs) invokes forward and returns a 32-by-10 tensor. CrossEntropyLoss accepts these logits and one integer class index per row.
  • Backward pass. loss.backward() accumulates derivatives in each parameter’s .grad. Calling zero_grad() at the start of the next batch keeps older derivatives out of the next update.
  • Weight update. optimizer.step() applies stochastic gradient descent. Putting the clipping operation immediately before this call caps the combined gradient norm at 1.0.

This ordering is useful for debugging. To find a bad update, inspect a batch’s labels and logits, print the loss, then examine gradient norms before clipping. Clipping limits the size of an update but cannot correct an invalid label or replace a non-finite gradient. See the PyTorch optimization tutorial.

2. Train the same classifier in TensorFlow with Keras

Keras expresses the same network as a sequence of layers. Keras 3 also supports other backends, including PyTorch and JAX. This example uses tf.keras with TensorFlow so you can see what the built-in fit() loop handles. See the Keras multi-backend guide.

TensorFlow and Keras example

import tensorflow as tf

tf.keras.utils.set_random_seed(46)
model = tf.keras.Sequential([
    tf.keras.Input(shape=(32,)),
    tf.keras.layers.Dense(64, activation="relu"),
    tf.keras.layers.Dense(10),
])
optimizer = tf.keras.optimizers.SGD(
    learning_rate=0.01, global_clipnorm=1.0
)
loss_fn = tf.keras.losses.SparseCategoricalCrossentropy(
    from_logits=True
)
model.compile(optimizer=optimizer, loss=loss_fn)
history = model.fit(
    X_train, y_train, epochs=10, batch_size=batch_size,
    shuffle=False, verbose=0
)
print("Last epoch mean loss:", history.history["loss"][-1])

What does Keras fit() handle?

The three calls have distinct jobs. Sequential defines the layers, compile() associates the loss and optimizer with the model, and fit() iterates over batches and epochs.

  • Automatic training loop. For each batch, Keras runs the forward pass, computes the mean loss and its gradients, and applies the optimizer. Setting shuffle=False gives it the same example order as the other two programs.
  • Gradient clipping. global_clipnorm=1.0 clips gradients by their combined norm. The similarly named clipnorm applies to each gradient separately, so it would change the experiment. See the Keras SGD options.

The last layer has no softmax, so it outputs raw scores. SparseCategoricalCrossentropy(from_logits=True) tells Keras to interpret them correctly. A sparse label stores one integer, such as 3, for each example. A custom update is also possible in TensorFlow with tf.GradientTape.

3. Train the same classifier in Apple MLX

In MLX the two linear layers look familiar if you have used PyTorch. The forward calculation lives in __call__. On Apple silicon, CPU and GPU operations can use arrays in shared memory. MLX also builds computations lazily, which makes the point where the program evaluates an update important.

MLX example

import mlx.core as mx
import mlx.nn as nn
import mlx.optimizers as optim

class SimpleModel(nn.Module):
    def __init__(self):
        super().__init__()
        self.fc1 = nn.Linear(32, 64)
        self.fc2 = nn.Linear(64, 10)

    def __call__(self, x):
        return self.fc2(nn.relu(self.fc1(x)))

def loss_fn(model, inputs, labels):
    logits = model(inputs)
    return nn.losses.cross_entropy(logits, labels, reduction="mean")

mx.random.seed(46)
model = SimpleModel()
mx.eval(model.parameters())
optimizer = optim.SGD(learning_rate=0.01)
loss_and_grad = nn.value_and_grad(model, loss_fn)

for epoch in range(10):
    for features, classes in batches():
        inputs, labels = mx.array(features), mx.array(classes)
        loss, grads = loss_and_grad(model, inputs, labels)
        grads, _ = optim.clip_grad_norm(grads, max_norm=1.0)
        optimizer.update(model, grads)
        mx.eval(loss, model.parameters(), optimizer.state)

print("Last batch loss:", loss.item())

What does MLX evaluate?

Read the MLX training code in two parts. First it describes how to calculate a scalar loss and update the model. Then it explicitly evaluates the pending work for the current batch.

  • Unified memory. On an Apple silicon Mac, MLX arrays can be accessed by the CPU and GPU without an explicit device-to-device copy. Creating MLX arrays from NumPy is a separate input-conversion step in this teaching example.
  • Dynamic computation. Ordinary Python builds the computation from the current inputs. Lazy evaluation defers execution, so timing only the creation of the computation can make a training step look artificially fast.
  • Manual update. nn.value_and_grad(model, loss_fn) returns a function. Calling that function returns a scalar loss and a tree of parameter gradients. Pass the gradients to the optimizer and evaluate the new parameters and optimizer state. Compare the official MLX classifier example.

Why the MLX and PyTorch loops look similar

Both examples give you a place to inspect the loss, modify a gradient, or skip a batch before the optimizer updates the parameters. You reach those values in different ways.

  • Finding a gradient. PyTorch writes it to each parameter’s .grad after backpropagation. MLX returns a gradient tree with the same nesting as the trainable parameters. When debugging either loop, first confirm that the weight you expect to update actually has a gradient.
  • Choosing when work runs. PyTorch’s eager operations and MLX’s lazy operations have different execution behavior. TensorFlow also runs eagerly by default. Wrapping TensorFlow code with tf.function can trace a graph for repeated execution. See TensorFlow’s guide to graphs.
  • Choosing hardware. This PyTorch snippet uses CPU tensors. PyTorch also supports the MPS device on compatible Macs. To benchmark it there, move both model and input tensors to the same device and synchronize the accelerator before stopping the timer. See the PyTorch MPS guide.

Keras provides a useful comparison because its default loop hides the same sequence of operations. If you get different behavior across the examples, check the batch, the loss reduction, and the optimizer settings first. Changing a framework also changes default initializers, so matching learning rates and architectures alone will not produce identical weights.

How to compare the three implementations fairly

  • Training objective. All three versions use ten output logits and minimize mean cross-entropy. With ten equal logits, every class has probability 0.1. One example then has loss −ln(0.1), about 2.303. This gives you a quick check on the loss definition before assessing accuracy.
  • Batch and memory. Each example uses 32 rows per update. Keep the same precision, batch order and array shapes. Record whether input conversion is included in a timing, especially when comparing the NumPy-based setup here with a native data loader.
  • Graph execution. Separate the first step from subsequent ones. A first step can include tracing, compilation, or allocation. For an MLX timing, include mx.eval inside the timed operation so the reported time includes actual work.
  • Hardware. Measure on the device you plan to use and record its processor, RAM, library versions, and device selection. These short programs explain the APIs. Their timings alone cannot establish which framework will be fastest for an image model or a language model.

Which workflow fits your project?

Choose according to the change you expect to make next. The same two-layer network leads to different practical choices.

  • PyTorch. If you build on an existing PyTorch checkpoint or want to log a gradient before every step, the explicit loop is a convenient starting point. Try the CPU version first, then change device placement and measure again.
  • TensorFlow with Keras. If you want training history, validation, and callbacks with a standard loop, start with fit(). Change the batch size or optimizer in one place. If your update rule later needs custom logic, you can write a TensorFlow training step.
  • MLX. If you are developing locally on Apple silicon and want to investigate lazy execution or shared-memory behavior, start with its explicit loop. Evaluate updates consistently when comparing throughput or memory use.

Three checks make good next exercises for this lesson.

  • Run one batch in each framework. Confirm that the output shape is (32, 10) and that every label is an integer between 0 and 9. A shape error is easier to diagnose here than after ten epochs.
  • Compare losses on the same batch with fixed weights if you need numerical parity. Keras reports a running mean over an epoch in this example. PyTorch and MLX print the last batch’s loss. These summaries answer different questions.
  • Once the trained model is ready for an app, choose a deployment runtime separately. For Swift and Xcode, see how to deploy a TensorFlow or PyTorch model on iPhone.

Verify the classifier before benchmarking

Every dense output needs one weight per input and one bias. The first layer has 64 sets of 32 weights, and the output has ten sets of 64. Count these separately and include the biases.

(32⋅64+64)+(64⋅10+10)=2762

Feed 32 examples and check for 32 rows of ten logits. With both layers’ weights and biases temporarily zero, each class has probability one tenth. Mean cross-entropy is then the natural logarithm of 10, about 2.3026. This is a sanity check. For gradient parity, use the same nonzero initial arrays so the first layer receives a useful signal.

Verify the classifier before benchmarkingFixed inputSame 32-by-32 batchFixed weightsMatch layoutCompare outputsLoss and gradients
Verify one deterministic batch before interpreting whole-run differences.

Compare updates and elapsed time

The common PyTorch linear weight layout is output by input, while Keras Dense uses input by output. MLX Linear also uses output by input. Align these arrays before comparing losses, unclipped gradient norms, clipped gradients, and new parameters. Check all training-loop dropout or other stateful layers are in the same mode if you extend the example.

Timing needs comparable devices and synchronization. The original PyTorch example uses CPU arrays. For accelerator results, include a warm-up and force the scheduled work to finish before reading the timer. Use repeated measurements and record whether input transfer is included.

References

Practice and FAQs

How many parameters are in the first dense layer?

There are 32 times 64 weights and 64 biases, totaling 2,112.

Why can MLX timing be misleading without evaluation?

Creating a lazy computation can enqueue or describe work. Evaluating a result accounts for the computation needed to produce it.

Do identical final training losses prove performance parity?

No. Compare a shared validation set and inspect numerical parity on a fixed batch. Two models can reach similar training losses through different trajectories.

Leave a reply

Your email address will not be published. Required fields are marked *

You Can Also Learn Deep Learning in 80 Days Inside the iOS App Continue this roadmap in a focused mobile study experience with offline access, flashcards, notes, and progress tracking.
Open on the App Store