Accumulate gradients with Tensorflow

This post demonstrates how to accumulate gradients with Tensorflow.


Code on my Github

If Github is not loading the Jupyter notebook, a known Github issue, click here to view the notebook on Jupyter’s nbviewer.


import tensorflow as tf

def accumu_grad(self, OPT, loss, scope):
    # retrieve trainable variables in scope of graph
    #tvs = tf.trainable_variables(scope=scope + '/actor')
    tvs = tf.trainable_variables(scope=scope)

    # ceate a list of variables with the same shape as the trainable
    accumu = [tf.Variable(tf.zeros_like(tv.initialized_value()), trainable=False) for tv in tvs]

    zero_op = [tv.assign(tf.zeros_like(tv)) for tv in accumu] # initialized with 0s

    gvs = OPT.compute_gradients(loss, tvs) # obtain list of gradients & variables
    #gvs = [(tf.where( tf.is_nan(grad), tf.zeros_like(grad), grad ), var) for grad, var in gvs]

    # adds to each element from the list you initialized earlier with zeros its gradient
    # accumu and gvs are in same shape, index 0 is grads, index 1 is vars
    accumu_op = [accumu[i].assign_add(gv[0]) for i, gv in enumerate(gvs)]

    apply_op = OPT.apply_gradients([(accumu[i], gv[1]) for i, gv in enumerate(gvs)]) # apply grads

    return zero_op, accumu_op, apply_op, accumu                


2020

PBT for MARL

46 minute read

My attempt to implement a water down version of PBT (Population based training) for MARL (Multi-agent reinforcement learning).

Back to top ↑

2019

.bash_profile for Mac

15 minute read

This post demonstrates how to create customized functions to bundle commands in a .bash_profile file on Mac.

DPPO distributed tensorflow

72 minute read

This post documents my implementation of the Distributed Proximal Policy Optimization (Distributed PPO or DPPO) algorithm. (Distributed continuous version)

A3C distributed tensorflow

27 minute read

This post documents my implementation of the A3C (Asynchronous Advantage Actor Critic) algorithm (Distributed discrete version).

Distributed Tensorflow

76 minute read

This post demonstrates a simple usage example of distributed Tensorflow with Python multiprocessing package.

N-step targets

76 minute read

This post documents my implementation of the N-step Q-values estimation algorithm.

Dueling DDQN with PER

49 minute read

This post documents my implementation of the Dueling Double Deep Q Network with Priority Experience Replay (Duel DDQN with PER) algorithm.

Dueling DDQN

24 minute read

This post documents my implementation of the Dueling Double Deep Q Network (Dueling DDQN) algorithm.

DDQN

29 minute read

This post documents my implementation of the Double Deep Q Network (DDQN) algorithm.

DQN

24 minute read

This post documents my implementation of the Deep Q Network (DQN) algorithm.

Back to top ↑