moving the docs to github
BIN
docs_raw/docs/algorithms/design_imgs/ac.png
Normal file
|
After Width: | Height: | Size: 30 KiB |
BIN
docs_raw/docs/algorithms/design_imgs/bs_dqn.png
Normal file
|
After Width: | Height: | Size: 13 KiB |
BIN
docs_raw/docs/algorithms/design_imgs/ddpg.png
Normal file
|
After Width: | Height: | Size: 23 KiB |
BIN
docs_raw/docs/algorithms/design_imgs/dfp.png
Normal file
|
After Width: | Height: | Size: 37 KiB |
BIN
docs_raw/docs/algorithms/design_imgs/distributional_dqn.png
Normal file
|
After Width: | Height: | Size: 17 KiB |
BIN
docs_raw/docs/algorithms/design_imgs/dqn.png
Normal file
|
After Width: | Height: | Size: 14 KiB |
BIN
docs_raw/docs/algorithms/design_imgs/dueling_dqn.png
Normal file
|
After Width: | Height: | Size: 25 KiB |
BIN
docs_raw/docs/algorithms/design_imgs/naf.png
Normal file
|
After Width: | Height: | Size: 33 KiB |
BIN
docs_raw/docs/algorithms/design_imgs/nec.png
Normal file
|
After Width: | Height: | Size: 47 KiB |
BIN
docs_raw/docs/algorithms/design_imgs/pg.png
Normal file
|
After Width: | Height: | Size: 14 KiB |
BIN
docs_raw/docs/algorithms/design_imgs/ppo.png
Normal file
|
After Width: | Height: | Size: 38 KiB |
25
docs_raw/docs/algorithms/imitation/bc.md
Normal file
@@ -0,0 +1,25 @@
|
||||
# Behavioral Cloning
|
||||
|
||||
**Actions space:** Discrete|Continuous
|
||||
|
||||
## Network Structure
|
||||
|
||||
<p style="text-align: center;">
|
||||
|
||||
<img src="..\..\design_imgs\dqn.png">
|
||||
|
||||
</p>
|
||||
|
||||
|
||||
|
||||
## Algorithm Description
|
||||
|
||||
### Training the network
|
||||
|
||||
The replay buffer contains the expert demonstrations for the task.
|
||||
These demonstrations are given as state, action tuples, and with no reward.
|
||||
The training goal is to reduce the difference between the actions predicted by the network and the actions taken by the expert for each state.
|
||||
|
||||
1. Sample a batch of transitions from the replay buffer.
|
||||
2. Use the current states as input to the network, and the expert actions as the targets of the network.
|
||||
3. The loss function for the network is MSE, and therefore we use the Q head to minimize this loss.
|
||||
25
docs_raw/docs/algorithms/other/dfp.md
Normal file
@@ -0,0 +1,25 @@
|
||||
# Direct Future Prediction
|
||||
|
||||
**Actions space:** Discrete
|
||||
|
||||
**References:** [Learning to Act by Predicting the Future](https://arxiv.org/abs/1611.01779)
|
||||
|
||||
## Network Structure
|
||||
|
||||
<p style="text-align: center;">
|
||||
|
||||
<img src="../../design_imgs/dfp.png" width=600>
|
||||
|
||||
</p>
|
||||
|
||||
## Algorithm Description
|
||||
### Choosing an action
|
||||
|
||||
1. The current states (observations and measurements) and the corresponding goal vector are passed as an input to the network. The output of the network is the predicted future measurements for time-steps $t+1,t+2,t+4,t+8,t+16$ and $t+32$ for each possible action.
|
||||
2. For each action, the measurements of each predicted time-step are multiplied by the goal vector, and the result is a single vector of future values for each action.
|
||||
3. Then, a weighted sum of the future values of each action is calculated, and the result is a single value for each action.
|
||||
4. The action values are passed to the exploration policy to decide on the action to use.
|
||||
|
||||
### Training the network
|
||||
|
||||
Given a batch of transitions, run them through the network to get the current predictions of the future measurements per action, and set them as the initial targets for training the network. For each transition $(s_t,a_t,r_t,s_{t+1} )$ in the batch, the target of the network for the action that was taken, is the actual measurements that were seen in time-steps $t+1,t+2,t+4,t+8,t+16$ and $t+32$. For the actions that were not taken, the targets are the current values.
|
||||
27
docs_raw/docs/algorithms/policy_optimization/ac.md
Normal file
@@ -0,0 +1,27 @@
|
||||
# Actor-Critic
|
||||
|
||||
**Actions space:** Discrete|Continuous
|
||||
|
||||
**References:** [Asynchronous Methods for Deep Reinforcement Learning](https://arxiv.org/abs/1602.01783)
|
||||
|
||||
## Network Structure
|
||||
<p style="text-align: center;">
|
||||
<img src="..\..\design_imgs\ac.png" width=500>
|
||||
</p>
|
||||
## Algorithm Description
|
||||
|
||||
### Choosing an action - Discrete actions
|
||||
|
||||
The policy network is used in order to predict action probabilites. While training, a sample is taken from a categorical distribution assigned with these probabilities. When testing, the action with the highest probability is used.
|
||||
|
||||
### Training the network
|
||||
A batch of $ T_{max} $ transitions is used, and the advantages are calculated upon it.
|
||||
|
||||
Advantages can be calculated by either of the following methods (configured by the selected preset) -
|
||||
|
||||
1. **A_VALUE** - Estimating advantage directly:$$ A(s_t, a_t) = \underbrace{\sum_{i=t}^{i=t + k - 1} \gamma^{i-t}r_i +\gamma^{k} V(s_{t+k})}_{Q(s_t, a_t)} - V(s_t) $$where $k$ is $T_{max} - State\_Index$ for each state in the batch.
|
||||
2. **GAE** - By following the [Generalized Advantage Estimation](https://arxiv.org/abs/1506.02438) paper.
|
||||
|
||||
The advantages are then used in order to accumulate gradients according to
|
||||
$$ L = -\mathop{\mathbb{E}} [log (\pi) \cdot A] $$
|
||||
|
||||
28
docs_raw/docs/algorithms/policy_optimization/cppo.md
Normal file
@@ -0,0 +1,28 @@
|
||||
# Clipped Proximal Policy Optimization
|
||||
|
||||
**Actions space:** Discrete|Continuous
|
||||
|
||||
**References:** [Proximal Policy Optimization Algorithms](https://arxiv.org/pdf/1707.06347.pdf)
|
||||
|
||||
## Network Structure
|
||||
|
||||
<p style="text-align: center;">
|
||||
<img src="..\..\design_imgs\ppo.png">
|
||||
</p>
|
||||
|
||||
|
||||
## Algorithm Description
|
||||
### Choosing an action - Continuous action
|
||||
Same as in PPO.
|
||||
### Training the network
|
||||
Very similar to PPO, with several small (but very simplifying) changes:
|
||||
|
||||
1. Train both the value and policy networks, simultaneously, by defining a single loss function, which is the sum of each of the networks loss functions. Then, back propagate gradients only once from this unified loss function.
|
||||
|
||||
2. The unified network's optimizer is set to Adam (instead of L-BFGS for the value network as in PPO).
|
||||
|
||||
3. Value targets are now also calculated based on the GAE advantages. In this method, the $ V $ values are predicted from the critic network, and then added to the GAE based advantages, in order to get a $ Q $ value for each action. Now, since our critic network is predicting a $ V $ value for each state, setting the $ Q $ calculated action-values as a target, will on average serve as a $ V $ state-value target.
|
||||
|
||||
4. Instead of adapting the penalizing KL divergence coefficient used in PPO, the likelihood ratio $r_t(\theta) =\frac{\pi_{\theta}(a|s)}{\pi_{\theta_{old}}(a|s)}$ is clipped, to achieve a similar effect. This is done by defining the policy's loss function to be the minimum between the standard surrogate loss and an epsilon clipped surrogate loss:
|
||||
|
||||
$$L^{CLIP}(\theta)=E_{t}[min(r_t(\theta)\cdot \hat{A}_t, clip(r_t(\theta), 1-\epsilon, 1+\epsilon) \cdot \hat{A}_t)] $$
|
||||
32
docs_raw/docs/algorithms/policy_optimization/ddpg.md
Normal file
@@ -0,0 +1,32 @@
|
||||
# Deep Deterministic Policy Gradient
|
||||
|
||||
**Actions space:** Continuous
|
||||
|
||||
**References:** [Continuous control with deep reinforcement learning](https://arxiv.org/abs/1509.02971)
|
||||
|
||||
## Network Structure
|
||||
|
||||
<p style="text-align: center;">
|
||||
|
||||
<img src="..\..\design_imgs\ddpg.png">
|
||||
|
||||
</p>
|
||||
|
||||
## Algorithm Description
|
||||
### Choosing an action
|
||||
Pass the current states through the actor network, and get an action mean vector $ \mu $. While in training phase, use a continuous exploration policy, such as the Ornstein-Uhlenbeck process, to add exploration noise to the action. When testing, use the mean vector $\mu$ as-is.
|
||||
### Training the network
|
||||
Start by sampling a batch of transitions from the experience replay.
|
||||
|
||||
* To train the **critic network**, use the following targets:
|
||||
|
||||
$$ y_t=r(s_t,a_t )+\gamma \cdot Q(s_{t+1},\mu(s_{t+1} )) $$
|
||||
First run the actor target network, using the next states as the inputs, and get $ \mu (s_{t+1} ) $. Next, run the critic target network using the next states and $ \mu (s_{t+1} ) $, and use the output to calculate $ y_t $ according to the equation above. To train the network, use the current states and actions as the inputs, and $y_t$ as the targets.
|
||||
|
||||
* To train the **actor network**, use the following equation:
|
||||
|
||||
$$ \nabla_{\theta^\mu } J \approx E_{s_t \tilde{} \rho^\beta } [\nabla_a Q(s,a)|_{s=s_t,a=\mu (s_t ) } \cdot \nabla_{\theta^\mu} \mu(s)|_{s=s_t} ] $$
|
||||
Use the actor's online network to get the action mean values using the current states as the inputs. Then, use the critic online network in order to get the gradients of the critic output with respect to the action mean values $ \nabla _a Q(s,a)|_{s=s_t,a=\mu(s_t ) } $. Using the chain rule, calculate the gradients of the actor's output, with respect to the actor weights, given $ \nabla_a Q(s,a) $. Finally, apply those gradients to the actor network.
|
||||
|
||||
After every training step, do a soft update of the critic and actor target networks' weights from the online networks.
|
||||
|
||||
27
docs_raw/docs/algorithms/policy_optimization/pg.md
Normal file
@@ -0,0 +1,27 @@
|
||||
# Policy Gradient
|
||||
|
||||
**Actions space:** Discrete|Continuous
|
||||
|
||||
**References:** [Simple Statistical Gradient-Following Algorithms for Connectionist Reinforcement Learning](http://www-anw.cs.umass.edu/~barto/courses/cs687/williams92simple.pdf)
|
||||
|
||||
## Network Structure
|
||||
|
||||
<p style="text-align: center;">
|
||||
|
||||
<img src="..\..\design_imgs\pg.png">
|
||||
|
||||
</p>
|
||||
|
||||
## Algorithm Description
|
||||
### Choosing an action - Discrete actions
|
||||
Run the current states through the network and get a policy distribution over the actions. While training, sample from the policy distribution. When testing, take the action with the highest probability.
|
||||
|
||||
### Training the network
|
||||
The policy head loss is defined as $ L=-log (\pi) \cdot PolicyGradientRescaler $. The $PolicyGradientRescaler$ is used in order to reduce the policy gradient variance, which might be very noisy. This is done in order to reduce the variance of the updates, since noisy gradient updates might destabilize the policy's convergence. The rescaler is a configurable parameter and there are few options to choose from:
|
||||
* **Total Episode Return** - The sum of all the discounted rewards during the episode.
|
||||
* **Future Return** - Return from each transition until the end of the episode.
|
||||
* **Future Return Normalized by Episode** - Future returns across the episode normalized by the episode's mean and standard deviation.
|
||||
* **Future Return Normalized by Timestep** - Future returns normalized using running means and standard deviations, which are calculated seperately for each timestep, across different episodes.
|
||||
|
||||
Gradients are accumulated over a number of full played episodes. The gradients accumulation over several episodes serves the same purpose - reducing the update variance. After accumulating gradients for several episodes, the gradients are then applied to the network.
|
||||
|
||||
24
docs_raw/docs/algorithms/policy_optimization/ppo.md
Normal file
@@ -0,0 +1,24 @@
|
||||
# Proximal Policy Optimization
|
||||
|
||||
**Actions space:** Discrete|Continuous
|
||||
|
||||
**References:** [Proximal Policy Optimization Algorithms](https://arxiv.org/pdf/1707.06347.pdf)
|
||||
|
||||
## Network Structure
|
||||
|
||||
<p style="text-align: center;">
|
||||
|
||||
<img src="..\..\design_imgs\ppo.png">
|
||||
|
||||
</p>
|
||||
|
||||
|
||||
## Algorithm Description
|
||||
### Choosing an action - Continuous actions
|
||||
Run the observation through the policy network, and get the mean and standard deviation vectors for this observation. While in training phase, sample from a multi-dimensional Gaussian distribution with these mean and standard deviation values. When testing, just take the mean values predicted by the network.
|
||||
### Training the network
|
||||
1. Collect a big chunk of experience (in the order of thousands of transitions, sampled from multiple episodes).
|
||||
2. Calculate the advantages for each transition, using the *Generalized Advantage Estimation* method (Schulman '2015).
|
||||
3. Run a single training iteration of the value network using an L-BFGS optimizer. Unlike first order optimizers, the L-BFGS optimizer runs on the entire dataset at once, without batching. It continues running until some low loss threshold is reached. To prevent overfitting to the current dataset, the value targets are updated in a soft manner, using an Exponentially Weighted Moving Average, based on the total discounted returns of each state in each episode.
|
||||
4. Run several training iterations of the policy network. This is done by using the previously calculated advantages as targets. The loss function penalizes policies that deviate too far from the old policy (the policy that was used *before* starting to run the current set of training iterations) using a regularization term.
|
||||
5. After training is done, the last sampled KL divergence value will be compared with the *target KL divergence* value, in order to adapt the penalty coefficient used in the policy loss. If the KL divergence went too high, increase the penalty, if it went too low, reduce it. Otherwise, leave it unchanged.
|
||||
30
docs_raw/docs/algorithms/value_optimization/bs_dqn.md
Normal file
@@ -0,0 +1,30 @@
|
||||
# Bootstrapped DQN
|
||||
|
||||
**Actions space:** Discrete
|
||||
|
||||
**References:** [Deep Exploration via Bootstrapped DQN](https://arxiv.org/abs/1602.04621)
|
||||
|
||||
## Network Structure
|
||||
|
||||
<p style="text-align: center;">
|
||||
|
||||
<img src="..\..\design_imgs\bs_dqn.png">
|
||||
|
||||
</p>
|
||||
|
||||
## Algorithm Description
|
||||
### Choosing an action
|
||||
The current states are used as the input to the network. The network contains several $Q$ heads, which are used for returning different estimations of the action $ Q $ values. For each episode, the bootstrapped exploration policy selects a single head to play with during the episode. According to the selected head, only the relevant output $ Q $ values are used. Using those $ Q $ values, the exploration policy then selects the action for acting.
|
||||
|
||||
### Storing the transitions
|
||||
For each transition, a Binomial mask is generated according to a predefined probability, and the number of output heads. The mask is a binary vector where each element holds a 0 for heads that shouldn't train on the specific transition, and 1 for heads that should use the transition for training. The mask is stored as part of the transition info in the replay buffer.
|
||||
|
||||
### Training the network
|
||||
First, sample a batch of transitions from the replay buffer. Run the current states through the network and get the current $ Q $ value predictions for all the heads and all the actions. For each transition in the batch, and for each output head, if the transition mask is 1 - change the targets of the played action to $y_t$, according to the standard DQN update rule:
|
||||
|
||||
$$ y_t=r(s_t,a_t )+\gamma\cdot max_a Q(s_{t+1},a) $$
|
||||
|
||||
Otherwise, leave it intact so that the transition does not affect the learning of this head. Then, train the online network according to the calculated targets.
|
||||
|
||||
As in DQN, once in every few thousand steps, copy the weights from the online network to the target network.
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
# Categorical DQN
|
||||
|
||||
**Actions space:** Discrete
|
||||
|
||||
**References:** [A Distributional Perspective on Reinforcement Learning](https://arxiv.org/abs/1707.06887)
|
||||
|
||||
## Network Structure
|
||||
|
||||
<p style="text-align: center;">
|
||||
|
||||
<img src="..\..\design_imgs\distributional_dqn.png">
|
||||
|
||||
</p>
|
||||
|
||||
|
||||
|
||||
## Algorithm Description
|
||||
|
||||
### Training the network
|
||||
|
||||
1. Sample a batch of transitions from the replay buffer.
|
||||
2. The Bellman update is projected to the set of atoms representing the $ Q $ values distribution, such that the $i-th$ component of the projected update is calculated as follows:
|
||||
$$ (\Phi \hat{T} Z_{\theta}(s_t,a_t))_i=\sum_{j=0}^{N-1}\Big[1-\frac{|[\hat{T}_{z_{j}}]^{V_{MAX}}_{V_{MIN}}-z_i|}{\Delta z}\Big]^1_0 \ p_j(s_{t+1}, \pi(s_{t+1})) $$
|
||||
where:
|
||||
* $[ \cdot ] $ bounds its argument in the range [a, b]
|
||||
* $\hat{T}_{z_{j}}$ is the Bellman update for atom $z_j$: $\hat{T}_{z_{j}} := r+\gamma z_j$
|
||||
|
||||
|
||||
3. Network is trained with the cross entropy loss between the resulting probability distribution and the target probability distribution. Only the target of the actions that were actually taken is updated.
|
||||
4. Once in every few thousand steps, weights are copied from the online network to the target network.
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
# Distributional DQN
|
||||
|
||||
**Actions space:** Discrete
|
||||
|
||||
**References:** [A Distributional Perspective on Reinforcement Learning](https://arxiv.org/abs/1707.06887)
|
||||
|
||||
## Network Structure
|
||||
|
||||
<p style="text-align: center;">
|
||||
|
||||
<img src="..\..\design_imgs\distributional_dqn.png">
|
||||
|
||||
</p>
|
||||
|
||||
|
||||
|
||||
## Algorithmic Description
|
||||
|
||||
### Training the network
|
||||
|
||||
1. Sample a batch of transitions from the replay buffer.
|
||||
2. The Bellman update is projected to the set of atoms representing the $ Q $ values distribution, such that the $i-th$ component of the projected update is calculated as follows:
|
||||
$$ (\Phi \hat{T} Z_{\theta}(s_t,a_t))_i=\sum_{j=0}^{N-1}\Big[1-\frac{|[\hat{T}_{z_{j}}]^{V_{MAX}}_{V_{MIN}}-z_i|}{\Delta z}\Big]^1_0 \ p_j(s_{t+1}, \pi(s_{t+1})) $$
|
||||
where:
|
||||
* $[ \cdot ] $ bounds its argument in the range [a, b]
|
||||
* $\hat{T}_{z_{j}}$ is the Bellman update for atom $z_j$: $\hat{T}_{z_{j}} := r+\gamma z_j$
|
||||
|
||||
|
||||
3. Network is trained with the cross entropy loss between the resulting probability distribution and the target probability distribution. Only the target of the actions that were actually taken is updated.
|
||||
4. Once in every few thousand steps, weights are copied from the online network to the target network.
|
||||
|
||||
|
||||
|
||||
28
docs_raw/docs/algorithms/value_optimization/double_dqn.md
Normal file
@@ -0,0 +1,28 @@
|
||||
# Double DQN
|
||||
|
||||
**Actions space:** Discrete
|
||||
|
||||
**References:** [Deep Reinforcement Learning with Double Q-learning](https://arxiv.org/abs/1509.06461.pdf)
|
||||
|
||||
## Network Structure
|
||||
|
||||
<p style="text-align: center;">
|
||||
|
||||
<img src="..\..\design_imgs\dqn.png">
|
||||
|
||||
</p>
|
||||
|
||||
|
||||
|
||||
## Algorithm Description
|
||||
|
||||
### Training the network
|
||||
1. Sample a batch of transitions from the replay buffer.
|
||||
2. Using the next states from the sampled batch, run the online network in order to find the $Q$ maximizing action $argmax_a Q(s_{t+1},a)$. For these actions, use the corresponding next states and run the target network to calculate $Q(s_{t+1},argmax_a Q(s_{t+1},a))$.
|
||||
3. In order to zero out the updates for the actions that were not played (resulting from zeroing the MSE loss), use the current states from the sampled batch, and run the online network to get the current Q values predictions. Set those values as the targets for the actions that were not actually played.
|
||||
4. For each action that was played, use the following equation for calculating the targets of the network:
|
||||
$$ y_t=r(s_t,a_t )+\gamma \cdot Q(s_{t+1},argmax_a Q(s_{t+1},a)) $$
|
||||
|
||||
|
||||
5. Finally, train the online network using the current states as inputs, and with the aforementioned targets.
|
||||
6. Once in every few thousand steps, copy the weights from the online network to the target network.
|
||||
28
docs_raw/docs/algorithms/value_optimization/dqn.md
Normal file
@@ -0,0 +1,28 @@
|
||||
# Deep Q Networks
|
||||
|
||||
**Actions space:** Discrete
|
||||
|
||||
**References:** [Playing Atari with Deep Reinforcement Learning](https://www.cs.toronto.edu/~vmnih/docs/dqn.pdf)
|
||||
|
||||
## Network Structure
|
||||
|
||||
<p style="text-align: center;">
|
||||
|
||||
<img src="..\..\design_imgs\dqn.png">
|
||||
|
||||
</p>
|
||||
|
||||
|
||||
|
||||
## Algorithm Description
|
||||
|
||||
### Training the network
|
||||
|
||||
1. Sample a batch of transitions from the replay buffer.
|
||||
2. Using the next states from the sampled batch, run the target network to calculate the $ Q $ values for each of the actions $ Q(s_{t+1},a) $, and keep only the maximum value for each state.
|
||||
3. In order to zero out the updates for the actions that were not played (resulting from zeroing the MSE loss), use the current states from the sampled batch, and run the online network to get the current Q values predictions. Set those values as the targets for the actions that were not actually played.
|
||||
4. For each action that was played, use the following equation for calculating the targets of the network: $$ y_t=r(s_t,a_t)+γ\cdot max_a {Q(s_{t+1},a)} $$
|
||||
|
||||
|
||||
5. Finally, train the online network using the current states as inputs, and with the aforementioned targets.
|
||||
6. Once in every few thousand steps, copy the weights from the online network to the target network.
|
||||
21
docs_raw/docs/algorithms/value_optimization/dueling_dqn.md
Normal file
@@ -0,0 +1,21 @@
|
||||
# Dueling DQN
|
||||
|
||||
**Actions space:** Discrete
|
||||
|
||||
**References:** [Dueling Network Architectures for Deep Reinforcement Learning](https://arxiv.org/abs/1511.06581)
|
||||
|
||||
## Network Structure
|
||||
|
||||
<p style="text-align: center;">
|
||||
|
||||
<img src="..\..\design_imgs\dueling_dqn.png">
|
||||
|
||||
</p>
|
||||
|
||||
## General Description
|
||||
Dueling DQN presents a change in the network structure comparing to DQN.
|
||||
|
||||
Dueling DQN uses a specialized _Dueling Q Head_ in order to separate $ Q $ to an $ A $ (advantage) stream and a $ V $ stream. Adding this type of structure to the network head allows the network to better differentiate actions from one another, and significantly improves the learning.
|
||||
|
||||
In many states, the values of the different actions are very similar, and it is less important which action to take.
|
||||
This is especially important in environments where there are many actions to choose from. In DQN, on each training iteration, for each of the states in the batch, we update the $Q$ values only for the specific actions taken in those states. This results in slower learning as we do not learn the $Q$ values for actions that were not taken yet. On dueling architecture, on the other hand, learning is faster - as we start learning the state-value even if only a single action has been taken at this state.
|
||||
32
docs_raw/docs/algorithms/value_optimization/mmc.md
Normal file
@@ -0,0 +1,32 @@
|
||||
# Mixed Monte Carlo
|
||||
|
||||
**Actions space:** Discrete
|
||||
|
||||
**References:** [Count-Based Exploration with Neural Density Models](https://arxiv.org/abs/1703.01310)
|
||||
|
||||
## Network Structure
|
||||
|
||||
<p style="text-align: center;">
|
||||
|
||||
<img src="../../design_imgs/dqn.png">
|
||||
|
||||
</p>
|
||||
|
||||
## Algorithm Description
|
||||
### Training the network
|
||||
In MMC, targets are calculated as a mixture between Double DQN targets and full Monte Carlo samples (total discounted returns).
|
||||
|
||||
The DDQN targets are calculated in the same manner as in the DDQN agent:
|
||||
|
||||
$$ y_t^{DDQN}=r(s_t,a_t )+\gamma Q(s_{t+1},argmax_a Q(s_{t+1},a)) $$
|
||||
|
||||
The Monte Carlo targets are calculated by summing up the discounted rewards across the entire episode:
|
||||
|
||||
$$ y_t^{MC}=\sum_{j=0}^T\gamma^j r(s_{t+j},a_{t+j} ) $$
|
||||
|
||||
A mixing ratio $\alpha$ is then used to get the final targets:
|
||||
|
||||
$$ y_t=(1-\alpha)\cdot y_t^{DDQN}+\alpha \cdot y_t^{MC} $$
|
||||
|
||||
Finally, the online network is trained using the current states as inputs, and the calculated targets.
|
||||
Once in every few thousand steps, copy the weights from the online network to the target network.
|
||||
30
docs_raw/docs/algorithms/value_optimization/n_step.md
Normal file
@@ -0,0 +1,30 @@
|
||||
# N-Step Q Learning
|
||||
|
||||
**Actions space:** Discrete
|
||||
|
||||
**References:** [Asynchronous Methods for Deep Reinforcement Learning](https://arxiv.org/abs/1602.01783)
|
||||
|
||||
## Network Structure
|
||||
|
||||
<p style="text-align: center;">
|
||||
|
||||
<img src="..\..\design_imgs\dqn.png">
|
||||
|
||||
</p>
|
||||
|
||||
|
||||
|
||||
## Algorithm Description
|
||||
|
||||
### Training the network
|
||||
|
||||
The $N$-step Q learning algorithm works in similar manner to DQN except for the following changes:
|
||||
|
||||
1. No replay buffer is used. Instead of sampling random batches of transitions, the network is trained every $N$ steps using the latest $N$ steps played by the agent.
|
||||
|
||||
2. In order to stabilize the learning, multiple workers work together to update the network. This creates the same effect as uncorrelating the samples used for training.
|
||||
|
||||
3. Instead of using single-step Q targets for the network, the rewards from $N$ consequent steps are accumulated to form the $N$-step Q targets, according to the following equation:
|
||||
$$R(s_t, a_t) = \sum_{i=t}^{i=t + k - 1} \gamma^{i-t}r_i +\gamma^{k} V(s_{t+k})$$
|
||||
where $k$ is $T_{max} - State\_Index$ for each state in the batch
|
||||
|
||||
22
docs_raw/docs/algorithms/value_optimization/naf.md
Normal file
@@ -0,0 +1,22 @@
|
||||
# Normalized Advantage Functions
|
||||
|
||||
**Actions space:** Continuous
|
||||
|
||||
**References:** [Continuous Deep Q-Learning with Model-based Acceleration](https://arxiv.org/abs/1603.00748.pdf)
|
||||
|
||||
## Network Structure
|
||||
|
||||
<p style="text-align: center;">
|
||||
|
||||
<img src="..\..\design_imgs\naf.png" width=600>
|
||||
|
||||
</p>
|
||||
|
||||
## Algorithm Description
|
||||
### Choosing an action
|
||||
The current state is used as an input to the network. The action mean $ \mu(s_t ) $ is extracted from the output head. It is then passed to the exploration policy which adds noise in order to encourage exploration.
|
||||
###Training the network
|
||||
The network is trained by using the following targets:
|
||||
$$ y_t=r(s_t,a_t )+\gamma\cdot V(s_{t+1}) $$
|
||||
Use the next states as the inputs to the target network and extract the $ V $ value, from within the head, to get $ V(s_{t+1} ) $. Then, update the online network using the current states and actions as inputs, and $ y_t $ as the targets.
|
||||
After every training step, use a soft update in order to copy the weights from the online network to the target network.
|
||||
28
docs_raw/docs/algorithms/value_optimization/nec.md
Normal file
@@ -0,0 +1,28 @@
|
||||
# Neural Episodic Control
|
||||
|
||||
**Actions space:** Discrete
|
||||
|
||||
**References:** [Neural Episodic Control](https://arxiv.org/abs/1703.01988)
|
||||
|
||||
## Network Structure
|
||||
|
||||
<p style="text-align: center;">
|
||||
|
||||
<img src="..\..\design_imgs\nec.png" width=500>
|
||||
|
||||
</p>
|
||||
|
||||
## Algorithm Description
|
||||
### Choosing an action
|
||||
1. Use the current state as an input to the online network and extract the state embedding, which is the intermediate output from the middleware.
|
||||
2. For each possible action $a_i$, run the DND head using the state embedding and the selected action $a_i$ as inputs. The DND is queried and returns the $ P $ nearest neighbor keys and values. The keys and values are used to calculate and return the action $ Q $ value from the network.
|
||||
3. Pass all the $ Q $ values to the exploration policy and choose an action accordingly.
|
||||
4. Store the state embeddings and actions taken during the current episode in a small buffer $B$, in order to accumulate transitions until it is possible to calculate the total discounted returns over the entire episode.
|
||||
|
||||
### Finalizing an episode
|
||||
For each step in the episode, the state embeddings and the taken actions are stored in the buffer $B$. When the episode is finished, the replay buffer calculates the $ N $-step total return of each transition in the buffer, bootstrapped using the maximum $Q$ value of the $N$-th transition. Those values are inserted along with the total return into the DND, and the buffer $B$ is reset.
|
||||
### Training the network
|
||||
Train the network only when the DND has enough entries for querying.
|
||||
|
||||
To train the network, the current states are used as the inputs and the $N$-step returns are used as the targets. The $N$-step return used takes into account $ N $ consecutive steps, and bootstraps the last value from the network if necessary:
|
||||
$$ y_t=\sum_{j=0}^{N-1}\gamma^j r(s_{t+j},a_{t+j} ) +\gamma^N max_a Q(s_{t+N},a) $$
|
||||
32
docs_raw/docs/algorithms/value_optimization/pal.md
Normal file
@@ -0,0 +1,32 @@
|
||||
# Persistent Advantage Learning
|
||||
|
||||
**Actions space:** Discrete
|
||||
|
||||
**References:** [Increasing the Action Gap: New Operators for Reinforcement Learning](https://arxiv.org/abs/1512.04860)
|
||||
|
||||
## Network Structure
|
||||
|
||||
<p style="text-align: center;">
|
||||
|
||||
<img src="../../design_imgs/dqn.png">
|
||||
|
||||
</p>
|
||||
|
||||
## Algorithm Description
|
||||
### Training the network
|
||||
1. Sample a batch of transitions from the replay buffer.
|
||||
|
||||
2. Start by calculating the initial target values in the same manner as they are calculated in DDQN
|
||||
$$ y_t^{DDQN}=r(s_t,a_t )+\gamma Q(s_{t+1},argmax_a Q(s_{t+1},a)) $$
|
||||
3. The action gap $ V(s_t )-Q(s_t,a_t) $ should then be subtracted from each of the calculated targets. To calculate the action gap, run the target network using the current states and get the $ Q $ values for all the actions. Then estimate $ V $ as the maximum predicted $ Q $ value for the current state:
|
||||
$$ V(s_t )=max_a Q(s_t,a) $$
|
||||
4. For _advantage learning (AL)_, reduce the action gap weighted by a predefined parameter $ \alpha $ from the targets $ y_t^{DDQN} $:
|
||||
$$ y_t=y_t^{DDQN}-\alpha \cdot (V(s_t )-Q(s_t,a_t )) $$
|
||||
5. For _persistent advantage learning (PAL)_, the target network is also used in order to calculate the action gap for the next state:
|
||||
$$ V(s_{t+1} )-Q(s_{t+1},a_{t+1}) $$
|
||||
where $ a_{t+1} $ is chosen by running the next states through the online network and choosing the action that has the highest predicted $ Q $ value. Finally, the targets will be defined as -
|
||||
$$ y_t=y_t^{DDQN}-\alpha \cdot min(V(s_t )-Q(s_t,a_t ),V(s_{t+1} )-Q(s_{t+1},a_{t+1} )) $$
|
||||
6. Train the online network using the current states as inputs, and with the aforementioned targets.
|
||||
|
||||
7. Once in every few thousand steps, copy the weights from the online network to the target network.
|
||||
|
||||
38
docs_raw/docs/contributing/add_agent.md
Normal file
@@ -0,0 +1,38 @@
|
||||
<!-- language-all: python -->
|
||||
|
||||
Coach's modularity makes adding an agent a simple and clean task, that involves the following steps:
|
||||
|
||||
1. Implement your algorithm in a new file under the agents directory. The agent can inherit base classes such as **ValueOptimizationAgent** or **ActorCriticAgent**, or the more generic **Agent** base class.
|
||||
|
||||
* **ValueOptimizationAgent**, **PolicyOptimizationAgent** and **Agent** are abstract classes.
|
||||
learn_from_batch() should be overriden with the desired behavior for the algorithm being implemented. If deciding to inherit from **Agent**, also choose_action() should be overriden.
|
||||
|
||||
|
||||
def learn_from_batch(self, batch):
|
||||
"""
|
||||
Given a batch of transitions, calculates their target values and updates the network.
|
||||
:param batch: A list of transitions
|
||||
:return: The loss of the training
|
||||
"""
|
||||
pass
|
||||
|
||||
def choose_action(self, curr_state, phase=RunPhase.TRAIN):
|
||||
"""
|
||||
choose an action to act with in the current episode being played. Different behavior might be exhibited when training
|
||||
or testing.
|
||||
|
||||
:param curr_state: the current state to act upon.
|
||||
:param phase: the current phase: training or testing.
|
||||
:return: chosen action, some action value describing the action (q-value, probability, etc)
|
||||
"""
|
||||
pass
|
||||
|
||||
|
||||
|
||||
* Make sure to add your new agent to **agents/\_\_init\_\_.py**
|
||||
|
||||
2. Implement your agent's specific network head, if needed, at the implementation for the framework of your choice. For example **architectures/neon_components/heads.py**. The head will inherit the generic base class Head.
|
||||
A new output type should be added to configurations.py, and a mapping between the new head and output type should be defined in the get_output_head() function at **architectures/neon_components/general_network.py**
|
||||
3. Define a new configuration class at configurations.py, which includes the new agent name in the **type** field, the new output type in the **output_types** field, and assigning default values to hyperparameters.
|
||||
4. (Optional) Define a preset using the new agent type with a given environment, and the hyperparameters that should be used for training on that environment.
|
||||
|
||||
70
docs_raw/docs/contributing/add_env.md
Normal file
@@ -0,0 +1,70 @@
|
||||
Adding a new environment to Coach is as easy as solving CartPole.
|
||||
|
||||
There are a few simple steps to follow, and we will walk through them one by one.
|
||||
|
||||
1. Coach defines a simple API for implementing a new environment which is defined in environment/environment_wrapper.py.
|
||||
There are several functions to implement, but only some of them are mandatory.
|
||||
|
||||
Here are the important ones:
|
||||
|
||||
def _take_action(self, action_idx):
|
||||
"""
|
||||
An environment dependent function that sends an action to the simulator.
|
||||
:param action_idx: the action to perform on the environment.
|
||||
:return: None
|
||||
"""
|
||||
pass
|
||||
|
||||
def _preprocess_observation(self, observation):
|
||||
"""
|
||||
Do initial observation preprocessing such as cropping, rgb2gray, rescale etc.
|
||||
Implementing this function is optional.
|
||||
:param observation: a raw observation from the environment
|
||||
:return: the preprocessed observation
|
||||
"""
|
||||
return observation
|
||||
|
||||
def _update_state(self):
|
||||
"""
|
||||
Updates the state from the environment.
|
||||
Should update self.observation, self.reward, self.done, self.measurements and self.info
|
||||
:return: None
|
||||
"""
|
||||
pass
|
||||
|
||||
def _restart_environment_episode(self, force_environment_reset=False):
|
||||
"""
|
||||
:param force_environment_reset: Force the environment to reset even if the episode is not done yet.
|
||||
:return:
|
||||
"""
|
||||
pass
|
||||
|
||||
def get_rendered_image(self):
|
||||
"""
|
||||
Return a numpy array containing the image that will be rendered to the screen.
|
||||
This can be different from the observation. For example, mujoco's observation is a measurements vector.
|
||||
:return: numpy array containing the image that will be rendered to the screen
|
||||
"""
|
||||
return self.observation
|
||||
|
||||
|
||||
2. Make sure to import the environment in environments/\_\_init\_\_.py:
|
||||
|
||||
from doom_environment_wrapper import *
|
||||
|
||||
Also, a new entry should be added to the EnvTypes enum mapping the environment name to the wrapper's class name:
|
||||
|
||||
Doom = "DoomEnvironmentWrapper"
|
||||
|
||||
|
||||
3. In addition a new configuration class should be implemented for defining the environment's parameters and placed in configurations.py.
|
||||
For instance, the following is used for Doom:
|
||||
|
||||
class Doom(EnvironmentParameters):
|
||||
type = 'Doom'
|
||||
frame_skip = 4
|
||||
observation_stack_size = 3
|
||||
desired_observation_height = 60
|
||||
desired_observation_width = 76
|
||||
|
||||
4. And that's it, you're done. Now just add a new preset with your newly created environment, and start training an agent on top of it.
|
||||
86
docs_raw/docs/dashboard.md
Normal file
@@ -0,0 +1,86 @@
|
||||
Reinforcement learning algorithms are neat. That is - when they work. But when they don't, RL algorithms are often quite tricky to debug.
|
||||
|
||||
Finding the root cause for why things break in RL is rather difficult. Moreover, different RL algorithms shine in some aspects, but then lack on other. Comparing the algorithms faithfully is also a hard task, which requires the right tools.
|
||||
|
||||
Coach Dashboard is a visualization tool which simplifies the analysis of the training process. Each run of Coach extracts a lot of information from within the algorithm and stores it in the experiment directory. This information is very valuable for debugging, analyzing and comparing different algorithms. But without a good visualization tool, this information can not be utilized. This is where Coach Dashboard takes place.
|
||||
|
||||
### Visualizing Signals
|
||||
|
||||
Coach Dashboard exposes a convenient user interface for visualizing the training signals. The signals are dynamically updated - during the agent training. Additionaly, it allows selecting a subset of the available signals, and then overlaying them on top of each other.
|
||||
|
||||
<p style="text-align: center;">
|
||||
|
||||
<img src="../img/updating_dynamically.gif" alt="Updating Dynamically" style="width: 800px;"/>
|
||||
|
||||
</p>
|
||||
|
||||
* Holding the CTRL key, while selecting signals, will allow visualizing more than one signal.
|
||||
* Signals can be visualized, using either of the Y-axes, in order to visualize signals with different scales. To move a signal to the second Y-axis, select it and press the 'Toggle Second Axis' button.
|
||||
|
||||
|
||||
### Tracking Statistics
|
||||
|
||||
When running parallel algorithms, such as A3C, it often helps visualizing the learning of all the workers, at the same time. Coach Dashboard allows viewing multiple signals (and even smooth them out, if required) from multiple workers. In addition, it supports viewing the mean and standard deviation of the same signal, across different workers, using Bollinger bands.
|
||||
|
||||
<p style="text-align: center;">
|
||||
<table style="box-shadow: none;">
|
||||
<tr>
|
||||
<td style="width: 450px; text-align: center;">
|
||||
<img src="../img/bollinger_bands.png" alt="Bollinger Bands" style="width: 400px;"/>
|
||||
<b>Displaying Bollinger Bands</b>
|
||||
</td>
|
||||
<td style="width: 450px; text-align: center;">
|
||||
<img src="../img/separate_signals.png" alt="Separate Signals" style="width: 400px;"/>
|
||||
<b>Displaying All The Workers</b>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
</p>
|
||||
|
||||
|
||||
|
||||
### Comparing Runs
|
||||
|
||||
Reinforcement learning algorithms are notoriously known as unstable, and suffer from high run-to-run variance. This makes benchmarking and comparing different algorithms even harder. To ease this process, it is common to execute several runs of the same algorithm and average over them. This is easy to do with Coach Dashboard, by centralizing all the experiment directories in a single directory, and then loading them as a single group. Loading several groups of different algorithms then allows comparing the averaged signals, such as the total episode reward.
|
||||
|
||||
In RL, there are several interesting performance metrics to consider, and this is easy to do by controlling the X-axis units in Coach Dashboard. It is possible to switch between several options such as the total number of steps or the total training time.
|
||||
|
||||
<p style="text-align: center;">
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<table style="box-shadow: none;">
|
||||
<tr>
|
||||
<td style="width: 450px; text-align: center;">
|
||||
|
||||
<img src="../img/compare_by_time.png" alt="Comparing By Time" style="width: 400px;"/>
|
||||
|
||||
|
||||
<b>Comparing Several Algorithms According to the Time Passed</b>
|
||||
|
||||
|
||||
</td>
|
||||
<td style="width: 450px; text-align: center;">
|
||||
|
||||
<img src="../img/compare_by_num_episodes.png" alt="Comparing By Number of Episodes" style="width: 400px;"/>
|
||||
|
||||
|
||||
<b>Comparing Several Algorithms According to the Number of Episodes Played</b>
|
||||
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
|
||||
|
||||
</p>
|
||||
|
||||
|
||||
48
docs_raw/docs/design.md
Normal file
@@ -0,0 +1,48 @@
|
||||
# Coach Design
|
||||
|
||||
## Network Design
|
||||
|
||||
Each agent has at least one neural network, used as the function approximator, for choosing the actions. The network is designed in a modular way to allow reusability in different agents. It is separated into three main parts:
|
||||
|
||||
* **Input Embedders** - This is the first stage of the network, meant to convert the input into a feature vector representation. It is possible to combine several instances of any of the supported embedders, in order to allow varied combinations of inputs.
|
||||
|
||||
There are two main types of input embedders:
|
||||
|
||||
1. Image embedder - Convolutional neural network.
|
||||
2. Vector embedder - Multi-layer perceptron.
|
||||
|
||||
|
||||
* **Middlewares** - The middleware gets the output of the input embedder, and processes it into a different representation domain, before sending it through the output head. The goal of the middleware is to enable processing the combined outputs of several input embedders, and pass them through some extra processing. This, for instance, might include an LSTM or just a plain simple FC layer.
|
||||
|
||||
* **Output Heads** - The output head is used in order to predict the values required from the network. These might include action-values, state-values or a policy. As with the input embedders, it is possible to use several output heads in the same network. For example, the *Actor Critic* agent combines two heads - a policy head and a state-value head.
|
||||
In addition, the output heads defines the loss function according to the head type.
|
||||
|
||||
|
||||
|
||||
<p style="text-align: center;">
|
||||
|
||||
<img src="../img/network.png" alt="Network Design" style="width: 400px;"/>
|
||||
|
||||
</p>
|
||||
|
||||
## Keeping Network Copies in Sync
|
||||
|
||||
Most of the reinforcement learning agents include more than one copy of the neural network. These copies serve as counterparts of the main network which are updated in different rates, and are often synchronized either locally or between parallel workers. For easier synchronization of those copies, a wrapper around these copies exposes a simplified API, which allows hiding these complexities from the agent.
|
||||
|
||||
<p style="text-align: center;">
|
||||
|
||||
<img src="../img/distributed.png" alt="Distributed Training" style="width: 600px;"/>
|
||||
|
||||
</p>
|
||||
|
||||
## Supported Algorithms
|
||||
|
||||
Coach supports many state-of-the-art reinforcement learning algorithms, which are separated into two main classes - value optimization and policy optimization. A detailed description of those algorithms may be found in the algorithms section.
|
||||
|
||||
<p style="text-align: center;">
|
||||
|
||||
<img src="../img/algorithms.png" alt="Supported Algorithms" style="width: 600px;"/>
|
||||
|
||||
</p>
|
||||
|
||||
|
||||
8
docs_raw/docs/extra.css
Normal file
@@ -0,0 +1,8 @@
|
||||
.wy-side-nav-search {
|
||||
background-color: #79a7a5;
|
||||
}
|
||||
|
||||
.wy-nav-top {
|
||||
background: #79a7a5;
|
||||
}
|
||||
|
||||
BIN
docs_raw/docs/img/algorithms.png
Normal file
|
After Width: | Height: | Size: 35 KiB |
BIN
docs_raw/docs/img/bollinger_bands.png
Normal file
|
After Width: | Height: | Size: 310 KiB |
BIN
docs_raw/docs/img/compare_by_num_episodes.png
Normal file
|
After Width: | Height: | Size: 449 KiB |
BIN
docs_raw/docs/img/compare_by_time.png
Normal file
|
After Width: | Height: | Size: 447 KiB |
BIN
docs_raw/docs/img/design.png
Normal file
|
After Width: | Height: | Size: 25 KiB |
BIN
docs_raw/docs/img/distributed.png
Normal file
|
After Width: | Height: | Size: 35 KiB |
BIN
docs_raw/docs/img/network.png
Normal file
|
After Width: | Height: | Size: 28 KiB |
BIN
docs_raw/docs/img/separate_signals.png
Normal file
|
After Width: | Height: | Size: 398 KiB |
BIN
docs_raw/docs/img/updating_dynamically.gif
Normal file
|
After Width: | Height: | Size: 1.4 MiB |
25
docs_raw/docs/index.md
Normal file
@@ -0,0 +1,25 @@
|
||||
# What is Coach?
|
||||
|
||||
## Motivation
|
||||
|
||||
Train and evaluate reinforcement learning agents by harnessing the power of multi-core CPU processing to achieve state-of-the-art results. Provide a sandbox for easing the development process of new algorithms through a modular design and an elegant set of APIs.
|
||||
|
||||
## Solution
|
||||
|
||||
Coach is a python environment which models the interaction between an agent and an environment in a modular way.
|
||||
With Coach, it is possible to model an agent by combining various building blocks, and training the agent on multiple environments.
|
||||
The available environments allow testing the agent in different practical fields such as robotics, autonomous driving, games and more.
|
||||
Coach collects statistics from the training process and supports advanced visualization techniques for debugging the agent being trained.
|
||||
|
||||
|
||||
|
||||
Blog post from the Intel® Nervana™ website can be found [here](https://www.intelnervana.com/reinforcement-learning-coach-intel).
|
||||
|
||||
GitHub repository is [here](https://github.com/NervanaSystems/coach).
|
||||
|
||||
## Design
|
||||
|
||||
<img src="img/design.png" alt="Coach Design" style="width: 800px;"/>
|
||||
|
||||
|
||||
|
||||
80
docs_raw/docs/mdx_math.py
Normal file
@@ -0,0 +1,80 @@
|
||||
#
|
||||
# Copyright (c) 2017 Intel Corporation
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
'''
|
||||
Math extension for Python-Markdown
|
||||
==================================
|
||||
|
||||
Adds support for displaying math formulas using [MathJax](http://www.mathjax.org/).
|
||||
|
||||
Author: 2015, Dmitry Shachnev <mitya57@gmail.com>.
|
||||
'''
|
||||
|
||||
import markdown
|
||||
|
||||
class MathExtension(markdown.extensions.Extension):
|
||||
def __init__(self, *args, **kwargs):
|
||||
self.config = {
|
||||
'enable_dollar_delimiter': [False, 'Enable single-dollar delimiter'],
|
||||
'render_to_span': [False,
|
||||
'Render to span elements rather than script for fallback'],
|
||||
}
|
||||
super(MathExtension, self).__init__(*args, **kwargs)
|
||||
|
||||
def extendMarkdown(self, md, md_globals):
|
||||
def handle_match_inline(m):
|
||||
if self.getConfig('render_to_span'):
|
||||
node = markdown.util.etree.Element('span')
|
||||
node.set('class', 'tex')
|
||||
node.text = ("\\\\(" + markdown.util.AtomicString(m.group(3)) +
|
||||
"\\\\)")
|
||||
else:
|
||||
node = markdown.util.etree.Element('script')
|
||||
node.set('type', 'math/tex')
|
||||
node.text = markdown.util.AtomicString(m.group(3))
|
||||
return node
|
||||
|
||||
def handle_match(m):
|
||||
node = markdown.util.etree.Element('script')
|
||||
node.set('type', 'math/tex; mode=display')
|
||||
if '\\begin' in m.group(2):
|
||||
node.text = markdown.util.AtomicString(m.group(2) + m.group(4) + m.group(5))
|
||||
else:
|
||||
node.text = markdown.util.AtomicString(m.group(3))
|
||||
return node
|
||||
|
||||
inlinemathpatterns = (
|
||||
markdown.inlinepatterns.Pattern(r'(?<!\\|\$)(\$)([^\$]+)(\$)'), # $...$
|
||||
markdown.inlinepatterns.Pattern(r'(?<!\\)(\\\()(.+?)(\\\))') # \(...\)
|
||||
)
|
||||
mathpatterns = (
|
||||
markdown.inlinepatterns.Pattern(r'(?<!\\)(\$\$)([^\$]+)(\$\$)'), # $$...$$
|
||||
markdown.inlinepatterns.Pattern(r'(?<!\\)(\\\[)(.+?)(\\\])'), # \[...\]
|
||||
markdown.inlinepatterns.Pattern(r'(?<!\\)(\\begin{([a-z]+?\*?)})(.+?)(\\end{\3})')
|
||||
)
|
||||
if not self.getConfig('enable_dollar_delimiter'):
|
||||
inlinemathpatterns = inlinemathpatterns[1:]
|
||||
for i, pattern in enumerate(inlinemathpatterns):
|
||||
pattern.handleMatch = handle_match_inline
|
||||
md.inlinePatterns.add('math-inline-%d' % i, pattern, '<escape')
|
||||
for i, pattern in enumerate(mathpatterns):
|
||||
pattern.handleMatch = handle_match
|
||||
md.inlinePatterns.add('math-%d' % i, pattern, '<escape')
|
||||
|
||||
def makeExtension(*args, **kwargs):
|
||||
return MathExtension(*args, **kwargs)
|
||||
42
docs_raw/docs/setup.py
Normal file
@@ -0,0 +1,42 @@
|
||||
#
|
||||
# Copyright (c) 2017 Intel Corporation
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
|
||||
#!/usr/bin/env python3
|
||||
|
||||
from distutils.core import setup
|
||||
|
||||
long_description = \
|
||||
"""This extension adds math formulas support to Python-Markdown_
|
||||
(works with version 2.6 or newer).
|
||||
|
||||
.. _Python-Markdown: https://github.com/waylan/Python-Markdown
|
||||
|
||||
You can find the source on GitHub_.
|
||||
Please refer to the `README file`_ for details on how to use it.
|
||||
|
||||
.. _GitHub: https://github.com/mitya57/python-markdown-math
|
||||
.. _`README file`: https://github.com/mitya57/python-markdown-math/blob/master/README.md
|
||||
"""
|
||||
|
||||
setup(name='python-markdown-math',
|
||||
description='Math extension for Python-Markdown',
|
||||
long_description=long_description,
|
||||
author='Dmitry Shachnev',
|
||||
author_email='mitya57@gmail.com',
|
||||
version='0.2',
|
||||
url='https://github.com/mitya57/python-markdown-math',
|
||||
py_modules=['mdx_math'],
|
||||
license='BSD')
|
||||
133
docs_raw/docs/usage.md
Normal file
@@ -0,0 +1,133 @@
|
||||
# Coach Usage
|
||||
|
||||
## Training an Agent
|
||||
|
||||
### Single-threaded Algorithms
|
||||
|
||||
This is the most common case. Just choose a preset using the `-p` flag and press enter.
|
||||
|
||||
*Example:*
|
||||
|
||||
`python coach.py -p CartPole_DQN`
|
||||
|
||||
### Multi-threaded Algorithms
|
||||
|
||||
Multi-threaded algorithms are very common this days.
|
||||
They typically achieve the best results, and scale gracefully with the number of threads.
|
||||
In Coach, running such algorithms is done by selecting a suitable preset, and choosing the number of threads to run using the `-n` flag.
|
||||
|
||||
*Example:*
|
||||
|
||||
`python coach.py -p CartPole_A3C -n 8`
|
||||
|
||||
## Evaluating an Agent
|
||||
|
||||
There are several options for evaluating an agent during the training:
|
||||
|
||||
* For multi-threaded runs, an evaluation agent will constantly run in the background and evaluate the model during the training.
|
||||
|
||||
* For single-threaded runs, it is possible to define an evaluation period through the preset. This will run several episodes of evaluation once in a while.
|
||||
|
||||
Additionally, it is possible to save checkpoints of the agents networks and then run only in evaluation mode.
|
||||
Saving checkpoints can be done by specifying the number of seconds between storing checkpoints using the `-s` flag.
|
||||
The checkpoints will be saved into the experiment directory.
|
||||
Loading a model for evaluation can be done by specifying the `-crd` flag with the experiment directory, and the `--evaluate` flag to disable training.
|
||||
|
||||
*Example:*
|
||||
|
||||
`python coach.py -p CartPole_DQN -s 60`
|
||||
`python coach.py -p CartPole_DQN --evaluate -crd CHECKPOINT_RESTORE_DIR`
|
||||
|
||||
## Playing with the Environment as a Human
|
||||
|
||||
Interacting with the environment as a human can be useful for understanding its difficulties and for collecting data for imitation learning.
|
||||
In Coach, this can be easily done by selecting a preset that defines the environment to use, and specifying the `--play` flag.
|
||||
When the environment is loaded, the available keyboard buttons will be printed to the screen.
|
||||
Pressing the escape key when finished will end the simulation and store the replay buffer in the experiment dir.
|
||||
|
||||
*Example:*
|
||||
|
||||
`python coach.py -p Breakout_DQN --play`
|
||||
|
||||
## Learning Through Imitation Learning
|
||||
|
||||
Learning through imitation of human behavior is a nice way to speedup the learning.
|
||||
In Coach, this can be done in two steps -
|
||||
|
||||
1. Create a dataset of demonstrations by playing with the environment as a human.
|
||||
After this step, a pickle of the replay buffer containing your game play will be stored in the experiment directory.
|
||||
The path to this replay buffer will be printed to the screen.
|
||||
To do so, you should select an environment type and level through the command line, and specify the `--play` flag.
|
||||
|
||||
*Example:*
|
||||
|
||||
`python coach.py -et Doom -lvl Basic --play`
|
||||
|
||||
|
||||
2. Next, use an imitation learning preset and set the replay buffer path accordingly.
|
||||
The path can be set either from the command line or from the preset itself.
|
||||
|
||||
*Example:*
|
||||
|
||||
`python coach.py -p Doom_Basic_BC -cp='agent.load_memory_from_file_path=\"<experiment dir>/replay_buffer.p\"'`
|
||||
|
||||
|
||||
## Visualizations
|
||||
|
||||
### Rendering the Environment
|
||||
|
||||
Rendering the environment can be done by using the `-r` flag.
|
||||
When working with multi-threaded algorithms, the rendered image will be representing the game play of the evaluation worker.
|
||||
When working with single-threaded algorithms, the rendered image will be representing the single worker which can be either training or evaluating.
|
||||
Keep in mind that rendering the environment in single-threaded algorithms may slow the training to some extent.
|
||||
When playing with the environment using the `--play` flag, the environment will be rendered automatically without the need for specifying the `-r` flag.
|
||||
|
||||
*Example:*
|
||||
|
||||
`python coach.py -p Breakout_DQN -r`
|
||||
|
||||
### Dumping GIFs
|
||||
|
||||
Coach allows storing GIFs of the agent game play.
|
||||
To dump GIF files, use the `-dg` flag.
|
||||
The files are dumped after every evaluation episode, and are saved into the experiment directory, under a gifs sub-directory.
|
||||
|
||||
*Example:*
|
||||
|
||||
`python coach.py -p Breakout_A3C -n 4 -dg`
|
||||
|
||||
## Switching between deep learning frameworks
|
||||
|
||||
Coach uses TensorFlow as its main backend framework, but it also supports neon for some of the algorithms.
|
||||
By default, TensorFlow will be used. It is possible to switch to neon using the `-f` flag.
|
||||
|
||||
*Example:*
|
||||
|
||||
`python coach.py -p Doom_Basic_DQN -f neon`
|
||||
|
||||
## Additional Flags
|
||||
|
||||
There are several convenient flags which are important to know about.
|
||||
Here we will list most of the flags, but these can be updated from time to time.
|
||||
The most up to date description can be found by using the `-h` flag.
|
||||
|
||||
|
||||
|Flag |Type |Description |
|
||||
|-------------------------------|----------|--------------|
|
||||
|`-p PRESET`, ``--preset PRESET`|string |Name of a preset to run (as configured in presets.py) |
|
||||
|`-l`, `--list` |flag |List all available presets|
|
||||
|`-e EXPERIMENT_NAME`, `--experiment_name EXPERIMENT_NAME`|string|Experiment name to be used to store the results.|
|
||||
|`-r`, `--render` |flag |Render environment|
|
||||
|`-f FRAMEWORK`, `--framework FRAMEWORK`|string|Neural network framework. Available values: tensorflow, neon|
|
||||
|`-n NUM_WORKERS`, `--num_workers NUM_WORKERS`|int|Number of workers for multi-process based agents, e.g. A3C|
|
||||
|`--play` |flag |Play as a human by controlling the game with the keyboard. This option will save a replay buffer with the game play.|
|
||||
|`--evaluate` |flag |Run evaluation only. This is a convenient way to disable training in order to evaluate an existing checkpoint.|
|
||||
|`-v`, `--verbose` |flag |Don't suppress TensorFlow debug prints.|
|
||||
|`-s SAVE_MODEL_SEC`, `--save_model_sec SAVE_MODEL_SEC`|int|Time in seconds between saving checkpoints of the model.|
|
||||
|`-crd CHECKPOINT_RESTORE_DIR`, `--checkpoint_restore_dir CHECKPOINT_RESTORE_DIR`|string|Path to a folder containing a checkpoint to restore the model from.|
|
||||
|`-dg`, `--dump_gifs` |flag |Enable the gif saving functionality.|
|
||||
|`-at AGENT_TYPE`, `--agent_type AGENT_TYPE`|string|Choose an agent type class to override on top of the selected preset. If no preset is defined, a preset can be set from the command-line by combining settings which are set by using `--agent_type`, `--experiment_type`, `--environemnt_type`|
|
||||
|`-et ENVIRONMENT_TYPE`, `--environment_type ENVIRONMENT_TYPE`|string|Choose an environment type class to override on top of the selected preset. If no preset is defined, a preset can be set from the command-line by combining settings which are set by using `--agent_type`, `--experiment_type`, `--environemnt_type`|
|
||||
|`-ept EXPLORATION_POLICY_TYPE`, `--exploration_policy_type EXPLORATION_POLICY_TYPE`|string|Choose an exploration policy type class to override on top of the selected preset.If no preset is defined, a preset can be set from the command-line by combining settings which are set by using `--agent_type`, `--experiment_type`, `--environemnt_type`|
|
||||
|`-lvl LEVEL`, `--level LEVEL` |string|Choose the level that will be played in the environment that was selected. This value will override the level parameter in the environment class.|
|
||||
|`-cp CUSTOM_PARAMETER`, `--custom_parameter CUSTOM_PARAMETER`|string| Semicolon separated parameters used to override specific parameters on top of the selected preset (or on top of the command-line assembled one). Whenever a parameter value is a string, it should be inputted as `'\"string\"'`. For ex.: `"visualization.render=False;` `num_training_iterations=500;` `optimizer='rmsprop'"`|
|
||||