Complete worked example
python
from bootstrap_lab import torch_setup
torch = torch_setup()
import io
from torch import nn
def checkpoint_roundtrip(weight, value):
source = nn.Linear(1, 1, bias=False)
with torch.no_grad():
source.weight.fill_(weight)
buffer = io.BytesIO()
torch.save(source.state_dict(), buffer)
buffer.seek(0)
restored = nn.Linear(1, 1, bias=False)
state = torch.load(buffer, map_location='cpu', weights_only=True)
restored.load_state_dict(state)
restored.eval()
with torch.inference_mode():
return restored(torch.tensor([[float(value)]])).item()- Reasoning
- The helper writes a known one-weight model’s state into an owned BytesIO buffer, rewinds it and loads with weights_only=True and map_location CPU. A fresh matching Linear module receives the state and performs evaluation.