Libtorch Sequential model is not consistent with pytorch Sequential model

AidanShipperley: <p>Hi, I have a very simple code example that demonstrates that identical implementations of a sequential model in both libtorch and pytorch have inconsistent weights and biases. This is performed on the same computer with the same updated version of libtorch/pytorch:</p>
<p>Python:</p>
<pre><code class="lang-auto">import random
import numpy as np
import torch

random.seed(1)
np.random.seed(1)
torch.manual_seed(1)
torch.backends.cudnn.deterministic = True
torch.use_deterministic_algorithms(True)
torch.backends.cudnn.benchmark = False
print('PyTorch Version:', torch.__version__)

seqModel =  torch.nn.Sequential(
            torch.nn.Linear(2, 2),
            torch.nn.Tanh(),
            torch.nn.Linear(2, 2),
            torch.nn.Tanh(),
            torch.nn.Linear(2, 1)
        )
print('seqModel:\n', seqModel)
for name, param in seqModel.named_parameters():
    print('name:', name, 'size:', param.data.size(), 'data:\n', param.data)
</code></pre>
<p>C++</p>
<pre><code class="lang-auto">std::cout &lt;&lt; "PyTorch version: "
        &lt;&lt; TORCH_VERSION_MAJOR &lt;&lt; "."
        &lt;&lt; TORCH_VERSION_MINOR &lt;&lt; "."
        &lt;&lt; TORCH_VERSION_PATCH &lt;&lt; std::endl;

        srand(1);
        torch::manual_seed(1);
        at::globalContext().setDeterministicCuDNN(true);
        at::globalContext().setDeterministicAlgorithms(true, false);
        at::globalContext().setBenchmarkCuDNN(false);

        auto net = torch::nn::Sequential(
            torch::nn::Linear(2, 2),
            torch::nn::Tanh(),
            torch::nn::Linear(2, 2),
            torch::nn::Tanh(),
            torch::nn::Linear(2, 1)
        );

        std::cout &lt;&lt; net &lt;&lt; std::endl;

        for (auto&amp; p : net-&gt;named_parameters()) {
            std::cout &lt;&lt; p.key() &lt;&lt; std::endl;
            std::cout &lt;&lt; p.value() &lt;&lt; std::endl;
        }
</code></pre>
<p>Python output:</p>
<blockquote>
<p>PyTorch Version: 1.11.0<br>
seqModel:<br>
Sequential(<br>
(0): Linear(in_features=2, out_features=2, bias=True)<br>
(1): Tanh()<br>
(2): Linear(in_features=2, out_features=2, bias=True)<br>
(3): Tanh()<br>
(4): Linear(in_features=2, out_features=1, bias=True)<br>
)<br>
name: 0.weight size: torch.Size([2, 2]) data:<br>
tensor([[ 0.3643, -0.3121],<br>
[-0.1371,  0.3319]])<br>
name: 0.bias size: torch.Size([2]) data:<br>
tensor([-0.6657,  0.4241])<br>
name: 2.weight size: torch.Size([2, 2]) data:<br>
tensor([[-0.1455,  0.3597],<br>
[ 0.0983, -0.0866]])<br>
name: 2.bias size: torch.Size([2]) data:<br>
tensor([0.1961, 0.0349])<br>
name: 4.weight size: torch.Size([1, 2]) data:<br>
tensor([[ 0.2583, -0.2756]])<br>
name: 4.bias size: torch.Size([1]) data:<br>
tensor([-0.0516])</p>
</blockquote>
<p>C++ output:</p>
<blockquote>
<p>PyTorch version: 1.11.0<br>
torch::nn::Sequential(<br>
(0): torch::nn::Linear(in_features=2, out_features=2, bias=true)<br>
(1): torch::nn::Tanh()<br>
(2): torch::nn::Linear(in_features=2, out_features=2, bias=true)<br>
(3): torch::nn::Tanh()<br>
(4): torch::nn::Linear(in_features=2, out_features=1, bias=true)<br>
)<br>
0.weight<br>
-0.0866  0.1961<br>
0.0349  0.2583<br>
[ CPUFloatType{2,2} ]<br>
0.bias<br>
-0.2756<br>
-0.0516<br>
[ CPUFloatType{2} ]<br>
2.weight<br>
0.3319 -0.6657<br>
0.4241 -0.1455<br>
[ CPUFloatType{2,2} ]<br>
2.bias<br>
0.3597<br>
0.0983<br>
[ CPUFloatType{2} ]<br>
4.weight<br>
0.3643 -0.3121<br>
[ CPUFloatType{1,2} ]<br>
4.bias<br>
-0.1371<br>
[ CPUFloatType{1} ]</p>
</blockquote>
<p>Does anybody know what in the world is going on? It’s almost like the random number generation is offset because you can see some of the same numbers shared between the two, they’re just completely in different spots. Is this how it’s supposed to work? Apologies if it’s something simple I missed, I’ve spent days trying to figure this out.</p>
<p>Thank you!</p>

ptrblck: <aside class="quote no-group" data-username="AidanShipperley" data-post="1" data-topic="153556">
<div class="title">
<div class="quote-controls"></div>
<img loading="lazy" alt="" width="24" height="24" src="https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/aidanshipperley/48/59501_2.png" class="avatar"> AidanShipperley:</div>
<blockquote>
<p>It’s almost like the random number generation is offset because you can see some of the same numbers shared between the two, they’re just completely in different spots.</p>
</blockquote>
</aside>
<p>I think this is generally correct. If you seed the code and print a simple <code>torch.randn</code> tensor before initializing the model you would see that the Python API as well as <code>libtorch</code> return the same values, which points to the same logic in these calls.<br>
However, I don’t think there is a guarantee of the same call order in the module <code>libtorch</code> C++ API vs. the Python API, which seems to create the offset.<br>
If you need to use the same parameters, I would recommend to store the model or <code>state_dict</code>.</p>

AidanShipperley: <p>Hi, thank you so much for your suggestion and help. This works if the model is consistent with each run of the program, but the input and output size of my model can change depending on the context in which it’s used, so I can’t have these weights and biases imported from a file.</p>
<p>I found a way to define a sequential with the same weights and biases as in Python without loading it from a file. Since there is something using randomness in the sequential model creation, you can just define the layers of the model before you create the sequential model:</p>
<pre><code class="lang-auto">torch::nn::Linear inputLayer = torch::nn::Linear(2, 2));
torch::nn::Linear middleLayer = torch::nn::Linear(2, 2));
torch::nn::Linear outputLayer = torch::nn::Linear(2, 1));
</code></pre>
<p>And then construct the sequential model like this:</p>
<pre><code class="lang-auto">torch::nn::Sequential critic({
        {"InputLayer" , inputLayer        },
        {"Tanh1"      , torch::nn::Tanh() },
        {"MiddleLayer", middleLayer       },
        {"Tanh2"      , torch::nn::Tanh() },
        {"OutputLayer", OutputLayer       }
    });
</code></pre>
<p>This model will have the exact same weights and biases as the model in python.</p>
<p>However, I’ve recently noticed the outputs produced by the model, which has identical weights and biases to the python model, differ by no more than 0.00001% after some unit testing. But there is still a difference, meaning I can’t use Libtorch it to recreate a python sequential model, especially in the case of a reinforcement learning model where outputs directly affect the environment, and therefore future inputs into the same model.</p>
<p>Does this mean it’s impossible to create a sequential model with dynamic input/output sizes that is consistent in Libtorch and Pytorch?</p>
<p>Thank you!</p>