Сохранение и загрузка с помощью state_dict
Сохраняйте контрольные точки весов, чтобы продолжить позже
«Сохранение и загрузка с помощью state_dict» — бесплатный урок Deep Learning Academy на CoddyKit. Это урок 3 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Deep Learning Academy, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Deep Learning Academy содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
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. 💾
Часто задаваемые вопросы
Урок «Сохранение и загрузка с помощью state_dict» бесплатный?
Да — полный текст урока «Сохранение и загрузка с помощью state_dict» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Deep Learning Academy, подпишись на CoddyKit PRO. Курс Deep Learning Academy содержит 4 уроков всего.
Чему я научусь в уроке «Сохранение и загрузка с помощью state_dict»?
Сохраняйте контрольные точки весов, чтобы продолжить позже Ты практикуешь Deep Learning Academy с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Deep Learning Academy?
Предыдущий опыт не требуется. Deep Learning Academy на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 3 из 4.
Сколько времени занимает урок «Сохранение и загрузка с помощью state_dict»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Deep Learning Academy?
Да. Каждый урок Deep Learning Academy включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Разделите данные на обучение, проверку и тестирование
- Цикл эпохи с проверкой
- Сохранение и загрузка с помощью state_dict
- Ранняя остановка по потерям на проверке