Defining a Simple Model
First, we define a simple neural network called FakeNet. This network will serve as our working example throughout this guide.Creating a Fake Dataset and Training the Model
For demonstration purposes, we generate a synthetic dataset using random tensors and perform a simple training loop. We’ll use the Mean Squared Error (MSE) loss function together with the SGD optimizer.Saving and Loading the Model Using state_dict
PyTorch recommends saving only the model parameters with the state dictionary. This includes the model’s weights, biases, and optimizer hyperparameters.It is generally recommended to save only the state_dict to allow flexibility when modifying the model architecture or optimizer in the future.
Saving and Loading the Entire Model
Another approach is to save the full model object as a Python pickle. Although convenient, this method requires the same class definitions when reloading.Creating and Using Checkpoints
Checkpoints allow you to save the full training state, including the model, optimizer, current epoch, and loss. This is essential for resuming training with minimal disruption.Saving a Checkpoint
Loading from a Checkpoint
Reload the model, optimizer, and training state from a checkpoint:Warm Starting (Transfer Learning)
Warm starting involves initializing a new model with parameters from a previously trained model. This is particularly useful for transfer learning, where you reuse learned features to speed up convergence on a new task.strict=False parameter ensures that only matching layers are loaded, allowing flexibility when the architectures differ slightly.
Saving and Loading Across Different Devices
PyTorch makes it simple to load models trained on one device (e.g., GPU) onto another (e.g., CPU) by using themap_location argument.
When using the
map_location argument, always confirm that both your model and input data reside on the same device to avoid runtime errors.