Save and Load Training Checkpoint
Problem Statement
Create a complete training checkpoint with model, optimizer, and training state, save to a buffer, and restore from it.
Background
Training checkpoints include not just model weights but also optimizer state (momentum buffers, learning rates) and training metadata (epoch, loss). Use io.BytesIO as an in-memory buffer.
Your Task
The starter code trains for 3 steps and prepares a checkpoint dict. Save the complete training checkpoint (model state, optimizer state, epoch, loss) to an in-memory buffer, then restore everything from the buffer into fresh model and optimizer instances.
Output Format
Returns a dictionary with "saved_epoch", "weights_restored", "optimizer_restored", and "checkpoint_keys".
Example
None
{'saved_epoch': 3, 'weights_restored': True, 'optimizer_restored': True, 'checkpoint_keys': ['model_state_dict', 'optimizer_state_dict', 'epoch', 'loss']}- The function
checkpoint_test()starts by seeding withtorch.manual_seed(42)and creates a modelnn.Linear(3, 2)with an Adam optimizer, then runs 3 training steps with input[[1.0, 2.0, 3.0]]and target[[1.0, 0.0]]to calculate the loss. - After training, it saves a checkpoint to an
io.BytesIObuffer containing the model state dictionary, optimizer state dictionary, epoch (3), and the last loss value. - A new model and optimizer are created with the same architecture but a fresh seed (99), and the checkpoint is loaded from the buffer to restore the model and optimizer states.
- The function then verifies that the model weights match after loading and checks if the optimizer state was loaded, resulting in the output dictionary with the saved epoch, weights restoration status, optimizer restoration status, and checkpoint keys.
Constraints
- Use io.BytesIO (no file I/O)
- Save model + optimizer + metadata
- Verify full restoration