The damage classifier
scored ninety four percent
in the notebook.

So you wrote
the serving script.

model = DamageNet()
model.load_state_dict(torch.load("best.pt"))

@torch.no_grad()
def score(image):
return model(prepare(image).unsqueeze(0))

A returns clerk
uploaded the same photo
twice.

0.81.

Then 0.62.

Same pixels.

Different answer.

And over the week
every score
drifted a little lower.

Here is the mechanism.

A PyTorch model
has two modes.

Training.

And evaluation.

A new model
starts in training mode.

Loading the weights
does not change that.

torch.no_grad
does not change that.

It only stops
gradients being recorded.

In the notebook
the evaluate helper
called model.eval()
first.

You copied the model.

Not the helper.

The one line
that mattered
lived in a function
nobody thought of
as part of the model.

So in production
two layers
were still training.

Dropout
was switching off
a random part of the network
on every request.

That is the 0.81
and the 0.62.

BatchNorm
was normalising each image
with that one image's statistics,
not the ones it learned.

And in training mode
it updates
its running averages
on every forward pass,
gradients or not.

Every photo the clerks uploaded
was quietly rewriting
what the model thought
a normal photo looked like.

That is the drift.

The ninety four percent
was real.

It was measured
in the right mode.

It just measured
a model
you never deployed.

No error.

No warning.

Plausible numbers,
every time.

Here is the fix.

model.load_state_dict(torch.load("best.pt"))
model.eval()

One line,
straight after loading.

Then make it
impossible to forget.

Put loading and eval
in one function,
and use it
in the notebook,
the tests
and the server.

assert not model.training

at startup.

And one test
that scores the same input
twice
and expects
the same number.

Then one more,
that scores it
alone
and inside a batch of strangers,
and expects
the same number again.

A model that disagrees
with itself
is not uncertain.

It is still training.

On your customers.

– Serguey Asael Shinder