Guardar y cargar con state_dict
Guarde los pesos en un checkpoint para reanudar más tarde
Guardar y cargar con state_dict es una lección gratuita de Deep Learning Academy en CoddyKit. Esta es la lección 3 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Deep Learning Academy, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Deep Learning Academy incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en 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. 💾
Preguntas frecuentes
¿La lección «Guardar y cargar con state_dict» es gratis?
Sí — el texto completo de «Guardar y cargar con state_dict» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Deep Learning Academy, actualiza a CoddyKit PRO. El curso de Deep Learning Academy incluye 4 lecciones en total.
¿Qué aprenderé en «Guardar y cargar con state_dict»?
Guarde los pesos en un checkpoint para reanudar más tarde Practicas Deep Learning Academy con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar Deep Learning Academy?
No se requiere experiencia previa. Deep Learning Academy en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 3 de 4.
¿Cuánto tiempo toma la lección «Guardar y cargar con state_dict»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de Deep Learning Academy?
Sí. Cada lección de Deep Learning Academy incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- Separe entrenamiento, validación y prueba
- Un bucle de épocas con validación
- Guardar y cargar con state_dict
- Early stopping según la pérdida de validación