In pytorch I'm getting NaNs every once in a while. I'm thinking about saving checkpoints…
- User
In pytorch I'm getting NaNs every once in a while. I'm thinking about saving checkpoints of the model 10 steps behind and restoring the last one whenever a NaN is encountered. How do I do that?
- Assistant
First, you need to define a function that will save the checkpoint of your model. Here is an example:
def save_checkpoint(model, optimizer, loss, epoch): checkpoint = { 'model_state_dict': model.state_dict(), 'optimizer_state_dict': optimizer.state_dict(), 'loss': loss, 'epoch': epoch } torch.save(checkpoint, 'checkpoint.pth')This function saves the state of your model, optimizer, loss, and epoch to a file called 'checkpoint.pth'.
Next, you need to load the last checkpoint whenever a NaN is encountered. Here is an example:
model = MyModel() optimizer = torch.optim.Adam(model.parameters()) loss_fn = torch.nn.CrossEntropyLoss() for epoch in range(num_epochs): for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() output = model(data) loss = loss_fn(output, target) if torch.isnan(loss): # load the last checkpoint checkpoint = torch.load('checkpoint.pth') model.load_state_dict(checkpoint['model_state_dict']) optimizer.load_state_dict(checkpoint['optimizer_state_dict']) epoch = checkpoint['epoch'] continue loss.backward() optimizer.step() # save the checkpoint every 10 steps if (batch_idx + 1) % 10 == 0: save_checkpoint(model, optimizer, loss.item(), epoch) - User
Rewrite the code to only save the model in memory.
- Assistant
Sure, here's an example code that only saves the model in memory:
model = MyModel() optimizer = torch.optim.Adam(model.parameters()) loss_fn = torch.nn.CrossEntropyLoss() current_epoch = 0 last_checkpoint = None for epoch in range(num_epochs): for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() output = model(data) loss = loss_fn(output, target) if torch.isnan(loss): if last_checkpoint is not None: model.load_state_dict(last_checkpoint) continue loss.backward() optimizer.step() # Save the model state every 10 batches if batch_idx % 10 == 0: last_checkpoint = model.state_dict() if batch_idx == len(train_loader) - 1: last_checkpoint = model.state_dict() current_epoch += 1Here, instead of saving to disk, we create a variable
last_checkpointthat stores the state dictionary of the model every 10 batches. If we encounter a NaN loss, we can simply reload the model state from this variable.Note that we also save the final model state after completing each epoch so that the trained model can be used for inference later. The final model state is saved to the variable even if the batch index is not divisible by 10.