Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/model save2 #161

Merged
merged 2 commits into from
Jan 6, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions pixyz/models/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -179,3 +179,29 @@ def test(self, test_x_dict={}, **kwargs):
loss = self.test_loss_cls.eval(test_x_dict, **kwargs)

return loss

def save(self, path):
"""Save the model. The only parameters that are saved are those that are included in the distribution.
Parameters such as device, optimizer, placement of clip_grad, etc. are not saved.

Parameters
----------
path : str
Target file path

"""
torch.save({
'distributions': self.distributions.state_dict(),
}, path)

def load(self, path):
"""Load the model.

Parameters
----------
path : str
Target file path

"""
checkpoint = torch.load(path)
self.distributions.load_state_dict(checkpoint['distributions'])
38 changes: 38 additions & 0 deletions tests/models/test_model.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import os
import torch
import torch.nn as nn
from pixyz.distributions import Normal
from pixyz.losses import CrossEntropy
from pixyz.models import Model


class TestModel:
def _make_model(self, loc):
class Dist(Normal):
def __init__(self):
super().__init__(loc=loc, scale=1)
self.module = nn.Linear(2, 2)

p = Dist()

if torch.cuda.is_available():
device = "cuda"
else:
device = "cpu"

loss = CrossEntropy(p, p).to(device)
model = Model(loss=loss, distributions=[p])
return model

def test_save_load(self, tmp_path):
model = self._make_model(0)
save_path = os.path.join(tmp_path, 'model.pth')
model.save(save_path)

model = self._make_model(1)
p: Normal = model.distributions[0]
assert p.get_params()['loc'] == 1

model.load(save_path)
p: Normal = model.distributions[0]
assert p.get_params()['loc'] == 0