PythiloLesson 4 of 8 · progress kept in this browser

Restore module modes after a prediction helper

A shared evaluation helper should not permanently alter a caller's training policy. Save each module's training flag before switching to evaluation mode, perform prediction without gradient recording and restore the original flags even on failure.

Saving only the root flag is insufficient when a model intentionally mixes a training head with an evaluation backbone. This exercise preserves that mixed state and returns a detached clone so later mutations do not alias the prediction result. It does not make concurrent training and inference on the same mutable model safe; separate ownership is still required.

import torch
from torch import nn
model=nn.Linear(2,1)
with torch.no_grad():
    result=model(torch.ones(1,2))
print(result.requires_grad)
This example uses torch. Run it in the Pythilo app, where these features are available.
Your task

Implement owned_prediction(model,x): save every module training flag, eval the model, return model(x).detach().clone() under torch.no_grad, then restore every saved flag in finally.

This lesson uses torch, which Python in this browser does not include. Read it here, and run and check it in the Pythilo app on iPhone or iPad.