title: How can I fix the scaling optimization pytorch code error
body: <p>I want make a scaling optimization system</p>
  <pre><code>
  class GraphFit:
    def __init__(self):
      self.X=torch.tensor([])
      self.Y=torch.tensor([])
  
      self.scale_x=torch.Tensor([])
      self.scale_y=torch.Tensor([])
  
      self.opt=0
    
    def scale(self,imagx=1.,imagy=1):
      self.scale_x=torch.tensor([1.],requires_grad=True)
      self.scale_y=torch.tensor([1.],requires_grad=True)
  
      self.X=self.scale_x *self.X
      self.Y=self.scale_y *self.Y
  
    def optimize(self,lr=1e-03):
      params=[self.scale_x,self.scale_y]
      self.opt=torch.optim.Adam(params,lr)    
    
  
  
      
  
  
  x=torch.linspace(-10,10,100)
   
  yt=0.5*torch.sin(0.2 * x)   ##truth 
  
  y=torch.sin(x)   ## try
  
  G1=GraphFit()
  G1.X=x
  
  G1.scale()    
  
  G1.optimize()
  
  L=nn.MSELoss()
  
  
  for i in range(1):  ####
    G1.opt.zero_grad() 
    G1.Y=torch.sin(G1.X)
    err=L(G1.Y,yt)
    err.backward()
    G1.opt.step()
  
    if i%100==0:
      print(err)
  
  print(G1.scale_y.grad,G1.scale_x.grad)
  
  </code></pre>
  <p>When I use  'for i in range(1)' , its output is</p>
  <pre><code>tensor(0.1189, grad_fn=&lt;MseLossBackward&gt;)
  None tensor([-0.0425])
  </code></pre>
  <p>and when I use 'for i in range(N)' for N &gt;1</p>
  <p>it's output is</p>
  <pre><code>---&gt; 83   err.backward()
  
  Trying to backward through the graph a second time, but the buffers have already been freed. Specify retain_graph=True when calling backward the first time.
  </code></pre>
  <p>What is the problem and how can I fix it?</p>
  <p><code> </code>
  <code> </code></p>
  <p>########################</p>
  <p>dummydummydummydummydummydummydummydummydummydummy
  dummydummydummydummydummydummydummydummydummydummy
  dummydummydummydummydummydummydummydummydummydummy
  dummydummydummydummydummydummydummydummydummydummy</p>