'backward through the graph' error when optimizing parameter in torch.distributions object

username: cinna
cooked: <p>I am implementing maximum-likelihood estimation using torch.distributions. When the parameter of my distribution is a variable then optimization works fine. But when the parameter is a function of a variable then I get “RuntimeError: Trying to backward through the graph a second time (or directly access saved variables after they have already been freed). Saved intermediate values of the graph are freed when you call .backward() or autograd.grad(). Specify retain_graph=True if you need to backward through the graph a second time or if you need to access saved variables after calling backward.”</p>
<p>Please see below for an example that works and an example that does not work. My goal is to have the parameter that initializes torch.distributions object to be the output of calling a function on my variable rather than the variable itself.</p>
<p>############################################################<br>
import torch<br>
from numpy.random import randn</p>
<p>############ This works #####################</p>
<h1>
<a name="generate-random-data-sample-with-mean5-std1-1" class="anchor" href="#generate-random-data-sample-with-mean5-std1-1"></a>generate random data sample with mean=5, std=1</h1>
<p>data = torch.tensor(randn(1000)+5,dtype=torch.float32)</p>
<h1>
<a name="create-torch-variable-for-the-mean-2" class="anchor" href="#create-torch-variable-for-the-mean-2"></a>create torch variable for the mean</h1>
<p>mu = torch.tensor(0,dtype=torch.float32,requires_grad=True)</p>
<h1>
<a name="create-torch-normal-distribution-object-3" class="anchor" href="#create-torch-normal-distribution-object-3"></a>create torch Normal distribution object</h1>
<p>dist = torch.distributions.Normal(loc=mu,scale=1.0)</p>
<h1>
<a name="create-optimizer-to-maximize-log-likelihood-wrt-mu-4" class="anchor" href="#create-optimizer-to-maximize-log-likelihood-wrt-mu-4"></a>create optimizer to maximize log-likelihood w.r.t mu</h1>
<p>optimizer = torch.optim.RMSprop([mu],lr=0.1)</p>
<p>for i in range(100):<br>
loss = -dist.log_prob(data).sum()<br>
optimizer.zero_grad()<br>
loss.backward()<br>
optimizer.step()</p>
<p>print(mu)<br>
out: tensor(5.0025, requires_grad=True)<br>
######################################################</p>
<p>########### This does <strong>not</strong> work #####################</p>
<h1>
<a name="create-torch-normal-distribution-object-but-the-location-parameter-is-a-function-of-mu-5" class="anchor" href="#create-torch-normal-distribution-object-but-the-location-parameter-is-a-function-of-mu-5"></a>create torch Normal distribution object but the location parameter is a function of mu</h1>
<h1>
<a name="i-know-that-mu0-and-enforce-it-by-using-mu2-for-the-mean-6" class="anchor" href="#i-know-that-mu0-and-enforce-it-by-using-mu2-for-the-mean-6"></a>I know that mu&gt;0 and enforce it by using mu^2 for the mean</h1>
<p>dist = torch.distributions.Normal(loc=<strong>torch.square</strong>(mu),scale=1.0)</p>
<h1>
<a name="create-optimizer-to-maximize-log-likelihood-wrt-mu-7" class="anchor" href="#create-optimizer-to-maximize-log-likelihood-wrt-mu-7"></a>create optimizer to maximize log-likelihood w.r.t mu</h1>
<p>optimizer = torch.optim.RMSprop([mu],lr=0.1)</p>
<p>for i in range(100):<br>
loss = -dist.log_prob(data).sum()<br>
optimizer.zero_grad()<br>
loss.backward()<br>
optimizer.step()</p>
<p>print(mu)<br>
########################################################</p>

username: Nipun_Batra
cooked: <p>Here’s the working code for the second case.</p>
<pre><code class="lang-python">mu = torch.tensor(1.0, dtype=torch.float32, requires_grad=True)


optimizer = torch.optim.RMSprop([mu], lr=0.1)

for i in range(400):
    dist = torch.distributions.Normal(loc=torch.square(mu), scale=1.0)
    loss = -dist.log_prob(data).sum()
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()

print(mu * mu)
</code></pre>

username: cinna
cooked: <p>Your code creates a new instance of torch.distributions.Normal object inside the loop. I am trying to avoid this inefficiency by creating the distribution object outside the loop and training its parameters inside. This works fine in my first example but doesn’t work in the second one.<br>
My use case has many distribution objects that are trained simultaneously and recreating each object in each loop iteration is expensive.</p>