Convert/import Torch model to PyTorch

As of today, you can deserialize Lua’s .t7 files into PyTorch containing Tensors, numbers, tables, nn models (no nngraph), strings.

We provide the load_lua utility for this purpose.

Here’s an example of saving a tensor in Torch and loading it back in PyTorch


th> a = torch.randn(10)
                                                                      [0.0027s]
th> torch.save('a.t7', a)
                                                                      [0.0010s]
th> a
-1.4479
 1.3707
 0.5663
-1.0590
 0.0706
-1.6495
-1.0805
 0.8277
-0.4595
 0.1237
[torch.DoubleTensor of size 10]

                                                                      [0.0033s]
In [1]: import torch

In [2]: from torch.utils.serialization import load_lua

In [3]: a = load_lua('a.t7')

In [4]: a
Out[4]:

-1.4479
 1.3707
 0.5663
-1.0590
 0.0706
-1.6495
-1.0805
 0.8277
-0.4595
 0.1237
[torch.DoubleTensor of size 10]

Here’s an example of loading a 2 layer sequential neural network:

th> a = nn.Sequential():add(nn.Linear(10, 20)):add(nn.ReLU())
                                                                      [0.0001s]
th> a
nn.Sequential {
  [input -> (1) -> (2) -> output]
  (1): nn.Linear(10 -> 20)
  (2): nn.ReLU
}
                                                                      [0.0001s]
th> torch.save('a.t7', a)
                                                                      [0.0008s]
th>
In [5]: a = load_lua('a.t7')

In [6]: a
Out[6]:
nn.Sequential {
  [input -> (0) -> (1) -> output]
  (0): nn.Linear(10 -> 20)
  (1): nn.ReLU
}

In [7]: a.__class__
Out[7]: torch.legacy.nn.Sequential.Sequential
5 Likes