Porting a neural network from TensorFlow to PyTorch? Before you compare training curves, test one update. Load the same weights, feed both models the same three examples, and compare the predictions before and after a single training step. That gives you a small regression test for the port. Unlike a typical software test, the expected result is a range: floating-point operations need not produce identical bits.
Set up a fixture that exposes a transposed weight matrix
Our network takes two numbers, mixes them into two hidden values, and uses ReLU to replace negative values with zero. A final linear layer turns those two values into one prediction. The nine trainable numbers are the two weight matrices and their biases (the offsets). A shared random seed would not guarantee the same starting weights across libraries, so the test assigns every number explicitly. Save the fixture below as case.py.
X = [[1., 0.], [0., 1.], [1., 1.]]
Y = [[1.], [0.], [0.5]]
W = [[0.5, -0.25], [-0.125, 0.75]] # inputs by hidden units
B = [0.0625, -0.125]
V = [[0.75], [-0.5]]
C = [0.125]
LR = 0.125The targets are columns, not flat lists: subtracting a (3,) target from a (3, 1) prediction can silently produce a (3, 3) array of pairwise errors. The loss here is mean squared error (MSE): square each of the three prediction errors and take their mean. Each optimizer takes one plain stochastic gradient descent (SGD) step on that whole batch, subtracting 0.125 times each gradient. No momentum, shuffling, or regularization.
TensorFlow: record the forward pass on a tape
The Keras Dense layer stores its kernel by input, then output. We call the layers once so their variables exist, overwrite the generated parameters, and make a fresh prediction inside TensorFlow’s GradientTape. The tape records the operations needed to calculate how the loss changes with each parameter. Save as tf_step.py.
import json, os
os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
os.environ['KERAS_BACKEND'] = 'tensorflow'
import tensorflow as tf
from case import X, Y, W, B, V, C, LR
tf.config.set_visible_devices([], 'GPU')
x, y = tf.constant(X), tf.constant(Y)
h = tf.keras.layers.Dense(2, activation='relu', dtype='float32')
out = tf.keras.layers.Dense(1, dtype='float32')
def predict():
return out(h(x))
predict() # build both layers before assigning weights
h.kernel.assign(W); h.bias.assign(B)
out.kernel.assign(V); out.bias.assign(C)
params = [h.kernel, h.bias, out.kernel, out.bias]
with tf.GradientTape() as tape:
p = predict()
loss = tf.reduce_mean(tf.square(p - y))
g = tape.gradient(loss, params)
tf.keras.optimizers.SGD(learning_rate=LR).apply_gradients(zip(g, params))
q = predict()
assert 'CPU' in q.device
print(json.dumps(dict(framework=tf.__version__, keras=tf.keras.__version__,
device=q.device, pre=p.numpy().tolist(), mse=float(loss),
grads=[v.numpy().tolist() for v in g], weights=[v.numpy().tolist() for v in params],
post=q.numpy().tolist(), mse_after=float(tf.reduce_mean(tf.square(q-y))))))PyTorch: transpose the kernels and call backward
A PyTorch Linear layer stores its weights by output, then input. Transpose both matrices when loading them; leave the biases alone. The first matrix is square, so the wrong orientation still fits. During training, PyTorch autograd records the forward operations; backward() accumulates derivatives on the parameters and step() updates them. Clear old gradients before the backward pass. Save as pt_step.py.
import json, torch
from case import X, Y, W, B, V, C, LR
torch.set_default_device('cpu')
torch.set_default_dtype(torch.float32)
x, y = torch.tensor(X), torch.tensor(Y)
h, out = torch.nn.Linear(2, 2), torch.nn.Linear(2, 1)
with torch.no_grad():
h.weight.copy_(torch.tensor(W).T); h.bias.copy_(torch.tensor(B))
out.weight.copy_(torch.tensor(V).T); out.bias.copy_(torch.tensor(C))
def predict():
return out(torch.relu(h(x)))
def common_layout(t):
return (t.T if t.ndim == 2 else t).detach().tolist()
params = [h.weight, h.bias, out.weight, out.bias]
opt = torch.optim.SGD(params, lr=LR)
opt.zero_grad()
p = predict()
loss = (p - y).square().mean()
loss.backward()
g = [common_layout(v.grad) for v in params]
opt.step()
with torch.no_grad():
q = predict()
assert q.device.type == 'cpu'
print(json.dumps(dict(framework=torch.__version__, device=str(q.device),
pre=p.detach().tolist(), mse=loss.item(), grads=g,
weights=[common_layout(v) for v in params], post=q.tolist(),
mse_after=(q-y).square().mean().item())))Run each implementation in its own CPU environment
We used Python 3.12.13 on 64-bit Windows, TensorFlow 2.20.0 (Keras 3.15.1, TensorFlow backend), and PyTorch 2.9.1+cpu. From a fresh working folder containing the files above, run these commands in Windows Command Prompt. The interpreters are named explicitly so that neither script imports packages from the other environment.
python -m venv tf
python -m venv pt
tf\Scripts\python -m pip install tensorflow==2.20.0 keras==3.15.1
pt\Scripts\python -m pip install torch==2.9.1 --index-url https://download.pytorch.org/whl/cpu
tf\Scripts\python tf_step.py > tf.json
pt\Scripts\python pt_step.py > pt.jsonSave the comparison below as compare.py, then run python compare.py tf.json pt.json. Both runners export predictions, gradients, and updated parameters in the same input-by-output layout. The comparator checks each scalar with absolute tolerance 0.000001 and no relative tolerance; a shape mismatch also fails. On our CPU, the maximum absolute difference was zero for every group of values.
import json, math, sys
from pathlib import Path
def differences(a, b):
if isinstance(a, list):
assert isinstance(b, list) and len(a) == len(b)
for x, y in zip(a, b):
yield from differences(x, y)
else:
assert math.isfinite(a) and math.isfinite(b)
yield abs(a-b)
if __name__ == '__main__':
tf, pt = [json.loads(Path(p).read_text()) for p in sys.argv[1:]]
for key in ('pre', 'mse', 'grads', 'weights', 'post', 'mse_after'):
d = max(differences(tf[key], pt[key]))
print(f'{key}: max absolute difference = {d:.9g}')
assert d <= 1e-6
assert tf['mse_after'] < tf['mse'] and pt['mse_after'] < pt['mse']Read the first mismatch, not just the final loss
For input [1, 0], both networks predicted 0.546875 before training and 0.703559 after the update. Across all three examples, MSE fell from 0.09847005 to 0.03239606 in both runs (rounded). In particular, the output bias moved from 0.125 to 0.19791667. That last check distinguishes an optimizer that updated the model from one that merely calculated derivatives.
If the initial predictions differ, inspect the input order, weight layout, and biases before debugging the optimizer. Try dropping the transpose on the first PyTorch weight matrix only: the code still runs, but the first two predictions still match while the [1, 1] prediction changes from 0.265625 to 0.109375. If predictions agree but gradients differ, inspect the loss reduction and target shape. If gradients agree but updated weights differ, check the learning rate and optimizer state.
For this port, either library implements the same calculation. Use the version that integrates with the layers and training pipeline you already maintain; keep the fixture as a regression test when changing frameworks. Three synthetic rows and one CPU update tell us nothing about GPU speed, memory at scale, or accuracy on unseen data. For the underlying concepts, see how neural networks learn; for a first model without a framework comparison, try the Python machine learning hello world.
For a longer PyTorch training project, Eli Stevens, Luca Antiga, and Thomas Viehmann’s Deep Learning with PyTorch covers tensors, training loops, and image models. The first edition predates the releases tested above. As an Amazon Associate I earn from qualifying purchases. View the first-edition paperback on Amazon US.



