0Pricing
Deep Learning Academy · Aula

Salve e Carregue com state_dict

Crie um ponto de verificação dos pesos para continuar depois

Salve e Carregue com state_dict é uma aula grátis de Deep Learning Academy no CoddyKit. Esta é a aula 3 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Deep Learning Academy, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Deep Learning Academy inclui 4 aulas no total.

Partes desta aula ainda não foram traduzidas e aparecem em inglês.

Why Checkpoints Matter

Training can take hours, and crashes happen. Saving your progress as a checkpoint lets you stop, resume, or ship the model without retraining from zero.

What a state_dict Holds

A model's state_dict is a plain dictionary mapping each layer name to its learned tensors. It is everything the model knows, packed for storage.

model.state_dict()

Save the Weights

Use torch.save on the state_dict to write the weights to disk. The .pt or .pth extension is the common convention for these files.

torch.save(model.state_dict(), 'model.pt')

Load the Weights Back

To restore, read the file with torch.load and pour it into a model using load_state_dict. The architecture must match the saved one.

model.load_state_dict(torch.load('model.pt'))

Recreate the Architecture First

A state_dict holds numbers, not the class itself. You must build the same model object in code before you can load weights into it.

model = MyNet()
model.load_state_dict(torch.load('model.pt'))

Eval Mode After Loading

Right after loading for inference, call model.eval(). It switches dropout and batch norm into prediction behavior so outputs are correct.

model.eval()

Save the Optimizer Too

To truly resume training, also save the optimizer's state_dict. It holds momentum and adaptive stats that would otherwise reset to zero.

torch.save(optimizer.state_dict(), 'opt.pt')

Bundle a Full Checkpoint

Pack model, optimizer, and the current epoch into one checkpoint dict. Now a single file restores your entire training session.

ckpt = {'epoch': epoch, 'model': model.state_dict(), 'opt': optimizer.state_dict()}
torch.save(ckpt, 'ckpt.pt')

Resume From a Checkpoint

Load the bundle and restore each piece in turn. Reading the saved epoch lets you continue the loop exactly where it left off.

ckpt = torch.load('ckpt.pt')
model.load_state_dict(ckpt['model'])
optimizer.load_state_dict(ckpt['opt'])

Map to the Right Device

If you saved on GPU and load on CPU, pass map_location to torch.load. It moves the weights to a device your machine actually has.

torch.load('model.pt', map_location='cpu')

Save the Best, Not the Last

Watch validation loss and overwrite your checkpoint only when it improves. That way you keep the best model, not whatever the final epoch produced.

Quick Check

You saved only model.state_dict(). What must exist before you can load it?

Recap

Save weights with state_dict and torch.save, rebuild the model to load them, and bundle the optimizer and epoch for a full resume. Keep the best one. 💾

Perguntas Frequentes

A aula “Salve e Carregue com state_dict” é grátis?

Sim — o texto completo de “Salve e Carregue com state_dict” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Deep Learning Academy, atualize para CoddyKit PRO. O curso de Deep Learning Academy inclui 4 aulas no total.

O que vou aprender em “Salve e Carregue com state_dict”?

Crie um ponto de verificação dos pesos para continuar depois Você pratica Deep Learning Academy com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.

Preciso ter experiência prévia para começar Deep Learning Academy?

Nenhuma experiência prévia é necessária. Deep Learning Academy no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 3 de 4.

Quanto tempo leva a aula “Salve e Carregue com state_dict”?

A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.

Posso escrever e executar código nesta aula de Deep Learning Academy?

Sim. Cada aula de Deep Learning Academy inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.

Todas as aulas deste curso

  1. Separe Treinamento, Validação e Teste
  2. Um Ciclo de Épocas com Validação
  3. Salve e Carregue com state_dict
  4. Parada Antecipada com a Perda de Validação
← Voltar para Deep Learning Academy