Restore device in cpp API (#14711)

Summary:
This is a stack PR based on https://github.com/pytorch/pytorch/pull/14454.

It enables the restoring the storage to appropriate device.

~~[TODO]: add/modify appropriate tests~~ Done
Pull Request resolved: https://github.com/pytorch/pytorch/pull/14711

Reviewed By: dzhulgakov

Differential Revision: D13315746

Pulled By: houseroad

fbshipit-source-id: fe6f24a45c35e88fd1a2eebc09950d4430fac185
This commit is contained in:
Lu Fang
2018-12-04 00:44:43 -08:00
committed by Facebook Github Bot
parent cbd805169f
commit 6e0c5a8a4e
5 changed files with 43 additions and 20 deletions
+9 -2
View File
@@ -215,9 +215,13 @@ TEST(SerializeTest, Optim) {
TEST(SerializeTest, XOR_CUDA) {
torch::manual_seed(0);
// We better be able to save and load a XOR model!
auto getLoss = [](Sequential model, uint32_t batch_size) {
auto getLoss = [](Sequential model, uint32_t batch_size, bool is_cuda=false) {
auto inputs = torch::empty({batch_size, 2});
auto labels = torch::empty({batch_size});
if (is_cuda) {
inputs = inputs.cuda();
labels = labels.cuda();
}
for (size_t i = 0; i < batch_size; i++) {
inputs[i] = torch::randint(2, {2}, torch::kInt64);
labels[i] = inputs[i][0].item<int64_t>() ^ inputs[i][1].item<int64_t>();
@@ -255,10 +259,13 @@ TEST(SerializeTest, XOR_CUDA) {
ASSERT_LT(loss.item<float>(), 0.1);
model2->to(torch::kCUDA);
loss = getLoss(model2, 100, true);
ASSERT_LT(loss.item<float>(), 0.1);
auto tempfile2 = torch::utils::make_tempfile();
torch::save(model2, tempfile2.name);
torch::load(model3, tempfile2.name);
loss = getLoss(model3, 100);
loss = getLoss(model3, 100, true);
ASSERT_LT(loss.item<float>(), 0.1);
}