Pytorch autograd peeking inside

okay_All_Right: <pre><code class="lang-python">import numpy as np

import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim

class Net(nn.Module):

    def __init__(self):
        super(Net, self).__init__()
        self.fc = nn.Linear(3, 1)
        self.a_head = nn.Linear(1, 2)
        self.v_head = nn.Linear(1, 1)
        nn.init.uniform_(self.fc.weight,1,1)
        nn.init.uniform_(self.fc.bias,0,0)
        nn.init.uniform_(self.a_head.weight,1,1)
        nn.init.uniform_(self.a_head.bias,0,0)
        nn.init.uniform_(self.v_head.weight,1,1)
        nn.init.uniform_(self.v_head.bias,0,0)

    def forward(self, x):
        x = F.tanh(self.fc(x))
        a = self.a_head(x) - self.a_head(x).mean(1, keepdim=True)
        v = self.v_head(x)
        action_scores = a + v
        return action_scores

class Model():

    max_grad_norm = 0.5
    def __init__(self):

        self.eval_net, self.target_net = Net().float(), Net().float()
        self.optimizer = optim.Adam(self.eval_net.parameters(), lr=1e-3)
    
    def update(self):

        x1 = torch.tensor([[1,1,1]], dtype=torch.float)
        y1 = torch.tensor([[1]], dtype=torch.long).view(-1, 1)
        x2 = torch.tensor([[1,1,1]], dtype=torch.float)
                
        with torch.no_grad():
            y2 = self.eval_net(s_).max(1, keepdim=True)[1]
            q_target = self.target_net(x2).gather(1, y2)

        q_eval = self.eval_net(x1).gather(1, y1)
        print("__________________x1","_________",y1,"_")
        print("_fc_w",self.eval_net.fc.weight,"fc_b",self.eval_net.fc.bias,"_fc_wgrads",self.eval_net.fc.weight.grad,"_fc_bgrads",self.eval_net.fc.bias.grad)
        print("_a_w",self.eval_net.a_head.weight,"a_b",self.eval_net.a_head.bias,"_a_wgrads",self.eval_net.a_head.weight.grad,"_a_bgrads",self.eval_net.a_head.bias.grad)
        print("_v_w",self.eval_net.v_head.weight,"v_b",self.eval_net.v_head.bias,"_v_wgrads",self.eval_net.v_head.weight.grad,"_v_bgrads",self.eval_net.v_head.bias.grad)

        print("loss",q_eval-q_target)

        self.optimizer.zero_grad() 
        loss = F.smooth_l1_loss(q_eval, 2*q_target)

        loss.backward() # that's where the derivatives are calculated    

        print("loss__",loss)

        #nn.utils.clip_grad_norm_(self.eval_net.parameters(), self.max_grad_norm)
        #self.optimizer.step()

        print("_fc_w",self.eval_net.fc.weight,"fc_b",self.eval_net.fc.bias,"_fc_wgrads",self.eval_net.fc.weight.grad,"_fc_bgrads",self.eval_net.fc.bias.grad)
        print("_a_w",self.eval_net.a_head.weight,"a_b",self.eval_net.a_head.bias,"_a_wgrads",self.eval_net.a_head.weight.grad,"_a_bgrads",self.eval_net.a_head.bias.grad)
        print("_v_w",self.eval_net.v_head.weight,"v_b",self.eval_net.v_head.bias,"_v_wgrads",self.eval_net.v_head.weight.grad,"_v_bgrads",self.eval_net.v_head.bias.grad)

def main():
    model = Model()    
    model.update()
                 
if __name__ == '__main__':
    main()
</code></pre>
<p>well I wrote a little model that that has two networks, eval_net and target_net, with biase 0 and weight 1; data x1 y1 and x2 with 1 as value, just to try to recalculate manually using my calculator and check with pytorch gradients results, but i’m always wrong, so how pytorch computed these grads in this specific model ?</p>
<p>this is the output</p>
<p>_fc_weight.grads =  tensor[[-0.0098, -0.0098, -0.0098]]<br>
_fc_bias.grads =  tensor[-0.0098]</p>
<p>_a_w grads tensor[[ 0.4951],[-0.4951]]<br>
_a_b grads tensor([ 0.4975, -0.4975])</p>
<p>_v_wgrads tensor[[-0.9901]]<br>
_v_bgrads tensor[-0.9951]</p>
<p>manually calculating, but got wrong values gradients, so what is the secret formula for this specific case ?<br>
that’s what i’ve done for <em>a_w_grads:<br>
print("mycalculation</em>_______",p*(1-math.tanh(3)**2)<em>2</em>(p-loss))</p>

okay_All_Right: <p>with this function:</p>
<p>def getBack(var_grad_fn):<br>
print(var_grad_fn)<br>
for n in var_grad_fn.next_functions:<br>
if n[0]:<br>
try:<br>
tensor = getattr(n[0], ‘variable’)<br>
print(n[0])<br>
print(‘Tensor with grad found:’, tensor)<br>
print(’ - gradient:’, tensor.grad)<br>
print()<br>
except AttributeError as e:<br>
getBack(n[0])</p>
<p>I got:<br>
&lt;SmoothL1LossBackward object at 0x00000085E8839280&gt;<br>
&lt;GatherBackward object at 0x00000085E88393D0&gt;<br>
&lt;AddBackward0 object at 0x00000085E8839400&gt;<br>
&lt;SubBackward0 object at 0x00000085E8839370&gt;<br>
&lt;AddmmBackward object at 0x00000085E8839490&gt;<br>
&lt;AccumulateGrad object at 0x00000085E8839550&gt;<br>
Tensor with grad found: Parameter containing:<br>
tensor([0., 0.], requires_grad=True)</p>
<ul>
<li>gradient: tensor([ 0.4975, -0.4975])</li>
</ul>
<p>&lt;TanhBackward object at 0x00000085E8839580&gt;<br>
&lt;AddmmBackward object at 0x00000085E8839670&gt;<br>
&lt;AccumulateGrad object at 0x00000085E8839700&gt;<br>
Tensor with grad found: Parameter containing:<br>
tensor([0.], requires_grad=True)</p>
<ul>
<li>gradient: tensor([-0.0098])</li>
</ul>
<p>&lt;TBackward object at 0x00000085E88396D0&gt;<br>
&lt;AccumulateGrad object at 0x00000085E8839730&gt;<br>
Tensor with grad found: Parameter containing:<br>
tensor([[1., 1., 1.]], requires_grad=True)</p>
<ul>
<li>gradient: tensor([[-0.0098, -0.0098, -0.0098]])</li>
</ul>
<p>&lt;TBackward object at 0x00000085E88395B0&gt;<br>
&lt;AccumulateGrad object at 0x00000085E8839670&gt;<br>
Tensor with grad found: Parameter containing:<br>
tensor([[1.],<br>
[1.]], requires_grad=True)</p>
<ul>
<li>gradient: tensor([[ 0.4951],<br>
[-0.4951]])</li>
</ul>
<p>&lt;MeanBackward1 object at 0x00000085E88394C0&gt;<br>
&lt;AddmmBackward object at 0x00000085E88395B0&gt;<br>
&lt;AccumulateGrad object at 0x00000085E8839550&gt;<br>
Tensor with grad found: Parameter containing:<br>
tensor([0., 0.], requires_grad=True)</p>
<ul>
<li>gradient: tensor([ 0.4975, -0.4975])</li>
</ul>
<p>&lt;TanhBackward object at 0x00000085E8839580&gt;<br>
&lt;AddmmBackward object at 0x00000085E88396D0&gt;<br>
&lt;AccumulateGrad object at 0x00000085E8839700&gt;<br>
Tensor with grad found: Parameter containing:<br>
tensor([0.], requires_grad=True)</p>
<ul>
<li>gradient: tensor([-0.0098])</li>
</ul>
<p>&lt;TBackward object at 0x00000085E8839730&gt;<br>
&lt;AccumulateGrad object at 0x00000085E8839790&gt;<br>
Tensor with grad found: Parameter containing:<br>
tensor([[1., 1., 1.]], requires_grad=True)</p>
<ul>
<li>gradient: tensor([[-0.0098, -0.0098, -0.0098]])</li>
</ul>
<p>&lt;TBackward object at 0x00000085E8839670&gt;<br>
&lt;AccumulateGrad object at 0x00000085E88396D0&gt;<br>
Tensor with grad found: Parameter containing:<br>
tensor([[1.],<br>
[1.]], requires_grad=True)</p>
<ul>
<li>gradient: tensor([[ 0.4951],<br>
[-0.4951]])</li>
</ul>
<p>&lt;AddmmBackward object at 0x00000085E8839460&gt;<br>
&lt;AccumulateGrad object at 0x00000085E88394C0&gt;<br>
Tensor with grad found: Parameter containing:<br>
tensor([0.], requires_grad=True)</p>
<ul>
<li>gradient: tensor([-0.9951])</li>
</ul>
<p>&lt;TanhBackward object at 0x00000085E88394F0&gt;<br>
&lt;AddmmBackward object at 0x00000085E88395E0&gt;<br>
&lt;AccumulateGrad object at 0x00000085E8839550&gt;<br>
Tensor with grad found: Parameter containing:<br>
tensor([0.], requires_grad=True)</p>
<ul>
<li>gradient: tensor([-0.0098])</li>
</ul>
<p>&lt;TBackward object at 0x00000085E88396A0&gt;<br>
&lt;AccumulateGrad object at 0x00000085E88396D0&gt;<br>
Tensor with grad found: Parameter containing:<br>
tensor([[1., 1., 1.]], requires_grad=True)</p>
<ul>
<li>gradient: tensor([[-0.0098, -0.0098, -0.0098]])</li>
</ul>
<p>&lt;TBackward object at 0x00000085E8839490&gt;<br>
&lt;AccumulateGrad object at 0x00000085E88395E0&gt;<br>
Tensor with grad found: Parameter containing:<br>
tensor([[1.]], requires_grad=True)</p>
<ul>
<li>gradient: tensor([[-0.9901]])</li>
</ul>
<p>doesnt help a lot</p>

albanD: <p>Hi,</p>
<p>The grads are computed for each elementary functions from the end to the start.<br>
You might want to check with a simple model if you want to write the formula by hand.</p>
<p>Also I’m not sure the formula for the gradient fo the smooth l1 loss is correct in the one like you shared.</p>
<p>If you want to print the graph of all the backward functions, I would recommend <a href="https://github.com/szagoruyko/pytorchviz">this</a> package which will make it much easier to visualize.</p>

okay_All_Right: <pre><code class="lang-python">inp = torch.tensor([[1,1,1]], dtype=torch.float)

i = torch.tensor([[1]], dtype=torch.long).view(-1, 1)

outp = self.eval_net(inp).gather(1, i)

self.optimizer.zero_grad()

loss = F.smooth_l1_loss(q_eval, 0*q_eval)

loss.backward()
</code></pre>
<p>so how the backward work if(eval_net) has multiple outputs ?</p>
<pre><code class="lang-python">class Net(nn.Module):
  def **init** (self):
    super(Net, self). **init** ()
    self.fc = nn.Linear(3, 1)
    self.a_head = nn.Linear(1, 2) #in this case two outputs
</code></pre>
<h1><a href="https://discuss.pytorch.org/t/how-loss-of-dimension-1-can-work-with-output-of-n-dimension-when-backward/95469">How loss of dimension 1 can work with output of n dimension when backward</a></h1>
<p>torchviz doesn’t show the math behind the derivatives</p>

albanD: <aside class="quote no-group" data-username="okay_All_Right" data-post="4" data-topic="95381">
<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/okay_all_right/48/28493_2.png" class="avatar"> okay_All_Right:</div>
<blockquote>
<p>torchviz doesn’t show the math behind the derivatives</p>
</blockquote>
</aside>
<p>But hopefully the math for these simple function should be easy to derive.<br>
At least it gives you the structure of the calculations.</p>
<blockquote>
<p>so how the backward work if(eval_net) has multiple outputs ?</p>
</blockquote>
<p>What do you mean? In your code example above, it returns a single Tensor that you call gather on right?</p>
<p>PS: You can put your code examples in between triple ticks ``` to make them look better (check how I edited your last message).</p>

okay_All_Right: <p>I’m going to be clear, <img src="https://discuss.pytorch.org/images/emoji/apple/slight_smile.png?v=9" title=":slight_smile:" class="emoji" alt=":slight_smile:"> I hate pytorch or any rl framework they are parasites, for that I wrote my own dqn that solves pendulumv0, I copied every piece of code from to numpy but it’s not still working, can someone debug the code, it’s the best that I could do come with<br>
</p><aside class="onebox allowlistedgeneric">
  <header class="source">
      <img src="https://github.githubassets.com/favicons/favicon.svg" class="site-icon" width="16" height="16">
      <a href="https://github.com/Isawyou/dqn-numpy-only-not-working/tree/master" target="_blank" rel="nofollow noopener">GitHub</a>
  </header>
  <article class="onebox-body">
    <img src="https://avatars3.githubusercontent.com/u/59315334?s=400&amp;v=4" class="thumbnail onebox-avatar" width="60" height="60">

<h3><a href="https://github.com/Isawyou/dqn-numpy-only-not-working/tree/master" target="_blank" rel="nofollow noopener">Isawyou/dqn-numpy-only-not-working</a></h3>

<p>the second file is pytorch implementation, solves Pendulum-v0 in one minute, I copied every piece of code, still not working, is there something wrong ? contact me if there is a bug to solve Pendul...</p>


  </article>
  <div class="onebox-metadata">
    
    
  </div>
  <div style="clear: both"></div>
</aside>


albanD: <aside class="quote no-group" data-username="okay_All_Right" data-post="6" data-topic="95381">
<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/okay_all_right/48/28493_2.png" class="avatar"> okay_All_Right:</div>
<blockquote>
<p>any rl framework they are parasites</p>
</blockquote>
</aside>
<p>Well they do help quite a lot to avoid having such issues.<br>
You don’t have to spend days computing gradients by hand and even more debugging them.</p>
<p>From looking at your code, I’m not sure how you define the gradient from the loss function, and given that your optimizer is already flipping the sign of the gradient, you should not do it there.<br>
Also your tanh formula is wrong as its missing the chain rule that mutiplies it by the flowing gradients.<br>
There might be other issues though…</p>

okay_All_Right: <p>your optimizer already flipping the sign of the gradient— where what line ?<br>
tanh formula wrong ? I dont see that …</p>
<p>well can you just refix the code and show me what you’ve got, because I really need that code, and also that why I hate using frameworks because they solve things for you without  understanding a nible of what they do, and also they’re heavier. thanks you so much anyway, I’ve been struggling for about month right know.</p>

albanD: <p>where what line ? where what line ?</p>
<p><a href="https://github.com/Isawyou/dqn-numpy-only-not-working/blob/c91a1b788523497f52ca6497c604851e76a97c3a/dqn%20numpy%20only/actor_net.py#L104" class="onebox" target="_blank" rel="noopener">https://github.com/Isawyou/dqn-numpy-only-not-working/blob/c91a1b788523497f52ca6497c604851e76a97c3a/dqn%20numpy%20only/actor_net.py#L104</a></p>
<blockquote>
<p>I dont see that …</p>
</blockquote>
<p>The chain rule says you should multiply the gradient with the derivative of the current function.<br>
If I understand correctly that <a href="https://github.com/Isawyou/dqn-numpy-only-not-working/blob/c91a1b788523497f52ca6497c604851e76a97c3a/dqn%20numpy%20only/actor_net.py#L46">this</a> tries to compute the gradient wrt of the output of the first linear, then you’re definitely missing a <code>grad_a</code> or <code>out1</code> somewhere in that formula.</p>
<blockquote>
<p>well can you just refix the code</p>
</blockquote>
<p>As I said above, writing this kind of code by hand would take way too much time as there are so many places where you can make subtle mistakes. I’m afraid I don’t have the time to do that for you.</p>
<blockquote>
<p>I hate using frameworks because they solve things for you without understanding a nible of what they do</p>
</blockquote>
<p>Yes, but depending on what you want to do, you don’t need to understand all the details.<br>
And even if you do understand all the details, it does not mean that you can re-implement the whole thing, bug-free, easily.</p>

okay_All_Right: <p>yeah, just like everybody, well all depend on pytorch to do the work for us, nobody can replicate what it does, I’m trying to break this idea, not you?</p>

albanD: <p>You can replicate it but you will need to use the right concept.<br>
Writing derivatives by hand works fine for linear of trivial problems.<br>
If you start having networks, you might need to have the backprop done automatically using something that looks like AD. Otherwise, as you see in your repo, the code becomes hard to read (and buggy) very quickly.</p>
<p>I prefer to spend time making pytorch do more stuff instead of re-implementing it. But that’s a personal choice <img src="https://discuss.pytorch.org/images/emoji/apple/slight_smile.png?v=9" title=":slight_smile:" class="emoji" alt=":slight_smile:"></p>

okay_All_Right: <p>and that’s why I’m lonely!</p>

okay_All_Right: <p>you was right about tanh, I’ve done an error <img src="https://discuss.pytorch.org/images/emoji/apple/slight_smile.png?v=9" title=":slight_smile:" class="emoji" alt=":slight_smile:"></p>

okay_All_Right: <p>import argparse</p>
<p>import pickle</p>
<p>from collections import namedtuple</p>
<p>import matplotlib.pyplot as plt</p>
<p>import numpy as np</p>
<p>import gym</p>
<p>import torch</p>
<p>import torch.nn as nn</p>
<p>import torch.nn.functional as F</p>
<p>import torch.optim as optim</p>
<p>parser = argparse.ArgumentParser(description=‘Solve the Pendulum-v0 with DQN’)</p>
<p>parser.add_argument(</p>
<pre><code>'--gamma', type=float, default=0.9, metavar='G', help='discount factor (default: 0.9)')
</code></pre>
<p>parser.add_argument(</p>
<pre><code>'--num_actions', type=int, default=5, metavar='N', help='discretize action space (default: 5)')
</code></pre>
<p>parser.add_argument(’–seed’, type=int, default=0, metavar=‘N’, help=‘random seed (default: 0)’)</p>
<p>parser.add_argument(’–render’, action=‘store_true’, help=‘render the environment’)</p>
<p>parser.add_argument(</p>
<pre><code>'--log-interval',

type=int,

default=10,

metavar='N',

help='interval between training status logs (default: 10)')
</code></pre>
<p>args = parser.parse_args()</p>
<p>torch.manual_seed(args.seed)</p>
<p>np.random.seed(args.seed)</p>
<p>TrainingRecord = namedtuple(‘TrainingRecord’, [‘ep’, ‘reward’])</p>
<p>Transition = namedtuple(‘Transition’, [‘s’, ‘a’, ‘r’, ‘s_’])</p>
<p>class Opt():</p>
<pre><code>def __init__(self):



    self.params = {}

    self.params['W1'] = self._uniform_init(3, 100)

    self.params['b1'] = np.zeros(100)

    self.params['W2'] = self._uniform_init(100, 5)

    self.params['b2'] = np.zeros(5)

    self.grads = {}

    self.grads['W1'] = self._uniform_init(3, 100)

    self.grads['b1'] = np.zeros(100)

    self.grads['W2'] = self._uniform_init(100, 5)

    self.grads['b2'] = np.zeros(5)



    self.optm_cfg ={}

    self.optm_cfg['W1'] = None

    self.optm_cfg['b1'] = None

    self.optm_cfg['W2'] = None

    self.optm_cfg['b2'] = None

def train(self):



    self.params['W2'] = self._adam(self.params['W2'], self.grads['W2'], config=self.optm_cfg['W2'])[0]

    self.params['W1'] = self._adam(self.params['W1'], self.grads['W1'], config=self.optm_cfg['W1'])[0]

    self.params['b2'] = self._adam(self.params['b2'], self.grads['b2'], config=self.optm_cfg['b2'])[0]

    self.params['b1'] = self._adam(self.params['b1'], self.grads['b1'], config=self.optm_cfg['b1'])[0]

    #print("_a_b", self.params['b2'])

    #print("_fc_b", self.params['b1'])

    # Update the configuration parameters to be used in the next iteration

    self.optm_cfg['W2'] = self._adam(self.params['W2'], self.grads['W2'], config=self.optm_cfg['W2'])[1]

    self.optm_cfg['W1'] = self._adam(self.params['W1'], self.grads['W1'], config=self.optm_cfg['W1'])[1]

    self.optm_cfg['b2'] = self._adam(self.params['b2'], self.grads['b2'], config=self.optm_cfg['b2'])[1]

    self.optm_cfg['b1'] = self._adam(self.params['b1'], self.grads['b1'], config=self.optm_cfg['b1'])[1]



def _adam(self, x, dx, config=None):

  

    if config is None: config = {}

    config.setdefault('learning_rate', 1e-3)

    config.setdefault('beta1', 0.9)

    config.setdefault('beta2', 0.999)

    config.setdefault('epsilon', 1e-8)

    config.setdefault('m', np.zeros_like(x))

    config.setdefault('v', np.zeros_like(x))

    config.setdefault('t', 0)

  

    next_x = None

  

    #Adam update formula,                                                 #

    config['t'] += 1

    config['m'] = config['beta1']*config['m'] + (1-config['beta1'])*dx

    config['v'] = config['beta2']*config['v'] + (1-config['beta2'])*(dx**2)

    bias_corr1 = (1 - config['beta1']**config['t'])

    bias_corr2 =  (1 - config['beta2']**config['t'])

  

    denom=(np.sqrt(config['v'])) / (np.sqrt(bias_corr2)+config['epsilon'])

 

    step_size=config['learning_rate'] / bias_corr1

  

    next_x= x + (-step_size)*(config['m']/denom)

    if(len(next_x.shape)&gt;1):

        import math

        for i in range(len(next_x[0])):

            if(math.isnan(next_x[0,i])):

                next_x[0,i]=x[0,i]

    else:

       import math

       for i in range(len(next_x)):

            if(math.isnan(next_x[i])):

                next_x[i]=x[i]

    return next_x, config

def _uniform_init(self, input_size, output_size):

    u = np.sqrt(6./(input_size+output_size))

    return np.random.uniform(-u, u, (input_size, output_size))
</code></pre>
<p>class Net(nn.Module):</p>
<pre><code>def __init__(self):

    super(Net, self).__init__()

    self.fc = nn.Linear(3, 100)

    self.a_head = nn.Linear(100, args.num_actions)

def forward(self, x):

    x = F.relu(self.fc(x))

    a = self.a_head(x) 

    action_scores = a 

    return action_scores
</code></pre>
<p>class Memory():</p>
<pre><code>data_pointer = 0

isfull = False

def __init__(self, capacity):

    self.memory = np.empty(capacity, dtype=object)

    self.capacity = capacity

def update(self, transition):

    self.memory[self.data_pointer] = transition

    self.data_pointer += 1

    if self.data_pointer == self.capacity:

        self.data_pointer = 0

        self.isfull = True

def sample(self, batch_size):

    return np.random.choice(self.memory, batch_size)
</code></pre>
<p>class Agent():</p>
<pre><code>action_list = [( -2,) ,(2,) ,(3,) ,(-3,),(4,) ]

max_grad_norm = 0.5

def __init__(self):

    self.training_step = 0

    self.epsilon = 1

    self.eval_net, self.target_net = Net().float(), Net().float()

    self.memory = Memory(2000)

    self.optimizer = optim.Adam(self.eval_net.parameters(), lr=1e-3)

    self.opt=Opt()

def select_action(self, state):

    state = torch.from_numpy(state).float().unsqueeze(0)

    if np.random.random() &lt; self.epsilon:

        action_index = np.random.randint(args.num_actions)

    else:

        probs = self.eval_net(state)

        action_index = probs.max(1)[1].item()

    return self.action_list[action_index], action_index

def save_param(self):

    torch.save(self.eval_net.state_dict(), 'param/dqn_net_params.pkl')

def store_transition(self, transition):

    self.memory.update(transition)

def update(self):

    self.training_step += 1

    transitions = self.memory.sample(32)

    s = torch.tensor([t.s for t in transitions], dtype=torch.float)

    a = torch.tensor([t.a for t in transitions], dtype=torch.long).view(-1, 1)

    r = torch.tensor([t.r for t in transitions], dtype=torch.float).view(-1, 1)

    s_ = torch.tensor([t.s_ for t in transitions], dtype=torch.float)

    # natural dqn

    # q_eval = self.eval_net(s).gather(1, a)

    # with torch.no_grad():

    #     q_target = r + args.gamma * self.target_net(s_).max(1, keepdim=True)[0]

    # double dqn

    with torch.no_grad():

        a_ = self.eval_net(s_).max(1, keepdim=True)[1]

        q_target = r + args.gamma * self.target_net(s_).gather(1, a_)

    q_eval = self.eval_net(s).gather(1, a)

    self.optimizer.zero_grad()

    loss = F.smooth_l1_loss(q_eval, q_target)

    loss.backward()

    #nn.utils.clip_grad_norm_(self.eval_net.parameters(), self.max_grad_norm)

    #self.optimizer.step()

    with torch.no_grad():

        for i in range(100):

            for j in range(5):

                self.opt.grads['b2'][j]=self.eval_net.a_head.bias.grad[j]

                self.opt.grads['W2'][i,j]=self.eval_net.a_head.weight.grad[j,i]

        for i in range(3):

            for j in range(100):

                self.opt.grads['b1'][j]=self.eval_net.fc.bias.grad[j]

                self.opt.grads['W1'][i,j]=self.eval_net.fc.weight.grad[j,i]

    

        self.opt.train()

    

        for i in range(100):

            for j in range(5):

                self.eval_net.a_head.bias[j]=self.opt.params['b2'][j]

                self.eval_net.a_head.weight[j,i]=self.opt.params['W2'][i,j]

        for i in range(3):

            for j in range(100):

                self.eval_net.fc.bias[j]=self.opt.params['b1'][j]

                self.eval_net.fc.weight[j,i]=self.opt.params['W1'][i,j]
    
    if self.training_step % 200 == 0:

        self.target_net.load_state_dict(self.eval_net.state_dict())

    self.epsilon = max(self.epsilon * 0.999, 0.01)

    return q_eval.mean().item()
</code></pre>
<p>def main():</p>
<pre><code>env = gym.make('Pendulum-v0')

env.seed(args.seed)

agent = Agent()

training_records = []

running_reward, running_q = -1000, 0

state = env.reset()

for i_ep in range(100):

    score = 0

    

    for t in range(200000000000):

        action, action_index = agent.select_action(state)

        state_, reward, done, _ = env.step(action)

        score += reward

        if True:

            env.render()

        agent.store_transition(Transition(state, action_index, (reward + 8) / 8, state_))

        state = state_

        if agent.memory.isfull:

            q = agent.update()

            running_q = 0.99 * running_q + 0.01 * q

    running_reward = running_reward * 0.9 + score * 0.1

    training_records.append(TrainingRecord(i_ep, running_reward))

    if i_ep % args.log_interval == 0:

        print('Ep {}\tAverage score: {:.2f}\tAverage Q: {:.2f}'.format(

            i_ep, running_reward, running_q))

    if running_reward &gt; -200:

        print("Solved! Running reward is now {}!".format(running_reward))

        env.close()

        agent.save_param()

        with open('log/dqn_training_records.pkl', 'wb') as f:

            pickle.dump(training_records, f)

        break

env.close()

plt.plot([r.ep for r in training_records], [r.reward for r in training_records])

plt.title('DQN')

plt.xlabel('Episode')

plt.ylabel('Moving averaged episode reward')

plt.savefig("img/dqn.png")

plt.show()
</code></pre>
<p>if <strong>name</strong> == ‘<strong>main</strong>’:</p>
<pre><code>main()
</code></pre>
<p>I’ve implented adam by hand, not working why, if I uncomment the optimizer.step(), its working,<br>
I copied this <a href="https://pytorch.org/docs/stable/_modules/torch/optim/adam.html#Adam.step" rel="nofollow noopener">https://pytorch.org/docs/stable/_modules/torch/optim/adam.html#Adam.step</a></p>

okay_All_Right: <p>well, it sounds like doing RMSprop by hand works like a charm, <img src="https://discuss.pytorch.org/images/emoji/apple/slight_smile.png?v=9" title=":slight_smile:" class="emoji" alt=":slight_smile:"> I conclude that adam has floating point unstability, I think that I solved ! who wants the source code, contacts me ! cheers</p>