浏览代码

Merge branch 'master' into asymm-envs

/asymm-envs
Andrew Cohen 5 年前
当前提交
a2f8319a
共有 42 个文件被更改,包括 855 次插入488 次删除
  1. 2
      .yamato/com.unity.ml-agents-pack.yml
  2. 2
      .yamato/com.unity.ml-agents-test.yml
  3. 24
      Project/Assets/ML-Agents/Examples/Basic/Scripts/BasicController.cs
  4. 7
      com.unity.ml-agents/CHANGELOG.md
  5. 3
      com.unity.ml-agents/Editor/EditorUtilities.cs
  6. 6
      com.unity.ml-agents/Runtime/Academy.cs
  7. 10
      com.unity.ml-agents/Runtime/Agent.cs
  8. 3
      com.unity.ml-agents/Runtime/Policies/BrainParameters.cs
  9. 2
      com.unity.ml-agents/Runtime/Sensors/CameraSensorComponent.cs
  10. 5
      com.unity.ml-agents/Runtime/Sensors/RenderTextureSensorComponent.cs
  11. 6
      com.unity.ml-agents/Runtime/SideChannels/FloatPropertiesChannel.cs
  12. 2
      com.unity.ml-agents/Runtime/SideChannels/SideChannel.cs
  13. 4
      com.unity.ml-agents/Runtime/SideChannels/SideChannelUtils.cs
  14. 21
      config/sac_trainer_config.yaml
  15. 56
      docs/Background-Machine-Learning.md
  16. 33
      docs/Background-TensorFlow.md
  17. 23
      docs/Background-Unity.md
  18. 38
      docs/Glossary.md
  19. 22
      docs/Installation-Anaconda-Windows.md
  20. 2
      docs/Learning-Environment-Create-New.md
  21. 9
      docs/Limitations.md
  22. 691
      docs/Migrating.md
  23. 8
      docs/Python-API.md
  24. 4
      docs/Training-ML-Agents.md
  25. 9
      docs/Training-PPO.md
  26. 40
      docs/Training-SAC.md
  27. 2
      docs/Training-on-Amazon-Web-Service.md
  28. 2
      docs/Training-on-Microsoft-Azure.md
  29. 52
      ml-agents/mlagents/trainers/agent_processor.py
  30. 12
      ml-agents/mlagents/trainers/env_manager.py
  31. 4
      ml-agents/mlagents/trainers/ghost/trainer.py
  32. 1
      ml-agents/mlagents/trainers/ppo/trainer.py
  33. 90
      ml-agents/mlagents/trainers/sac/trainer.py
  34. 3
      ml-agents/mlagents/trainers/tests/test_reward_signals.py
  35. 23
      ml-agents/mlagents/trainers/tests/test_rl_trainer.py
  36. 32
      ml-agents/mlagents/trainers/tests/test_sac.py
  37. 20
      ml-agents/mlagents/trainers/tests/test_simple_rl.py
  38. 12
      ml-agents/mlagents/trainers/tests/test_subprocess_env_manager.py
  39. 3
      ml-agents/mlagents/trainers/tests/test_trainer_controller.py
  40. 14
      ml-agents/mlagents/trainers/trainer/rl_trainer.py
  41. 10
      ml-agents/mlagents/trainers/trainer/trainer.py
  42. 31
      ml-agents/mlagents/trainers/trainer_controller.py

2
.yamato/com.unity.ml-agents-pack.yml


image: package-ci/ubuntu:stable
flavor: b1.large
commands:
- npm install upm-ci-utils@stable -g --registry https://api.bintray.com/npm/unity/unity-npm
- npm install upm-ci-utils@stable -g --registry https://artifactory.prd.cds.internal.unity3d.com/artifactory/api/npm/upm-npm
- upm-ci package pack --package-path com.unity.ml-agents
artifacts:
packages:

2
.yamato/com.unity.ml-agents-test.yml


image: {{ platform.image }}
flavor: {{ platform.flavor}}
commands:
- npm install upm-ci-utils@stable -g --registry https://api.bintray.com/npm/unity/unity-npm
- npm install upm-ci-utils@stable -g --registry https://artifactory.prd.cds.internal.unity3d.com/artifactory/api/npm/upm-npm
- upm-ci package test -u {{ editor.version }} --package-path com.unity.ml-agents {{ editor.coverageOptions }}
- python ml-agents/tests/yamato/check_coverage_percent.py upm-ci~/test-results/ {{ editor.minCoveragePct }}
artifacts:

24
Project/Assets/ML-Agents/Examples/Basic/Scripts/BasicController.cs


using UnityEngine;
using UnityEngine.SceneManagement;
using MLAgents;
/// <summary>

Agent m_Agent;
ResetAgent();
m_Position = 10;
transform.position = new Vector3(m_Position - 10f, 0f, 0f);
smallGoal.transform.position = new Vector3(k_SmallGoalPosition - 10f, 0f, 0f);
largeGoal.transform.position = new Vector3(k_LargeGoalPosition - 10f, 0f, 0f);
}
/// <summary>

}
public void ResetAgent()
{
m_Position = 10;
smallGoal.transform.position = new Vector3(k_SmallGoalPosition - 10f, 0f, 0f);
largeGoal.transform.position = new Vector3(k_LargeGoalPosition - 10f, 0f, 0f);
{
// This is a very inefficient way to reset the scene. Used here for testing.
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
m_Agent = null; // LoadScene only takes effect at the next Update.
// We set the Agent to null to avoid using the Agent before the reload
}
public void FixedUpdate()

void WaitTimeInference()
{
if (m_Agent == null)
{
return;
}
m_Agent.RequestDecision();
m_Agent?.RequestDecision();
}
else
{

ApplyAction(m_Agent.GetAction());
m_TimeSinceDecision = 0f;
m_Agent.RequestDecision();
m_Agent?.RequestDecision();
}
else
{

7
com.unity.ml-agents/CHANGELOG.md


communication between Unity and the Python process.
- The obsolete `Agent` methods `GiveModel`, `Done`, `InitializeAgent`,
`AgentAction` and `AgentReset` have been removed.
- The GhostTrainer has been extended to support asymmetric games and the asymmetric example environment Strikers Vs. Goalie has been added.
- The GhostTrainer has been extended to support asymmetric games and the
asymmetric example environment Strikers Vs. Goalie has been added.
- CameraSensorComponent.m_Grayscale and RenderTextureSensorComponent.m_Grayscale
were changed from `public` to `private` (#3808).
### Minor Changes

overwrite the existing files. (#3705)
- `StackingSensor` was changed from `internal` visibility to `public`
- Updated Barracuda to 0.6.3-preview.
- Model updates can now happen asynchronously with environment steps for better performance. (#3690)
- `num_updates` and `train_interval` for SAC were replaced with `steps_per_update`. (#3690)
### Bug Fixes

3
com.unity.ml-agents/Editor/EditorUtilities.cs


namespace MLAgents.Editor
{
/// <summary>
/// A static helper class for the Editor components of the ML-Agents SDK.
/// </summary>
public static class EditorUtilities
{
/// <summary>

6
com.unity.ml-agents/Runtime/Academy.cs


// Don't show this object in the hierarchy
m_StepperObject.hideFlags = HideFlags.HideInHierarchy;
m_FixedUpdateStepper = m_StepperObject.AddComponent<AcademyFixedUpdateStepper>();
try
{
// This try-catch is because DontDestroyOnLoad cannot be used in Editor Tests
GameObject.DontDestroyOnLoad(m_StepperObject);
}
catch {}
}
/// <summary>

10
com.unity.ml-agents/Runtime/Agent.cs


void NotifyAgentDone(DoneReason doneReason)
{
if (m_Info.done)
{
// The Agent was already marked as Done and should not be notified again
return;
}
m_Info.episodeId = m_EpisodeId;
m_Info.reward = m_Reward;
m_Info.done = true;

/// <summary>
/// When the Agent uses Heuristics, it will call this method every time it
/// needs an action. This can be used for debugging or controlling the agent
/// with keyboard.
/// with keyboard. This can also be useful to record demonstrations for imitation learning.
/// <returns> A float array corresponding to the next action of the Agent
/// </returns>
/// <param name="actionsOut">An array corresponding to the next action of the Agent</param>
public virtual void Heuristic(float[] actionsOut)
{
Debug.LogWarning("Heuristic method called but not implemented. Returning placeholder actions.");

3
com.unity.ml-agents/Runtime/Policies/BrainParameters.cs


/// </summary>
public SpaceType vectorActionSpaceType = SpaceType.Discrete;
/// <summary>
/// The number of actions specified by this Brain.
/// </summary>
public int numActions
{
get

2
com.unity.ml-agents/Runtime/Sensors/CameraSensorComponent.cs


}
[HideInInspector, SerializeField, FormerlySerializedAs("grayscale")]
public bool m_Grayscale;
bool m_Grayscale;
/// <summary>
/// Whether to generate grayscale images or color.

5
com.unity.ml-agents/Runtime/Sensors/RenderTextureSensorComponent.cs


[HideInInspector, SerializeField, FormerlySerializedAs("renderTexture")]
RenderTexture m_RenderTexture;
/// <summary>
/// Stores the <see cref="RenderTexture"/> associated with this sensor.
/// </summary>
public RenderTexture renderTexture
{
get { return m_RenderTexture; }

}
[HideInInspector, SerializeField, FormerlySerializedAs("grayscale")]
public bool m_Grayscale;
bool m_Grayscale;
/// <summary>
/// Whether the RenderTexture observation should be converted to grayscale or not.

6
com.unity.ml-agents/Runtime/SideChannels/FloatPropertiesChannel.cs


namespace MLAgents.SideChannels
{
/// <summary>
/// Side channel that is comprised of a collection of float variables, represented by
/// <see cref="IFloatProperties"/>
/// Side channel that is comprised of a collection of float variables.
/// </summary>
public class FloatPropertiesChannel : SideChannel
{

action?.Invoke(value);
}
/// <inheritdoc/>
public float GetPropertyWithDefault(string key, float defaultValue)
{
float valueOut;

/// <inheritdoc/>
/// <inheritdoc/>
public IList<string> ListProperties()
{
return new List<string>(m_FloatProperties.Keys);

2
com.unity.ml-agents/Runtime/SideChannels/SideChannel.cs


/// <summary>
/// Queues a message to be sent to Python during the next simulation step.
/// </summary>
/// <param name="data"> The byte array of data to be sent to Python.</param>
/// <param name="msg"> The byte array of data to be sent to Python.</param>
protected void QueueMessageToSend(OutgoingMessage msg)
{
MessageQueue.Add(msg.ToByteArray());

4
com.unity.ml-agents/Runtime/SideChannels/SideChannelUtils.cs


namespace MLAgents.SideChannels
{
/// <summary>
/// Collection of static utilities for managing the registering/unregistering of
/// <see cref="SideChannels"/> and the sending/receiving of messages for all the channels.
/// </summary>
public static class SideChannelUtils
{

21
config/sac_trainer_config.yaml


max_steps: 5.0e5
memory_size: 128
normalize: false
num_update: 1
train_interval: 1
steps_per_update: 10
num_layers: 2
time_horizon: 64
sequence_length: 64

buffer_size: 500000
max_steps: 2.0e6
init_entcoef: 0.05
train_interval: 1
max_steps: 2.0e6
max_steps: 1.0e6
num_layers: 2
hidden_units: 64
summary_freq: 20000

init_entcoef: 0.05
hidden_units: 256
summary_freq: 60000
summary_freq: 100000
time_horizon: 64
num_layers: 2

normalize: true
time_horizon: 1000
batch_size: 256
train_interval: 2
steps_per_update: 20
max_steps: 5e6
max_steps: 3e6
summary_freq: 30000
init_entcoef: 1.0
num_layers: 3

batch_size: 256
buffer_size: 500000
summary_freq: 30000
train_interval: 2
steps_per_update: 20
max_steps: 1e7
max_steps: 5e6
hidden_units: 512
reward_signals:
extrinsic:

max_steps: 2e7
summary_freq: 30000
num_layers: 4
train_interval: 2
steps_per_update: 30
hidden_units: 512
reward_signals:
extrinsic:

batch_size: 128
buffer_size: 500000
max_steps: 2e7
steps_per_update: 20
summary_freq: 60000
Hallway:

memory_size: 128
init_entcoef: 0.1
max_steps: 1.0e7
max_steps: 5.0e6
summary_freq: 10000
time_horizon: 64
use_recurrent: true

56
docs/Background-Machine-Learning.md


# Background: Machine Learning
Given that a number of users of the ML-Agents toolkit might not have a formal
Given that a number of users of the ML-Agents Toolkit might not have a formal
understanding of the ML-Agents toolkit. However, we will not attempt to provide
understanding of the ML-Agents Toolkit. However, we will not attempt to provide
a thorough treatment of machine learning as there are fantastic resources
online.

## Unsupervised Learning
The goal of [unsupervised
learning](https://en.wikipedia.org/wiki/Unsupervised_learning) is to group or
cluster similar items in a data set. For example, consider the players of a
game. We may want to group the players depending on how engaged they are with
the game. This would enable us to target different groups (e.g. for
highly-engaged players we might invite them to be beta testers for new features,
while for unengaged players we might email them helpful tutorials). Say that we
wish to split our players into two groups. We would first define basic
attributes of the players, such as the number of hours played, total money spent
on in-app purchases and number of levels completed. We can then feed this data
set (three attributes for every player) to an unsupervised learning algorithm
where we specify the number of groups to be two. The algorithm would then split
the data set of players into two groups where the players within each group
would be similar to each other. Given the attributes we used to describe each
player, in this case, the output would be a split of all the players into two
groups, where one group would semantically represent the engaged players and the
second group would semantically represent the unengaged players.
The goal of
[unsupervised learning](https://en.wikipedia.org/wiki/Unsupervised_learning) is
to group or cluster similar items in a data set. For example, consider the
players of a game. We may want to group the players depending on how engaged
they are with the game. This would enable us to target different groups (e.g.
for highly-engaged players we might invite them to be beta testers for new
features, while for unengaged players we might email them helpful tutorials).
Say that we wish to split our players into two groups. We would first define
basic attributes of the players, such as the number of hours played, total money
spent on in-app purchases and number of levels completed. We can then feed this
data set (three attributes for every player) to an unsupervised learning
algorithm where we specify the number of groups to be two. The algorithm would
then split the data set of players into two groups where the players within each
group would be similar to each other. Given the attributes we used to describe
each player, in this case, the output would be a split of all the players into
two groups, where one group would semantically represent the engaged players and
the second group would semantically represent the unengaged players.
With unsupervised learning, we did not provide specific examples of which
players are considered engaged and which are considered unengaged. We just

to achieve good performance.
We now switch to reinforcement learning, the third class of machine learning
algorithms, and arguably the one most relevant for the ML-Agents toolkit.
algorithms, and arguably the one most relevant for the ML-Agents Toolkit.
## Reinforcement Learning

one can view a non-playable character (NPC) as a virtual robot, with its own
observations about the environment, its own set of actions and a specific
objective. Thus it is natural to explore how we can train behaviors within Unity
using reinforcement learning. This is precisely what the ML-Agents toolkit
using reinforcement learning. This is precisely what the ML-Agents Toolkit
training character behaviors using the ML-Agents toolkit.
training character behaviors using the ML-Agents Toolkit.
<p align="center">
<a href="http://www.youtube.com/watch?feature=player_embedded&v=fiQsmdwEGT8" target="_blank">

data, while the inference phase involves applying this model to new, previously
unseen, data. More specifically:
* For our unsupervised learning example, the training phase learns the optimal
- For our unsupervised learning example, the training phase learns the optimal
* For our supervised learning example, the training phase learns the mapping
- For our supervised learning example, the training phase learns the mapping
* For our reinforcement learning example, the training phase learns the optimal
- For our reinforcement learning example, the training phase learns the optimal
policy through guided trials, and in the inference phase, the agent observes
and tales actions in the wild using its learned policy.

More specifically, they can be used to solve both attribute and model selection
tasks. Deep learning has gained popularity in recent years due to its
outstanding performance on several challenging machine learning tasks. One
example is [AlphaGo](https://en.wikipedia.org/wiki/AlphaGo), a [computer
Go](https://en.wikipedia.org/wiki/Computer_Go) program, that leverages deep
learning, that was able to beat Lee Sedol (a Go world champion).
example is [AlphaGo](https://en.wikipedia.org/wiki/AlphaGo), a
[computer Go](https://en.wikipedia.org/wiki/Computer_Go) program, that leverages
deep learning, that was able to beat Lee Sedol (a Go world champion).
A key characteristic of deep learning algorithms is their ability learn very
complex functions from large amounts of training data. This makes them a natural

33
docs/Background-TensorFlow.md


# Background: TensorFlow
As discussed in our
[machine learning background page](Background-Machine-Learning.md),
many of the algorithms we provide in the
ML-Agents toolkit leverage some form of deep learning. More specifically, our
implementations are built on top of the open-source library
[TensorFlow](https://www.tensorflow.org/). This means that the models produced
by the ML-Agents toolkit are (currently) in a format only understood by
TensorFlow. In this page we provide a brief overview of TensorFlow, in addition
to TensorFlow-related tools that we leverage within the ML-Agents toolkit.
[machine learning background page](Background-Machine-Learning.md), many of the
algorithms we provide in the ML-Agents Toolkit leverage some form of deep
learning. More specifically, our implementations are built on top of the
open-source library [TensorFlow](https://www.tensorflow.org/). In this page we
provide a brief overview of TensorFlow, in addition to TensorFlow-related tools
that we leverage within the ML-Agents Toolkit.
## TensorFlow

a desktop, server, or mobile device. Within the ML-Agents toolkit, when you
train the behavior of an agent, the output is a TensorFlow model (.nn) file
that you can then associate with an Agent. Unless you implement a new
algorithm, the use of TensorFlow is mostly abstracted away and behind the
scenes.
a desktop, server, or mobile device. Within the ML-Agents Toolkit, when you
train the behavior of an agent, the output is a TensorFlow model (.nn) file that
you can then associate with an Agent. Unless you implement a new algorithm, the
use of TensorFlow is mostly abstracted away and behind the scenes.
## TensorBoard

It allows the visualization of certain agent attributes (e.g. reward) throughout
training which can be helpful in both building intuitions for the different
hyperparameters and setting the optimal values for your Unity environment. We
provide more details on setting the hyperparameters in later parts of the
documentation, but, in the meantime, if you are unfamiliar with TensorBoard we
recommend our guide on [using TensorBoard with ML-Agents](Using-Tensorboard.md) or
this [tutorial](https://github.com/dandelionmane/tf-dev-summit-tensorboard-tutorial).
provide more details on setting the hyperparameters in the
[Training ML-Agents](Training-ML-Agents.md) page. If you are unfamiliar with
TensorBoard we recommend our guide on
[using TensorBoard with ML-Agents](Using-Tensorboard.md) or this
[tutorial](https://github.com/dandelionmane/tf-dev-summit-tensorboard-tutorial).

23
docs/Background-Unity.md


and [Tutorials page](https://unity3d.com/learn/tutorials). The
[Roll-a-ball tutorial](https://unity3d.com/learn/tutorials/s/roll-ball-tutorial)
is a fantastic resource to learn all the basic concepts of Unity to get started
with the ML-Agents toolkit:
with the ML-Agents Toolkit:
* [Editor](https://docs.unity3d.com/Manual/UsingTheEditor.html)
* [Interface](https://docs.unity3d.com/Manual/LearningtheInterface.html)
* [Scene](https://docs.unity3d.com/Manual/CreatingScenes.html)
* [GameObject](https://docs.unity3d.com/Manual/GameObjects.html)
* [Rigidbody](https://docs.unity3d.com/ScriptReference/Rigidbody.html)
* [Camera](https://docs.unity3d.com/Manual/Cameras.html)
* [Scripting](https://docs.unity3d.com/Manual/ScriptingSection.html)
* [Physics](https://docs.unity3d.com/Manual/PhysicsSection.html)
* [Ordering of event functions](https://docs.unity3d.com/Manual/ExecutionOrder.html)
- [Editor](https://docs.unity3d.com/Manual/UsingTheEditor.html)
- [Interface](https://docs.unity3d.com/Manual/LearningtheInterface.html)
- [Scene](https://docs.unity3d.com/Manual/CreatingScenes.html)
- [GameObject](https://docs.unity3d.com/Manual/GameObjects.html)
- [Rigidbody](https://docs.unity3d.com/ScriptReference/Rigidbody.html)
- [Camera](https://docs.unity3d.com/Manual/Cameras.html)
- [Scripting](https://docs.unity3d.com/Manual/ScriptingSection.html)
- [Physics](https://docs.unity3d.com/Manual/PhysicsSection.html)
- [Ordering of event functions](https://docs.unity3d.com/Manual/ExecutionOrder.html)
* [Prefabs](https://docs.unity3d.com/Manual/Prefabs.html)
- [Prefabs](https://docs.unity3d.com/Manual/Prefabs.html)

38
docs/Glossary.md


# ML-Agents Toolkit Glossary
* **Academy** - Singleton object which controls timing, reset, and
- **Academy** - Singleton object which controls timing, reset, and
* **Action** - The carrying-out of a decision on the part of an agent within the
- **Action** - The carrying-out of a decision on the part of an agent within the
* **Agent** - Unity Component which produces observations and takes actions in
- **Agent** - Unity Component which produces observations and takes actions in
* **Policy** - The decision making mechanism, typically a neural network model.
* **Decision** - The specification produced by a Policy for an action to be
- **Policy** - The decision making mechanism, typically a neural network model.
- **Decision** - The specification produced by a Policy for an action to be
* **Editor** - The Unity Editor, which may include any pane (e.g. Hierarchy,
- **Editor** - The Unity Editor, which may include any pane (e.g. Hierarchy,
* **Environment** - The Unity scene which contains Agents.
* **FixedUpdate** - Unity method called each time the game engine is
stepped. ML-Agents logic should be placed here.
* **Frame** - An instance of rendering the main camera for the display.
- **Environment** - The Unity scene which contains Agents.
- **FixedUpdate** - Unity method called each time the game engine is stepped.
ML-Agents logic should be placed here.
- **Frame** - An instance of rendering the main camera for the display.
* **Observation** - Partial information describing the state of the environment
- **Observation** - Partial information describing the state of the environment
* **Policy** - Function for producing decisions from observations.
* **Reward** - Signal provided at every step used to indicate desirability of an
- **Policy** - Function for producing decisions from observations.
- **Reward** - Signal provided at every step used to indicate desirability of an
* **State** - The underlying properties of the environment (including all agents
- **State** - The underlying properties of the environment (including all agents
* **Step** - Corresponds to each `FixedUpdate` call of the game engine. Is the
- **Step** - Corresponds to each `FixedUpdate` call of the game engine. Is the
* **Update** - Unity function called each time a frame is rendered. ML-Agents
- **Update** - Unity function called each time a frame is rendered. ML-Agents
* **External Coordinator** - ML-Agents class responsible for communication with
- **External Coordinator** - ML-Agents class responsible for communication with
* **Trainer** - Python class which is responsible for training a given
group of Agents.
- **Trainer** - Python class which is responsible for training a given group of
Agents.

22
docs/Installation-Anaconda-Windows.md


:warning: **Note:** We no longer use this guide ourselves and so it may not work
correctly. We've decided to keep it up just in case it is helpful to you.
The ML-Agents toolkit supports Windows 10. While it might be possible to run the
ML-Agents toolkit using other versions of Windows, it has not been tested on
other versions. Furthermore, the ML-Agents toolkit has not been tested on a
The ML-Agents Toolkit supports Windows 10. While it might be possible to run the
ML-Agents Toolkit using other versions of Windows, it has not been tested on
other versions. Furthermore, the ML-Agents Toolkit has not been tested on a
To use the ML-Agents toolkit, you install Python and the required Python
To use the ML-Agents Toolkit, you install Python and the required Python
ML-Agents toolkit. However, training on a GPU might be required by future
ML-Agents Toolkit. However, training on a GPU might be required by future
versions and features.
## Step 1: Install Python via Anaconda

## Step 2: Setup and Activate a New Conda Environment
You will create a new [Conda environment](https://conda.io/docs/) to be used
with the ML-Agents toolkit. This means that all the packages that you install
with the ML-Agents Toolkit. This means that all the packages that you install
are localized to just this environment. It will not affect any other
installation of Python or other environments. Whenever you want to run
ML-Agents, you will need activate this Conda environment.

## Step 3: Install Required Python Packages
The ML-Agents toolkit depends on a number of Python packages. Use `pip` to
The ML-Agents Toolkit depends on a number of Python packages. Use `pip` to
install these Python dependencies.
If you haven't already, clone the ML-Agents Toolkit Github repository to your

```
This will complete the installation of all the required Python packages to run
the ML-Agents toolkit.
the ML-Agents Toolkit.
Sometimes on Windows, when you use pip to install certain Python packages, the
pip will get stuck when trying to read the cache of the package. If you see

## (Optional) Step 4: GPU Training using The ML-Agents Toolkit
GPU is not required for the ML-Agents toolkit and won't speed up the PPO
GPU is not required for the ML-Agents Toolkit and won't speed up the PPO
Currently for the ML-Agents toolkit, only CUDA v9.0 and cuDNN v7.0.5 is
Currently for the ML-Agents Toolkit, only CUDA v9.0 and cuDNN v7.0.5 is
supported.
### Install Nvidia CUDA toolkit

libraries, debugging and optimization tools, a C/C++ (Step Visual Studio 2017)
compiler and a runtime library and is needed to run the ML-Agents toolkit. In
compiler and a runtime library and is needed to run the ML-Agents Toolkit. In
this guide, we are using version
[9.0.176](https://developer.nvidia.com/compute/cuda/9.0/Prod/network_installers/cuda_9.0.176_win10_network-exe)).

2
docs/Learning-Environment-Create-New.md


## Overview
Using the ML-Agents toolkit in a Unity project involves the following basic
Using the ML-Agents Toolkit in a Unity project involves the following basic
steps:
1. Create an environment for your agents to live in. An environment can range

9
docs/Limitations.md


# Limitations
See the package-specific Limitations pages:
* [Unity `com.unity.mlagents` package](../com.unity.ml-agents/Documentation~/com.unity.ml-agents.md)
* [`mlagents` Python package](../ml-agents/README.md)
* [`mlagents_envs` Python package](../ml-agents-envs/README.md)
* [`gym_unity` Python package](../gym-unity/README.md)
- [Unity `com.unity.mlagents` package](../com.unity.ml-agents/Documentation~/com.unity.ml-agents.md)
- [`mlagents` Python package](../ml-agents/README.md)
- [`mlagents_envs` Python package](../ml-agents-envs/README.md)
- [`gym_unity` Python package](../gym-unity/README.md)

691
docs/Migrating.md


# Upgrading
The C# editor code and python trainer code are not compatible between releases. This means that if you upgrade one, you *must* upgrade the other as well. If you experience new errors or unable to connect to training after updating, please double-check that the versions are in the same.
The versions can be found in
* `Academy.k_ApiVersion` in Academy.cs ([example](https://github.com/Unity-Technologies/ml-agents/blob/b255661084cb8f701c716b040693069a3fb9a257/UnitySDK/Assets/ML-Agents/Scripts/Academy.cs#L95))
* `UnityEnvironment.API_VERSION` in environment.py ([example](https://github.com/Unity-Technologies/ml-agents/blob/b255661084cb8f701c716b040693069a3fb9a257/ml-agents-envs/mlagents/envs/environment.py#L45))
The C# editor code and python trainer code are not compatible between releases.
This means that if you upgrade one, you _must_ upgrade the other as well. If you
experience new errors or unable to connect to training after updating, please
double-check that the versions are in the same. The versions can be found in
- `Academy.k_ApiVersion` in Academy.cs
([example](https://github.com/Unity-Technologies/ml-agents/blob/b255661084cb8f701c716b040693069a3fb9a257/UnitySDK/Assets/ML-Agents/Scripts/Academy.cs#L95))
- `UnityEnvironment.API_VERSION` in environment.py
([example](https://github.com/Unity-Technologies/ml-agents/blob/b255661084cb8f701c716b040693069a3fb9a257/ml-agents-envs/mlagents/envs/environment.py#L45))
# Migrating

* The `--load` and `--train` command-line flags have been deprecated and replaced with `--resume` and `--inference`.
* Running with the same `--run-id` twice will now throw an error.
* The `play_against_current_self_ratio` self-play trainer hyperparameter has been renamed to `play_against_latest_model_ratio`
* Removed the multi-agent gym option from the gym wrapper. For multi-agent scenarios, use the [Low Level Python API](Python-API.md).
* The low level Python API has changed. You can look at the document [Low Level Python API documentation](Python-API.md) for more information. If you use `mlagents-learn` for training, this should be a transparent change.
* The obsolete `Agent` methods `GiveModel`, `Done`, `InitializeAgent`, `AgentAction` and `AgentReset` have been removed.
* The signature of `Agent.Heuristic()` was changed to take a `float[]` as a parameter, instead of returning the array. This was done to prevent a common source of error where users would return arrays of the wrong size.
- The `--load` and `--train` command-line flags have been deprecated and
replaced with `--resume` and `--inference`.
- Running with the same `--run-id` twice will now throw an error.
- The `play_against_current_self_ratio` self-play trainer hyperparameter has
been renamed to `play_against_latest_model_ratio`
- Removed the multi-agent gym option from the gym wrapper. For multi-agent
scenarios, use the [Low Level Python API](Python-API.md).
- The low level Python API has changed. You can look at the document
[Low Level Python API documentation](Python-API.md) for more information. If
you use `mlagents-learn` for training, this should be a transparent change.
- The obsolete `Agent` methods `GiveModel`, `Done`, `InitializeAgent`,
`AgentAction` and `AgentReset` have been removed.
- The signature of `Agent.Heuristic()` was changed to take a `float[]` as a
parameter, instead of returning the array. This was done to prevent a common
source of error where users would return arrays of the wrong size.
- `num_updates` and `train_interval` for SAC have been replaced with `steps_per_update`.
* Replace the `--load` flag with `--resume` when calling `mlagents-learn`, and don't use the `--train` flag as training
will happen by default. To run without training, use `--inference`.
* To force-overwrite files from a pre-existing run, add the `--force` command-line flag.
* The Jupyter notebooks have been removed from the repository.
* `Academy.FloatProperties` was removed.
* `Academy.RegisterSideChannel` and `Academy.UnregisterSideChannel` were removed.
* Replace `Academy.FloatProperties` with `SideChannelUtils.GetSideChannel<FloatPropertiesChannel>()`.
* Replace `Academy.RegisterSideChannel` with `SideChannelUtils.RegisterSideChannel()`.
* Replace `Academy.UnregisterSideChannel` with `SideChannelUtils.UnregisterSideChannel`.
* If your Agent class overrides `Heuristic()`, change the signature to `public override void Heuristic(float[] actionsOut)` and assign values to `actionsOut` instead of returning an array.
- Replace the `--load` flag with `--resume` when calling `mlagents-learn`, and
don't use the `--train` flag as training will happen by default. To run
without training, use `--inference`.
- To force-overwrite files from a pre-existing run, add the `--force`
command-line flag.
- The Jupyter notebooks have been removed from the repository.
- `Academy.FloatProperties` was removed.
- `Academy.RegisterSideChannel` and `Academy.UnregisterSideChannel` were
removed.
- Replace `Academy.FloatProperties` with
`SideChannelUtils.GetSideChannel<FloatPropertiesChannel>()`.
- Replace `Academy.RegisterSideChannel` with
`SideChannelUtils.RegisterSideChannel()`.
- Replace `Academy.UnregisterSideChannel` with
`SideChannelUtils.UnregisterSideChannel`.
- If your Agent class overrides `Heuristic()`, change the signature to
`public override void Heuristic(float[] actionsOut)` and assign values to
`actionsOut` instead of returning an array.
- Set `steps_per_update` to be around equal to the number of agents in your environment,
times `num_updates` and divided by `train_interval`.
* The `Agent.CollectObservations()` virtual method now takes as input a `VectorSensor` sensor as argument. The `Agent.AddVectorObs()` methods were removed.
* The `SetMask` was renamed to `SetMask` method must now be called on the `DiscreteActionMasker` argument of the `CollectDiscreteActionMasks` virtual method.
* We consolidated our API for `DiscreteActionMasker`. `SetMask` takes two arguments : the branch index and the list of masked actions for that branch.
* The `Monitor` class has been moved to the Examples Project. (It was prone to errors during testing)
* The `MLAgents.Sensors` namespace has been introduced. All sensors classes are part of the `MLAgents.Sensors` namespace.
* The `MLAgents.SideChannels` namespace has been introduced. All side channel classes are part of the `MLAgents.SideChannels` namespace.
* The interface for `RayPerceptionSensor.PerceiveStatic()` was changed to take an input class and write to an output class, and the method was renamed to `Perceive()`.
* The `SetMask` method must now be called on the `DiscreteActionMasker` argument of the `CollectDiscreteActionMasks` method.
* The method `GetStepCount()` on the Agent class has been replaced with the property getter `StepCount`
* The `--multi-gpu` option has been removed temporarily.
* `AgentInfo.actionMasks` has been renamed to `AgentInfo.discreteActionMasks`.
* `BrainParameters` and `SpaceType` have been removed from the public API
* `BehaviorParameters` have been removed from the public API.
* `DecisionRequester` has been made internal (you can still use the DecisionRequesterComponent from the inspector). `RepeatAction` was renamed `TakeActionsBetweenDecisions` for clarity.
* The following methods in the `Agent` class have been renamed. The original method names will be removed in a later release:
* `InitializeAgent()` was renamed to `Initialize()`
* `AgentAction()` was renamed to `OnActionReceived()`
* `AgentReset()` was renamed to `OnEpsiodeBegin()`
* `Done()` was renamed to `EndEpisode()`
* `GiveModel()` was renamed to `SetModel()`
* The `IFloatProperties` interface has been removed.
* The interface for SideChannels was changed:
* In C#, `OnMessageReceived` now takes a `IncomingMessage` argument, and `QueueMessageToSend` takes an `OutgoingMessage` argument.
* In python, `on_message_received` now takes a `IncomingMessage` argument, and `queue_message_to_send` takes an `OutgoingMessage` argument.
* Automatic stepping for Academy is now controlled from the AutomaticSteppingEnabled property.
- The `Agent.CollectObservations()` virtual method now takes as input a
`VectorSensor` sensor as argument. The `Agent.AddVectorObs()` methods were
removed.
- The `SetMask` was renamed to `SetMask` method must now be called on the
`DiscreteActionMasker` argument of the `CollectDiscreteActionMasks` virtual
method.
- We consolidated our API for `DiscreteActionMasker`. `SetMask` takes two
arguments : the branch index and the list of masked actions for that branch.
- The `Monitor` class has been moved to the Examples Project. (It was prone to
errors during testing)
- The `MLAgents.Sensors` namespace has been introduced. All sensors classes are
part of the `MLAgents.Sensors` namespace.
- The `MLAgents.SideChannels` namespace has been introduced. All side channel
classes are part of the `MLAgents.SideChannels` namespace.
- The interface for `RayPerceptionSensor.PerceiveStatic()` was changed to take
an input class and write to an output class, and the method was renamed to
`Perceive()`.
- The `SetMask` method must now be called on the `DiscreteActionMasker` argument
of the `CollectDiscreteActionMasks` method.
- The method `GetStepCount()` on the Agent class has been replaced with the
property getter `StepCount`
- The `--multi-gpu` option has been removed temporarily.
- `AgentInfo.actionMasks` has been renamed to `AgentInfo.discreteActionMasks`.
- `BrainParameters` and `SpaceType` have been removed from the public API
- `BehaviorParameters` have been removed from the public API.
- `DecisionRequester` has been made internal (you can still use the
DecisionRequesterComponent from the inspector). `RepeatAction` was renamed
`TakeActionsBetweenDecisions` for clarity.
- The following methods in the `Agent` class have been renamed. The original
method names will be removed in a later release:
- `InitializeAgent()` was renamed to `Initialize()`
- `AgentAction()` was renamed to `OnActionReceived()`
- `AgentReset()` was renamed to `OnEpsiodeBegin()`
- `Done()` was renamed to `EndEpisode()`
- `GiveModel()` was renamed to `SetModel()`
- The `IFloatProperties` interface has been removed.
- The interface for SideChannels was changed:
- In C#, `OnMessageReceived` now takes a `IncomingMessage` argument, and
`QueueMessageToSend` takes an `OutgoingMessage` argument.
- In python, `on_message_received` now takes a `IncomingMessage` argument, and
`queue_message_to_send` takes an `OutgoingMessage` argument.
- Automatic stepping for Academy is now controlled from the
AutomaticSteppingEnabled property.
* Add the `using MLAgents.Sensors;` in addition to `using MLAgents;` on top of your Agent's script.
* Replace your Agent's implementation of `CollectObservations()` with `CollectObservations(VectorSensor sensor)`. In addition, replace all calls to `AddVectorObs()` with `sensor.AddObservation()` or `sensor.AddOneHotObservation()` on the `VectorSensor` passed as argument.
* Replace your calls to `SetActionMask` on your Agent to `DiscreteActionMasker.SetActionMask` in `CollectDiscreteActionMasks`.
* If you call `RayPerceptionSensor.PerceiveStatic()` manually, add your inputs to a `RayPerceptionInput`. To get the previous float array output,
iterate through `RayPerceptionOutput.rayOutputs` and call `RayPerceptionOutput.RayOutput.ToFloatArray()`.
* Replace all calls to `Agent.GetStepCount()` with `Agent.StepCount`
* We strongly recommend replacing the following methods with their new equivalent as they will be removed in a later release:
* `InitializeAgent()` to `Initialize()`
* `AgentAction()` to `OnActionReceived()`
* `AgentReset()` to `OnEpisodeBegin()`
* `Done()` to `EndEpisode()`
* `GiveModel()` to `SetModel()`
* Replace `IFloatProperties` variables with `FloatPropertiesChannel` variables.
* If you implemented custom `SideChannels`, update the signatures of your methods, and add your data to the `OutgoingMessage` or read it from the `IncomingMessage`.
* Replace calls to Academy.EnableAutomaticStepping()/DisableAutomaticStepping() with Academy.AutomaticSteppingEnabled = true/false.
- Add the `using MLAgents.Sensors;` in addition to `using MLAgents;` on top of
your Agent's script.
- Replace your Agent's implementation of `CollectObservations()` with
`CollectObservations(VectorSensor sensor)`. In addition, replace all calls to
`AddVectorObs()` with `sensor.AddObservation()` or
`sensor.AddOneHotObservation()` on the `VectorSensor` passed as argument.
- Replace your calls to `SetActionMask` on your Agent to
`DiscreteActionMasker.SetActionMask` in `CollectDiscreteActionMasks`.
- If you call `RayPerceptionSensor.PerceiveStatic()` manually, add your inputs
to a `RayPerceptionInput`. To get the previous float array output, iterate
through `RayPerceptionOutput.rayOutputs` and call
`RayPerceptionOutput.RayOutput.ToFloatArray()`.
- Replace all calls to `Agent.GetStepCount()` with `Agent.StepCount`
- We strongly recommend replacing the following methods with their new
equivalent as they will be removed in a later release:
- `InitializeAgent()` to `Initialize()`
- `AgentAction()` to `OnActionReceived()`
- `AgentReset()` to `OnEpisodeBegin()`
- `Done()` to `EndEpisode()`
- `GiveModel()` to `SetModel()`
- Replace `IFloatProperties` variables with `FloatPropertiesChannel` variables.
- If you implemented custom `SideChannels`, update the signatures of your
methods, and add your data to the `OutgoingMessage` or read it from the
`IncomingMessage`.
- Replace calls to Academy.EnableAutomaticStepping()/DisableAutomaticStepping()
with Academy.AutomaticSteppingEnabled = true/false.
* The `UnitySDK` folder has been split into a Unity Package (`com.unity.ml-agents`) and an examples project (`Project`). Please follow the [Installation Guide](Installation.md) to get up and running with this new repo structure.
* Several changes were made to how agents are reset and marked as done:
* Calling `Done()` on the Agent will now reset it immediately and call the `AgentReset` virtual method. (This is to simplify the previous logic in which the Agent had to wait for the next `EnvironmentStep` to reset)
* The "Reset on Done" setting in AgentParameters was removed; this is now effectively always true. `AgentOnDone` virtual method on the Agent has been removed.
* The `Decision Period` and `On Demand decision` checkbox have been removed from the Agent. On demand decision is now the default (calling `RequestDecision` on the Agent manually.)
* The Academy class was changed to a singleton, and its virtual methods were removed.
* Trainer steps are now counted per-Agent, not per-environment as in previous versions. For instance, if you have 10 Agents in the scene, 20 environment steps now corresponds to 200 steps as printed in the terminal and in Tensorboard.
* Curriculum config files are now YAML formatted and all curricula for a training run are combined into a single file.
* The `--num-runs` command-line option has been removed from `mlagents-learn`.
* Several fields on the Agent were removed or made private in order to simplify the interface.
* The `agentParameters` field of the Agent has been removed. (Contained only `maxStep` information)
* `maxStep` is now a public field on the Agent. (Was moved from `agentParameters`)
* The `Info` field of the Agent has been made private. (Was only used internally and not meant to be modified outside of the Agent)
* The `GetReward()` method on the Agent has been removed. (It was being confused with `GetCumulativeReward()`)
* The `AgentAction` struct no longer contains a `value` field. (Value estimates were not set during inference)
* The `GetValueEstimate()` method on the Agent has been removed.
* The `UpdateValueAction()` method on the Agent has been removed.
* The deprecated `RayPerception3D` and `RayPerception2D` classes were removed, and the `legacyHitFractionBehavior` argument was removed from `RayPerceptionSensor.PerceiveStatic()`.
* RayPerceptionSensor was inconsistent in how it handle scale on the Agent's transform. It now scales the ray length and sphere size for casting as the transform's scale changes.
- The `UnitySDK` folder has been split into a Unity Package
(`com.unity.ml-agents`) and an examples project (`Project`). Please follow the
[Installation Guide](Installation.md) to get up and running with this new repo
structure.
- Several changes were made to how agents are reset and marked as done:
- Calling `Done()` on the Agent will now reset it immediately and call the
`AgentReset` virtual method. (This is to simplify the previous logic in
which the Agent had to wait for the next `EnvironmentStep` to reset)
- The "Reset on Done" setting in AgentParameters was removed; this is now
effectively always true. `AgentOnDone` virtual method on the Agent has been
removed.
- The `Decision Period` and `On Demand decision` checkbox have been removed from
the Agent. On demand decision is now the default (calling `RequestDecision` on
the Agent manually.)
- The Academy class was changed to a singleton, and its virtual methods were
removed.
- Trainer steps are now counted per-Agent, not per-environment as in previous
versions. For instance, if you have 10 Agents in the scene, 20 environment
steps now corresponds to 200 steps as printed in the terminal and in
Tensorboard.
- Curriculum config files are now YAML formatted and all curricula for a
training run are combined into a single file.
- The `--num-runs` command-line option has been removed from `mlagents-learn`.
- Several fields on the Agent were removed or made private in order to simplify
the interface.
- The `agentParameters` field of the Agent has been removed. (Contained only
`maxStep` information)
- `maxStep` is now a public field on the Agent. (Was moved from
`agentParameters`)
- The `Info` field of the Agent has been made private. (Was only used
internally and not meant to be modified outside of the Agent)
- The `GetReward()` method on the Agent has been removed. (It was being
confused with `GetCumulativeReward()`)
- The `AgentAction` struct no longer contains a `value` field. (Value
estimates were not set during inference)
- The `GetValueEstimate()` method on the Agent has been removed.
- The `UpdateValueAction()` method on the Agent has been removed.
- The deprecated `RayPerception3D` and `RayPerception2D` classes were removed,
and the `legacyHitFractionBehavior` argument was removed from
`RayPerceptionSensor.PerceiveStatic()`.
- RayPerceptionSensor was inconsistent in how it handle scale on the Agent's
transform. It now scales the ray length and sphere size for casting as the
transform's scale changes.
* Follow the instructions on how to install the `com.unity.ml-agents` package into your project in the [Installation Guide](Installation.md).
* If your Agent implemented `AgentOnDone` and did not have the checkbox `Reset On Done` checked in the inspector, you must call the code that was in `AgentOnDone` manually.
* If you give your Agent a reward or penalty at the end of an episode (e.g. for reaching a goal or falling off of a platform), make sure you call `AddReward()` or `SetReward()` *before* calling `Done()`. Previously, the order didn't matter.
* If you were not using `On Demand Decision` for your Agent, you **must** add a `DecisionRequester` component to your Agent GameObject and set its `Decision Period` field to the old `Decision Period` of the Agent.
* If you have a class that inherits from Academy:
* If the class didn't override any of the virtual methods and didn't store any additional data, you can just remove the old script from the scene.
* If the class had additional data, create a new MonoBehaviour and store the data in the new MonoBehaviour instead.
* If the class overrode the virtual methods, create a new MonoBehaviour and move the logic to it:
* Move the InitializeAcademy code to MonoBehaviour.OnAwake
* Move the AcademyStep code to MonoBehaviour.FixedUpdate
* Move the OnDestroy code to MonoBehaviour.OnDestroy.
* Move the AcademyReset code to a new method and add it to the Academy.OnEnvironmentReset action.
* Multiply `max_steps` and `summary_freq` in your `trainer_config.yaml` by the number of Agents in the scene.
* Combine curriculum configs into a single file. See [the WallJump curricula](../config/curricula/wall_jump.yaml) for an example of the new curriculum config format.
A tool like https://www.json2yaml.com may be useful to help with the conversion.
* If you have a model trained which uses RayPerceptionSensor and has non-1.0 scale in the Agent's transform, it must be retrained.
- Follow the instructions on how to install the `com.unity.ml-agents` package
into your project in the [Installation Guide](Installation.md).
- If your Agent implemented `AgentOnDone` and did not have the checkbox
`Reset On Done` checked in the inspector, you must call the code that was in
`AgentOnDone` manually.
- If you give your Agent a reward or penalty at the end of an episode (e.g. for
reaching a goal or falling off of a platform), make sure you call
`AddReward()` or `SetReward()` _before_ calling `Done()`. Previously, the
order didn't matter.
- If you were not using `On Demand Decision` for your Agent, you **must** add a
`DecisionRequester` component to your Agent GameObject and set its
`Decision Period` field to the old `Decision Period` of the Agent.
- If you have a class that inherits from Academy:
- If the class didn't override any of the virtual methods and didn't store any
additional data, you can just remove the old script from the scene.
- If the class had additional data, create a new MonoBehaviour and store the
data in the new MonoBehaviour instead.
- If the class overrode the virtual methods, create a new MonoBehaviour and
move the logic to it:
- Move the InitializeAcademy code to MonoBehaviour.OnAwake
- Move the AcademyStep code to MonoBehaviour.FixedUpdate
- Move the OnDestroy code to MonoBehaviour.OnDestroy.
- Move the AcademyReset code to a new method and add it to the
Academy.OnEnvironmentReset action.
- Multiply `max_steps` and `summary_freq` in your `trainer_config.yaml` by the
number of Agents in the scene.
- Combine curriculum configs into a single file. See
[the WallJump curricula](../config/curricula/wall_jump.yaml) for an example of
the new curriculum config format. A tool like https://www.json2yaml.com may be
useful to help with the conversion.
- If you have a model trained which uses RayPerceptionSensor and has non-1.0
scale in the Agent's transform, it must be retrained.
## Migrating from ML-Agents toolkit v0.12.0 to v0.13.0
## Migrating from ML-Agents Toolkit v0.12.0 to v0.13.0
* The low level Python API has changed. You can look at the document [Low Level Python API documentation](Python-API.md) for more information. This should only affect you if you're writing a custom trainer; if you use `mlagents-learn` for training, this should be a transparent change.
* `reset()` on the Low-Level Python API no longer takes a `train_mode` argument. To modify the performance/speed of the engine, you must use an `EngineConfigurationChannel`
* `reset()` on the Low-Level Python API no longer takes a `config` argument. `UnityEnvironment` no longer has a `reset_parameters` field. To modify float properties in the environment, you must use a `FloatPropertiesChannel`. For more information, refer to the [Low Level Python API documentation](Python-API.md)
* `CustomResetParameters` are now removed.
* The Academy no longer has a `Training Configuration` nor `Inference Configuration` field in the inspector. To modify the configuration from the Low-Level Python API, use an `EngineConfigurationChannel`.
To modify it during training, use the new command line arguments `--width`, `--height`, `--quality-level`, `--time-scale` and `--target-frame-rate` in `mlagents-learn`.
* The Academy no longer has a `Default Reset Parameters` field in the inspector. The Academy class no longer has a `ResetParameters`. To access shared float properties with Python, use the new `FloatProperties` field on the Academy.
* Offline Behavioral Cloning has been removed. To learn from demonstrations, use the GAIL and
Behavioral Cloning features with either PPO or SAC. See [Imitation Learning](Training-Imitation-Learning.md) for more information.
* `mlagents.envs` was renamed to `mlagents_envs`. The previous repo layout depended on [PEP420](https://www.python.org/dev/peps/pep-0420/), which caused problems with some of our tooling such as mypy and pylint.
* The official version of Unity ML-Agents supports is now 2018.4 LTS. If you run into issues, please consider deleting your library folder and reponening your projects. You will need to install the Barracuda package into your project in order to ML-Agents to compile correctly.
- The low level Python API has changed. You can look at the document
[Low Level Python API documentation](Python-API.md) for more information. This
should only affect you if you're writing a custom trainer; if you use
`mlagents-learn` for training, this should be a transparent change.
- `reset()` on the Low-Level Python API no longer takes a `train_mode`
argument. To modify the performance/speed of the engine, you must use an
`EngineConfigurationChannel`
- `reset()` on the Low-Level Python API no longer takes a `config` argument.
`UnityEnvironment` no longer has a `reset_parameters` field. To modify float
properties in the environment, you must use a `FloatPropertiesChannel`. For
more information, refer to the
[Low Level Python API documentation](Python-API.md)
- `CustomResetParameters` are now removed.
- The Academy no longer has a `Training Configuration` nor
`Inference Configuration` field in the inspector. To modify the configuration
from the Low-Level Python API, use an `EngineConfigurationChannel`. To modify
it during training, use the new command line arguments `--width`, `--height`,
`--quality-level`, `--time-scale` and `--target-frame-rate` in
`mlagents-learn`.
- The Academy no longer has a `Default Reset Parameters` field in the inspector.
The Academy class no longer has a `ResetParameters`. To access shared float
properties with Python, use the new `FloatProperties` field on the Academy.
- Offline Behavioral Cloning has been removed. To learn from demonstrations, use
the GAIL and Behavioral Cloning features with either PPO or SAC. See
[Imitation Learning](Training-Imitation-Learning.md) for more information.
- `mlagents.envs` was renamed to `mlagents_envs`. The previous repo layout
depended on [PEP420](https://www.python.org/dev/peps/pep-0420/), which caused
problems with some of our tooling such as mypy and pylint.
- The official version of Unity ML-Agents supports is now 2018.4 LTS. If you run
into issues, please consider deleting your library folder and reponening your
projects. You will need to install the Barracuda package into your project in
order to ML-Agents to compile correctly.
* If you had a custom `Training Configuration` in the Academy inspector, you will need to pass your custom configuration at every training run using the new command line arguments `--width`, `--height`, `--quality-level`, `--time-scale` and `--target-frame-rate`.
* If you were using `--slow` in `mlagents-learn`, you will need to pass your old `Inference Configuration` of the Academy inspector with the new command line arguments `--width`, `--height`, `--quality-level`, `--time-scale` and `--target-frame-rate` instead.
* Any imports from `mlagents.envs` should be replaced with `mlagents_envs`.
- If you had a custom `Training Configuration` in the Academy inspector, you
will need to pass your custom configuration at every training run using the
new command line arguments `--width`, `--height`, `--quality-level`,
`--time-scale` and `--target-frame-rate`.
- If you were using `--slow` in `mlagents-learn`, you will need to pass your old
`Inference Configuration` of the Academy inspector with the new command line
arguments `--width`, `--height`, `--quality-level`, `--time-scale` and
`--target-frame-rate` instead.
- Any imports from `mlagents.envs` should be replaced with `mlagents_envs`.
## Migrating from ML-Agents toolkit v0.11.0 to v0.12.0
## Migrating from ML-Agents Toolkit v0.11.0 to v0.12.0
* Text actions and observations, and custom action and observation protos have been removed.
* RayPerception3D and RayPerception2D are marked deprecated, and will be removed in a future release. They can be replaced by RayPerceptionSensorComponent3D and RayPerceptionSensorComponent2D.
* The `Use Heuristic` checkbox in Behavior Parameters has been replaced with a `Behavior Type` dropdown menu. This has the following options:
* `Default` corresponds to the previous unchecked behavior, meaning that Agents will train if they connect to a python trainer, otherwise they will perform inference.
* `Heuristic Only` means the Agent will always use the `Heuristic()` method. This corresponds to having "Use Heuristic" selected in 0.11.0.
* `Inference Only` means the Agent will always perform inference.
* Barracuda was upgraded to 0.3.2, and it is now installed via the Unity Package Manager.
- Text actions and observations, and custom action and observation protos have
been removed.
- RayPerception3D and RayPerception2D are marked deprecated, and will be removed
in a future release. They can be replaced by RayPerceptionSensorComponent3D
and RayPerceptionSensorComponent2D.
- The `Use Heuristic` checkbox in Behavior Parameters has been replaced with a
`Behavior Type` dropdown menu. This has the following options:
- `Default` corresponds to the previous unchecked behavior, meaning that
Agents will train if they connect to a python trainer, otherwise they will
perform inference.
- `Heuristic Only` means the Agent will always use the `Heuristic()` method.
This corresponds to having "Use Heuristic" selected in 0.11.0.
- `Inference Only` means the Agent will always perform inference.
- Barracuda was upgraded to 0.3.2, and it is now installed via the Unity Package
Manager.
* We [fixed a bug](https://github.com/Unity-Technologies/ml-agents/pull/2823) in `RayPerception3d.Perceive()` that was causing the `endOffset` to be used incorrectly. However this may produce different behavior from previous versions if you use a non-zero `startOffset`.
To reproduce the old behavior, you should increase the the value of `endOffset` by `startOffset`.
You can verify your raycasts are performing as expected in scene view using the debug rays.
* If you use RayPerception3D, replace it with RayPerceptionSensorComponent3D (and similarly for 2D). The settings, such as ray angles and detectable tags, are configured on the component now.
RayPerception3D would contribute `(# of rays) * (# of tags + 2)` to the State Size in Behavior Parameters, but this is no longer necessary, so you should reduce the State Size by this amount.
Making this change will require retraining your model, since the observations that RayPerceptionSensorComponent3D produces are different from the old behavior.
* If you see messages such as `The type or namespace 'Barracuda' could not be found` or `The type or namespace 'Google' could not be found`, you will need to [install the Barracuda preview package](Installation.md#package-installation).
- We [fixed a bug](https://github.com/Unity-Technologies/ml-agents/pull/2823) in
`RayPerception3d.Perceive()` that was causing the `endOffset` to be used
incorrectly. However this may produce different behavior from previous
versions if you use a non-zero `startOffset`. To reproduce the old behavior,
you should increase the the value of `endOffset` by `startOffset`. You can
verify your raycasts are performing as expected in scene view using the debug
rays.
- If you use RayPerception3D, replace it with RayPerceptionSensorComponent3D
(and similarly for 2D). The settings, such as ray angles and detectable tags,
are configured on the component now. RayPerception3D would contribute
`(# of rays) * (# of tags + 2)` to the State Size in Behavior Parameters, but
this is no longer necessary, so you should reduce the State Size by this
amount. Making this change will require retraining your model, since the
observations that RayPerceptionSensorComponent3D produces are different from
the old behavior.
- If you see messages such as
`The type or namespace 'Barracuda' could not be found` or
`The type or namespace 'Google' could not be found`, you will need to
[install the Barracuda preview package](Installation.md#package-installation).
## Migrating from ML-Agents toolkit v0.10 to v0.11.0
## Migrating from ML-Agents Toolkit v0.10 to v0.11.0
* The definition of the gRPC service has changed.
* The online BC training feature has been removed.
* The BroadcastHub has been deprecated. If there is a training Python process, all LearningBrains in the scene will automatically be trained. If there is no Python process, inference will be used.
* The Brain ScriptableObjects have been deprecated. The Brain Parameters are now on the Agent and are referred to as Behavior Parameters. Make sure the Behavior Parameters is attached to the Agent GameObject.
* To use a heuristic behavior, implement the `Heuristic()` method in the Agent class and check the `use heuristic` checkbox in the Behavior Parameters.
* Several changes were made to the setup for visual observations (i.e. using Cameras or RenderTextures):
* Camera resolutions are no longer stored in the Brain Parameters.
* AgentParameters no longer stores lists of Cameras and RenderTextures
* To add visual observations to an Agent, you must now attach a CameraSensorComponent or RenderTextureComponent to the agent. The corresponding Camera or RenderTexture can be added to these in the editor, and the resolution and color/grayscale is configured on the component itself.
- The definition of the gRPC service has changed.
- The online BC training feature has been removed.
- The BroadcastHub has been deprecated. If there is a training Python process,
all LearningBrains in the scene will automatically be trained. If there is no
Python process, inference will be used.
- The Brain ScriptableObjects have been deprecated. The Brain Parameters are now
on the Agent and are referred to as Behavior Parameters. Make sure the
Behavior Parameters is attached to the Agent GameObject.
- To use a heuristic behavior, implement the `Heuristic()` method in the Agent
class and check the `use heuristic` checkbox in the Behavior Parameters.
- Several changes were made to the setup for visual observations (i.e. using
Cameras or RenderTextures):
- Camera resolutions are no longer stored in the Brain Parameters.
- AgentParameters no longer stores lists of Cameras and RenderTextures
- To add visual observations to an Agent, you must now attach a
CameraSensorComponent or RenderTextureComponent to the agent. The
corresponding Camera or RenderTexture can be added to these in the editor,
and the resolution and color/grayscale is configured on the component
itself.
* In order to be able to train, make sure both your ML-Agents Python package and UnitySDK code come from the v0.11 release. Training will not work, for example, if you update the ML-Agents Python package, and only update the API Version in UnitySDK.
* If your Agents used visual observations, you must add a CameraSensorComponent corresponding to each old Camera in the Agent's camera list (and similarly for RenderTextures).
* Since Brain ScriptableObjects have been removed, you will need to delete all the Brain ScriptableObjects from your `Assets` folder. Then, add a `Behavior Parameters` component to each `Agent` GameObject.
You will then need to complete the fields on the new `Behavior Parameters` component with the BrainParameters of the old Brain.
## Migrating from ML-Agents toolkit v0.9 to v0.10
- In order to be able to train, make sure both your ML-Agents Python package and
UnitySDK code come from the v0.11 release. Training will not work, for
example, if you update the ML-Agents Python package, and only update the API
Version in UnitySDK.
- If your Agents used visual observations, you must add a CameraSensorComponent
corresponding to each old Camera in the Agent's camera list (and similarly for
RenderTextures).
- Since Brain ScriptableObjects have been removed, you will need to delete all
the Brain ScriptableObjects from your `Assets` folder. Then, add a
`Behavior Parameters` component to each `Agent` GameObject. You will then need
to complete the fields on the new `Behavior Parameters` component with the
BrainParameters of the old Brain.
## Migrating from ML-Agents Toolkit v0.9 to v0.10
* We have updated the C# code in our repository to be in line with Unity Coding Conventions. This has changed the name of some public facing classes and enums.
* The example environments have been updated. If you were using these environments to benchmark your training, please note that the resulting rewards may be slightly different in v0.10.
- We have updated the C# code in our repository to be in line with Unity Coding
Conventions. This has changed the name of some public facing classes and
enums.
- The example environments have been updated. If you were using these
environments to benchmark your training, please note that the resulting
rewards may be slightly different in v0.10.
* `UnitySDK/Assets/ML-Agents/Scripts/Communicator.cs` and its class `Communicator` have been renamed to `UnitySDK/Assets/ML-Agents/Scripts/ICommunicator.cs` and `ICommunicator` respectively.
* The `SpaceType` Enums `discrete`, and `continuous` have been renamed to `Discrete` and `Continuous`.
* We have removed the `Done` call as well as the capacity to set `Max Steps` on the Academy. Therefore an AcademyReset will never be triggered from C# (only from Python). If you want to reset the simulation after a
fixed number of steps, or when an event in the simulation occurs, we recommend looking at our multi-agent example environments (such as FoodCollector).
In our examples, groups of Agents can be reset through an "Area" that can reset groups of Agents.
* The import for `mlagents.envs.UnityEnvironment` was removed. If you are using the Python API, change `from mlagents_envs import UnityEnvironment` to `from mlagents_envs.environment import UnityEnvironment`.
- `UnitySDK/Assets/ML-Agents/Scripts/Communicator.cs` and its class
`Communicator` have been renamed to
`UnitySDK/Assets/ML-Agents/Scripts/ICommunicator.cs` and `ICommunicator`
respectively.
- The `SpaceType` Enums `discrete`, and `continuous` have been renamed to
`Discrete` and `Continuous`.
- We have removed the `Done` call as well as the capacity to set `Max Steps` on
the Academy. Therefore an AcademyReset will never be triggered from C# (only
from Python). If you want to reset the simulation after a fixed number of
steps, or when an event in the simulation occurs, we recommend looking at our
multi-agent example environments (such as FoodCollector). In our examples,
groups of Agents can be reset through an "Area" that can reset groups of
Agents.
- The import for `mlagents.envs.UnityEnvironment` was removed. If you are using
the Python API, change `from mlagents_envs import UnityEnvironment` to
`from mlagents_envs.environment import UnityEnvironment`.
## Migrating from ML-Agents toolkit v0.8 to v0.9
## Migrating from ML-Agents Toolkit v0.8 to v0.9
* We have changed the way reward signals (including Curiosity) are defined in the
`trainer_config.yaml`.
* When using multiple environments, every "step" is recorded in TensorBoard.
* The steps in the command line console corresponds to a single step of a single environment.
Previously, each step corresponded to one step for all environments (i.e., `num_envs` steps).
- We have changed the way reward signals (including Curiosity) are defined in
the `trainer_config.yaml`.
- When using multiple environments, every "step" is recorded in TensorBoard.
- The steps in the command line console corresponds to a single step of a single
environment. Previously, each step corresponded to one step for all
environments (i.e., `num_envs` steps).
* If you were overriding any of these following parameters in your config file, remove them
from the top-level config and follow the steps below:
* `gamma`: Define a new `extrinsic` reward signal and set it's `gamma` to your new gamma.
* `use_curiosity`, `curiosity_strength`, `curiosity_enc_size`: Define a `curiosity` reward signal
and set its `strength` to `curiosity_strength`, and `encoding_size` to `curiosity_enc_size`. Give it
the same `gamma` as your `extrinsic` signal to mimic previous behavior.
See [Reward Signals](Reward-Signals.md) for more information on defining reward signals.
* TensorBoards generated when running multiple environments in v0.8 are not comparable to those generated in
v0.9 in terms of step count. Multiply your v0.8 step count by `num_envs` for an approximate comparison.
You may need to change `max_steps` in your config as appropriate as well.
- If you were overriding any of these following parameters in your config file,
remove them from the top-level config and follow the steps below:
- `gamma`: Define a new `extrinsic` reward signal and set it's `gamma` to your
new gamma.
- `use_curiosity`, `curiosity_strength`, `curiosity_enc_size`: Define a
`curiosity` reward signal and set its `strength` to `curiosity_strength`,
and `encoding_size` to `curiosity_enc_size`. Give it the same `gamma` as
your `extrinsic` signal to mimic previous behavior. See
[Reward Signals](Reward-Signals.md) for more information on defining reward
signals.
- TensorBoards generated when running multiple environments in v0.8 are not
comparable to those generated in v0.9 in terms of step count. Multiply your
v0.8 step count by `num_envs` for an approximate comparison. You may need to
change `max_steps` in your config as appropriate as well.
## Migrating from ML-Agents toolkit v0.7 to v0.8
## Migrating from ML-Agents Toolkit v0.7 to v0.8
* We have split the Python packages into two separate packages `ml-agents` and `ml-agents-envs`.
* `--worker-id` option of `learn.py` has been removed, use `--base-port` instead if you'd like to run multiple instances of `learn.py`.
- We have split the Python packages into two separate packages `ml-agents` and
`ml-agents-envs`.
- `--worker-id` option of `learn.py` has been removed, use `--base-port` instead
if you'd like to run multiple instances of `learn.py`.
* If you are installing via PyPI, there is no change.
* If you intend to make modifications to `ml-agents` or `ml-agents-envs` please check the Installing for Development in the [Installation documentation](Installation.md).
- If you are installing via PyPI, there is no change.
- If you intend to make modifications to `ml-agents` or `ml-agents-envs` please
check the Installing for Development in the
[Installation documentation](Installation.md).
## Migrating from ML-Agents toolkit v0.6 to v0.7
## Migrating from ML-Agents Toolkit v0.6 to v0.7
* We no longer support TFS and are now using the [Unity Inference Engine](Unity-Inference-Engine.md)
- We no longer support TFS and are now using the
[Unity Inference Engine](Unity-Inference-Engine.md)
* Make sure to remove the `ENABLE_TENSORFLOW` flag in your Unity Project settings
- Make sure to remove the `ENABLE_TENSORFLOW` flag in your Unity Project
settings
## Migrating from ML-Agents toolkit v0.5 to v0.6
## Migrating from ML-Agents Toolkit v0.5 to v0.6
* Brains are now Scriptable Objects instead of MonoBehaviors.
* You can no longer modify the type of a Brain. If you want to switch
between `PlayerBrain` and `LearningBrain` for multiple agents,
you will need to assign a new Brain to each agent separately.
__Note:__ You can pass the same Brain to multiple agents in a scene by
leveraging Unity's prefab system or look for all the agents in a scene
using the search bar of the `Hierarchy` window with the word `Agent`.
- Brains are now Scriptable Objects instead of MonoBehaviors.
- You can no longer modify the type of a Brain. If you want to switch between
`PlayerBrain` and `LearningBrain` for multiple agents, you will need to assign
a new Brain to each agent separately. **Note:** You can pass the same Brain to
multiple agents in a scene by leveraging Unity's prefab system or look for all
the agents in a scene using the search bar of the `Hierarchy` window with the
word `Agent`.
* We replaced the **Internal** and **External** Brain with **Learning Brain**.
- We replaced the **Internal** and **External** Brain with **Learning Brain**.
* We removed the `Broadcast` checkbox of the Brain, to use the broadcast
- We removed the `Broadcast` checkbox of the Brain, to use the broadcast
* When training multiple Brains at the same time, each model is now stored
into a separate model file rather than in the same file under different
graph scopes.
* The **Learning Brain** graph scope, placeholder names, output names and custom
- When training multiple Brains at the same time, each model is now stored into
a separate model file rather than in the same file under different graph
scopes.
- The **Learning Brain** graph scope, placeholder names, output names and custom
* To update a scene from v0.5 to v0.6, you must:
* Remove the `Brain` GameObjects in the scene. (Delete all of the
Brain GameObjects under Academy in the scene.)
* Create new `Brain` Scriptable Objects using `Assets -> Create ->
ML-Agents` for each type of the Brain you plan to use, and put
the created files under a folder called Brains within your project.
* Edit their `Brain Parameters` to be the same as the parameters used
in the `Brain` GameObjects.
* Agents have a `Brain` field in the Inspector, you need to drag the
- To update a scene from v0.5 to v0.6, you must:
- Remove the `Brain` GameObjects in the scene. (Delete all of the Brain
GameObjects under Academy in the scene.)
- Create new `Brain` Scriptable Objects using `Assets -> Create -> ML-Agents`
for each type of the Brain you plan to use, and put the created files under
a folder called Brains within your project.
- Edit their `Brain Parameters` to be the same as the parameters used in the
`Brain` GameObjects.
- Agents have a `Brain` field in the Inspector, you need to drag the
* The Academy has a `Broadcast Hub` field in the inspector, which is
list of brains used in the scene. To train or control your Brain
from the `mlagents-learn` Python script, you need to drag the relevant
`LearningBrain` ScriptableObjects used in your scene into entries
into this list.
- The Academy has a `Broadcast Hub` field in the inspector, which is list of
brains used in the scene. To train or control your Brain from the
`mlagents-learn` Python script, you need to drag the relevant
`LearningBrain` ScriptableObjects used in your scene into entries into this
list.
## Migrating from ML-Agents toolkit v0.4 to v0.5
## Migrating from ML-Agents Toolkit v0.4 to v0.5
* The Unity project `unity-environment` has been renamed `UnitySDK`.
* The `python` folder has been renamed to `ml-agents`. It now contains two
- The Unity project `unity-environment` has been renamed `UnitySDK`.
- The `python` folder has been renamed to `ml-agents`. It now contains two
* The supported Unity version has changed from `2017.1 or later` to `2017.4
or later`. 2017.4 is an LTS (Long Term Support) version that helps us
- The supported Unity version has changed from `2017.1 or later` to
`2017.4 or later`. 2017.4 is an LTS (Long Term Support) version that helps us
maintain good quality and support. Earlier versions of Unity might still work,
but you may encounter an
[error](FAQ.md#instance-of-corebraininternal-couldnt-be-created) listed here.

* Discrete Actions now use [branches](https://arxiv.org/abs/1711.08946). You can
- Discrete Actions now use [branches](https://arxiv.org/abs/1711.08946). You can
now specify concurrent discrete actions. You will need to update the Brain
Parameters in the Brain Inspector in all your environments that use discrete
actions. Refer to the

### Python API
* In order to run a training session, you can now use the command
- In order to run a training session, you can now use the command
[here](Training-ML-Agents.md#training-with-mlagents-learn). For example,
if we previously ran
[here](Training-ML-Agents.md#training-with-mlagents-learn). For example, if we
previously ran
```sh
python3 learn.py 3DBall --train

from the root directory where we installed the ML-Agents Toolkit.
* It is now required to specify the path to the yaml trainer configuration file
- It is now required to specify the path to the yaml trainer configuration file
[trainer_config.yaml](../config/trainer_config.yaml). An example of passing
a trainer configuration to `mlagents-learn` is shown above.
* The environment name is now passed through the `--env` option.
* Curriculum learning has been changed. Refer to the
[curriculum learning documentation](Training-Curriculum-Learning.md)
for detailed information. In summary:
* Curriculum files for the same environment must now be placed into a folder.
[trainer_config.yaml](../config/trainer_config.yaml). An example of passing a
trainer configuration to `mlagents-learn` is shown above.
- The environment name is now passed through the `--env` option.
- Curriculum learning has been changed. Refer to the
[curriculum learning documentation](Training-Curriculum-Learning.md) for
detailed information. In summary:
- Curriculum files for the same environment must now be placed into a folder.
* `min_lesson_length` now specifies the minimum number of episodes in a lesson
- `min_lesson_length` now specifies the minimum number of episodes in a lesson
* It is no longer necessary to specify the `Max Steps` of the Academy to use
- It is no longer necessary to specify the `Max Steps` of the Academy to use
## Migrating from ML-Agents toolkit v0.3 to v0.4
## Migrating from ML-Agents Toolkit v0.3 to v0.4
* `using MLAgents;` needs to be added in all of the C# scripts that use
- `using MLAgents;` needs to be added in all of the C# scripts that use
* We've changed some of the Python packages dependencies in requirement.txt
- We've changed some of the Python packages dependencies in requirement.txt
folder
to update your Python packages.
folder to update your Python packages.
## Migrating from ML-Agents toolkit v0.2 to v0.3
## Migrating from ML-Agents Toolkit v0.2 to v0.3
There are a large number of new features and improvements in the ML-Agents
toolkit v0.3 which change both the training process and Unity API in ways which

### Important
* The ML-Agents toolkit is no longer compatible with Python 2.
- The ML-Agents Toolkit is no longer compatible with Python 2.
* The training script `ppo.py` and `PPO.ipynb` Python notebook have been
- The training script `ppo.py` and `PPO.ipynb` Python notebook have been
* Hyperparameters for training Brains are now stored in the
- Hyperparameters for training Brains are now stored in the
* Modifications to an Agent's rewards must now be done using either
- Modifications to an Agent's rewards must now be done using either
* Setting an Agent to done now requires the use of the `Done()` method.
* `CollectStates()` has been replaced by `CollectObservations()`, which now no
- Setting an Agent to done now requires the use of the `Done()` method.
- `CollectStates()` has been replaced by `CollectObservations()`, which now no
* To collect observations, call `AddVectorObs()` within `CollectObservations()`.
- To collect observations, call `AddVectorObs()` within `CollectObservations()`.
* `AgentStep()` has been replaced by `AgentAction()`.
* `WaitTime()` has been removed.
* The `Frame Skip` field of the Academy is replaced by the Agent's `Decision
Frequency` field, enabling the Agent to make decisions at different frequencies.
* The names of the inputs in the Internal Brain have been changed. You must
- `AgentStep()` has been replaced by `AgentAction()`.
- `WaitTime()` has been removed.
- The `Frame Skip` field of the Academy is replaced by the Agent's
`Decision Frequency` field, enabling the Agent to make decisions at different
frequencies.
- The names of the inputs in the Internal Brain have been changed. You must
replace `state` with `vector_observation` and `observation` with
`visual_observation`. In addition, you must remove the `epsilon` placeholder.

the concepts used in ML-Agents. The changes are highlighted in the table below.
| Old - v0.2 and earlier | New - v0.3 and later |
| --- | --- |
| State | Vector Observation |
| Observation | Visual Observation |
| Action | Vector Action |
| N/A | Text Observation |
| N/A | Text Action |
| ---------------------- | -------------------- |
| State | Vector Observation |
| Observation | Visual Observation |
| Action | Vector Action |
| N/A | Text Observation |
| N/A | Text Action |

8
docs/Python-API.md


`env.step()`).
- `reward` is a float vector of length batch size. Corresponds to the
rewards collected by each agent since the last simulation step.
- `done` is an array of booleans of length batch size. Is true if the
associated Agent was terminated during the last simulation step.
- `agent_id` is an int vector of length batch size containing unique
identifier for the corresponding Agent. This is used to track Agents
across simulation steps.

(Each array has one less dimension than the arrays in `DecisionSteps`)
- `reward` is a float. Corresponds to the rewards collected by the agent
since the last simulation step.
- `done` is a bool. Is true if the Agent was terminated during the last
simulation step.
- `agent_id` is an int and an unique identifier for the corresponding Agent.
- `action_mask` is an optional list of one dimensional array of booleans.
Only available in multi-discrete action space type.

`env.step()`).
- `reward` is a float vector of length batch size. Corresponds to the
rewards collected by each agent since the last simulation step.
- `done` is an array of booleans of length batch size. Is true if the
associated Agent was terminated during the last simulation step.
- `agent_id` is an int vector of length batch size containing unique
identifier for the corresponding Agent. This is used to track Agents
across simulation steps.

(Each array has one less dimension than the arrays in `TerminalSteps`)
- `reward` is a float. Corresponds to the rewards collected by the agent
since the last simulation step.
- `done` is a bool. Is true if the Agent was terminated during the last
simulation step.
- `agent_id` is an int and an unique identifier for the corresponding Agent.
- `max_step` is a bool. Is true if the Agent reached its maximum number of
steps during the last simulation step.

4
docs/Training-ML-Agents.md


| tau | How aggressively to update the target network used for bootstrapping value estimation in SAC. | SAC |
| time_horizon | How many steps of experience to collect per-agent before adding it to the experience buffer. | PPO, SAC |
| trainer | The type of training to perform: "ppo", "sac", "offline_bc" or "online_bc". | PPO, SAC |
| train_interval | How often to update the agent. | SAC |
| num_update | Number of mini-batches to update the agent with during each update. | SAC |
| steps_per_update | Ratio of agent steps per mini-batch update. | SAC |
| threaded | Run the trainer in a parallel thread from the environment steps. (Default: true) | PPO, SAC |
For specific advice on setting hyperparameters based on the type of training you
are conducting, see:

9
docs/Training-PPO.md


in most cases, it is sufficient to use the `--initialize-from` CLI parameter to initialize
all models from the same run.
### (Optional) Advanced: Disable Threading
By default, PPO model updates can happen while the environment is being stepped. This violates the
[on-policy](https://spinningup.openai.com/en/latest/user/algorithms.html#the-on-policy-algorithms)
assumption of PPO slightly in exchange for a 10-20% training speedup. To maintain the
strict on-policyness of PPO, you can disable parallel updates by setting `threaded` to `false`.
Default Value: `true`
## Training Statistics
To view training statistics, use TensorBoard. For information on launching and

40
docs/Training-SAC.md


Curiosity reward, which can be used to encourage exploration in sparse extrinsic reward
environments.
#### Number of Updates for Reward Signal (Optional)
#### Steps Per Update for Reward Signal (Optional)
`reward_signal_num_update` for the reward signals corresponds to the number of mini batches sampled
and used for updating the reward signals during each
update. By default, we update the reward signals once every time the main policy is updated.
`reward_signal_steps_per_update` for the reward signals corresponds to the number of steps per mini batch sampled
and used for updating the reward signals. By default, we update the reward signals once every time the main policy is updated.
we may want to update the policy N times, then update the reward signal (GAIL) M times.
We can change `train_interval` and `num_update` of SAC to N, as well as `reward_signal_num_update`
under `reward_signals` to M to accomplish this. By default, `reward_signal_num_update` is set to
`num_update`.
we may want to update the reward signal (GAIL) M times for every update of the policy.
We can change `steps_per_update` of SAC to N, as well as `reward_signal_steps_per_update`
under `reward_signals` to N / M to accomplish this. By default, `reward_signal_steps_per_update` is set to
`steps_per_update`.
Typical Range: `num_update`
Typical Range: `steps_per_update`
### Buffer Size

Typical Range: `1` - `5`
### Number of Updates
### Steps Per Update
`num_update` corresponds to the number of mini batches sampled and used for training during each
training event. In SAC, a single "update" corresponds to grabbing a batch of size `batch_size` from the experience
replay buffer, and using this mini batch to update the models. Typically, this can be left at 1.
However, to imitate the training procedure in certain papers (e.g.
[Kostrikov et. al](http://arxiv.org/abs/1809.02925), [Blondé et. al](http://arxiv.org/abs/1809.02064)),
we may want to update N times with different mini batches before grabbing additional samples.
We can change `train_interval` and `num_update` to N to accomplish this.
`steps_per_update` corresponds to the average ratio of agent steps (actions) taken to updates made of the agent's
policy. In SAC, a single "update" corresponds to grabbing a batch of size `batch_size` from the experience
replay buffer, and using this mini batch to update the models. Note that it is not guaranteed that after
exactly `steps_per_update` steps an update will be made, only that the ratio will hold true over many steps.
Typically, `steps_per_update` should be greater than or equal to 1. Note that setting `steps_per_update` lower will
improve sample efficiency (reduce the number of steps required to train)
but increase the CPU time spent performing updates. For most environments where steps are fairly fast (e.g. our example
environments) `steps_per_update` equal to the number of agents in the scene is a good balance.
For slow environments (steps take 0.1 seconds or more) reducing `steps_per_update` may improve training speed.
We can also change `steps_per_update` to lower than 1 to update more often than once per step, though this will
usually result in a slowdown unless the environment is very slow.
Typical Range: `1`
Typical Range: `1` - `20`
### Tau

2
docs/Training-on-Amazon-Web-Service.md


[Deep Learning AMI (Ubuntu)](https://aws.amazon.com/marketplace/pp/B077GCH38C)
listed under AWS Marketplace with a p2.xlarge instance.
### Installing the ML-Agents toolkit on the instance
### Installing the ML-Agents Toolkit on the instance
After launching your EC2 instance using the ami and ssh into it:

2
docs/Training-on-Microsoft-Azure.md


# Training on Microsoft Azure (works with ML-Agents toolkit v0.3)
# Training on Microsoft Azure (works with ML-Agents Toolkit v0.3)
:warning: **Note:** We no longer use this guide ourselves and so it may not work
correctly. We've decided to keep it up just in case it is helpful to you.

52
ml-agents/mlagents/trainers/agent_processor.py


import sys
from typing import List, Dict, Deque, TypeVar, Generic, Tuple, Any, Union
from collections import defaultdict, Counter, deque
from typing import List, Dict, TypeVar, Generic, Tuple, Any, Union
from collections import defaultdict, Counter
import queue
from mlagents_envs.base_env import (
DecisionSteps,

pass
def __init__(self, behavior_id: str, maxlen: int = 1000):
def __init__(self, behavior_id: str, maxlen: int = 20):
self.maxlen: int = maxlen
self.queue: Deque[T] = deque(maxlen=self.maxlen)
self.behavior_id = behavior_id
self._maxlen: int = maxlen
self._queue: queue.Queue = queue.Queue(maxsize=maxlen)
self._behavior_id = behavior_id
@property
def maxlen(self):
"""
The maximum length of the queue.
:return: Maximum length of the queue.
"""
return self._maxlen
@property
def behavior_id(self):
"""
The Behavior ID of this queue.
:return: Behavior ID associated with the queue.
"""
return self._behavior_id
def qsize(self) -> int:
"""
Returns the approximate size of the queue. Note that values may differ
depending on the underlying queue implementation.
"""
return self._queue.qsize()
return len(self.queue) == 0
return self._queue.empty()
"""
Gets the next item from the queue, throwing an AgentManagerQueue.Empty exception
if the queue is empty.
"""
return self.queue.popleft()
except IndexError:
return self._queue.get_nowait()
except queue.Empty:
self.queue.append(item)
self._queue.put(item)
class AgentManager(AgentProcessor):

self.trajectory_queue: AgentManagerQueue[Trajectory] = AgentManagerQueue(
self.behavior_id
)
# NOTE: we make policy queues of infinite length to avoid lockups of the trainers.
# In the environment manager, we make sure to empty the policy queue before continuing to produce steps.
self.behavior_id
self.behavior_id, maxlen=0
)
self.publish_trajectory_queue(self.trajectory_queue)

12
ml-agents/mlagents/trainers/env_manager.py


if self.first_step_infos is not None:
self._process_step_infos(self.first_step_infos)
self.first_step_infos = None
# Get new policies if found
# Get new policies if found. Always get the latest policy.
_policy = None
_policy = self.agent_managers[brain_name].policy_queue.get_nowait()
self.set_policy(brain_name, _policy)
# We make sure to empty the policy queue before continuing to produce steps.
# This halts the trainers until the policy queue is empty.
while True:
_policy = self.agent_managers[brain_name].policy_queue.get_nowait()
pass
if _policy is not None:
self.set_policy(brain_name, _policy)
# Step the environment
new_step_infos = self._step()
# Add to AgentProcessor

4
ml-agents/mlagents/trainers/ghost/trainer.py


# We grab at most the maximum length of the queue.
# This ensures that even if the queue is being filled faster than it is
# being emptied, the trajectories in the queue are on-policy.
for _ in range(trajectory_queue.maxlen):
for _ in range(trajectory_queue.qsize()):
t = trajectory_queue.get_nowait()
# adds to wrapped trainers queue
internal_trajectory_queue.put(t)

else:
# Dump trajectories from non-learning policy
try:
for _ in range(trajectory_queue.maxlen):
for _ in range(trajectory_queue.qsize()):
t = trajectory_queue.get_nowait()
# count ghost steps
self.ghost_step += len(t.steps)

1
ml-agents/mlagents/trainers/ppo/trainer.py


for stat, val in update_stats.items():
self._stats_reporter.add_stat(stat, val)
self._clear_update_buffer()
return True
def create_policy(
self, parsed_behavior_id: BehaviorIdentifiers, brain_parameters: BrainParameters

90
ml-agents/mlagents/trainers/sac/trainer.py


logger = get_logger(__name__)
BUFFER_TRUNCATE_PERCENT = 0.8
DEFAULT_STEPS_PER_UPDATE = 1
class SACTrainer(RLTrainer):

"init_entcoef",
"max_steps",
"normalize",
"num_update",
"steps_per_update",
"sequence_length",
"summary_freq",
"tau",

self.optimizer: SACOptimizer = None # type: ignore
self.step = 0
self.train_interval = (
trainer_parameters["train_interval"]
if "train_interval" in trainer_parameters
else 1
# Don't count buffer_init_steps in steps_per_update ratio, but also don't divide-by-0
self.update_steps = max(1, self.trainer_parameters["buffer_init_steps"])
self.reward_signal_update_steps = max(
1, self.trainer_parameters["buffer_init_steps"]
self.reward_signal_updates_per_train = (
trainer_parameters["reward_signals"]["reward_signal_num_update"]
if "reward_signal_num_update" in trainer_parameters["reward_signals"]
else trainer_parameters["num_update"]
self.steps_per_update = (
trainer_parameters["steps_per_update"]
if "steps_per_update" in trainer_parameters
else DEFAULT_STEPS_PER_UPDATE
)
self.reward_signal_steps_per_update = (
trainer_parameters["reward_signals"]["reward_signal_steps_per_update"]
if "reward_signal_steps_per_update" in trainer_parameters["reward_signals"]
else self.steps_per_update
)
self.checkpoint_replay_buffer = (

def _is_ready_update(self) -> bool:
"""
Returns whether or not the trainer has enough elements to run update model
:return: A boolean corresponding to whether or not update_model() can be run
:return: A boolean corresponding to whether or not _update_policy() can be run
"""
return (
self.update_buffer.num_experiences >= self.trainer_parameters["batch_size"]

@timed
def _update_policy(self) -> None:
def _update_policy(self) -> bool:
If train_interval is met, update the SAC policy given the current reward signals.
If reward_signal_train_interval is met, update the reward signals from the buffer.
Update the SAC policy and reward signals. The reward signal generators are updated using different mini batches.
By default we imitate http://arxiv.org/abs/1809.02925 and similar papers, where the policy is updated
N times, then the reward signals are updated N times.
:return: Whether or not the policy was updated.
if self.step % self.train_interval == 0:
self.update_sac_policy()
self.update_reward_signals()
policy_was_updated = self._update_sac_policy()
self._update_reward_signals()
return policy_was_updated
def create_policy(
self, parsed_behavior_id: BehaviorIdentifiers, brain_parameters: BrainParameters

return policy
def update_sac_policy(self) -> None:
def _update_sac_policy(self) -> bool:
Uses demonstration_buffer to update the policy.
The reward signal generators are updated using different mini batches.
If we want to imitate http://arxiv.org/abs/1809.02925 and similar papers, where the policy is updated
N times, then the reward signals are updated N times, then reward_signal_updates_per_train
is greater than 1 and the reward signals are not updated in parallel.
Uses update_buffer to update the policy. We sample the update_buffer and update
until the steps_per_update ratio is met.
has_updated = False
num_updates = self.trainer_parameters["num_update"]
for _ in range(num_updates):
while self.step / self.update_steps > self.steps_per_update:
logger.debug("Updating SAC policy at step {}".format(self.step))
buffer = self.update_buffer
if (

for stat_name, value in update_stats.items():
batch_update_stats[stat_name].append(value)
self.update_steps += 1
for stat, stat_list in batch_update_stats.items():
self._stats_reporter.add_stat(stat, np.mean(stat_list))
has_updated = True
if self.optimizer.bc_module:
update_stats = self.optimizer.bc_module.update()
for stat, val in update_stats.items():
self._stats_reporter.add_stat(stat, val)
# Truncate update buffer if neccessary. Truncate more than we need to to avoid truncating
# a large buffer at each update.
if self.update_buffer.num_experiences > self.trainer_parameters["buffer_size"]:

return has_updated
for stat, stat_list in batch_update_stats.items():
self._stats_reporter.add_stat(stat, np.mean(stat_list))
if self.optimizer.bc_module:
update_stats = self.optimizer.bc_module.update()
for stat, val in update_stats.items():
self._stats_reporter.add_stat(stat, val)
def update_reward_signals(self) -> None:
def _update_reward_signals(self) -> None:
"""
Iterate through the reward signals and update them. Unlike in PPO,
do it separate from the policy so that it can be done at a different

and policy are updated in parallel.
"""
buffer = self.update_buffer
num_updates = self.reward_signal_updates_per_train
for _ in range(num_updates):
while (
self.step / self.reward_signal_update_steps
> self.reward_signal_steps_per_update
):
# Get minibatches for reward signal update if needed
reward_signal_minibatches = {}
for name, signal in self.optimizer.reward_signals.items():

)
for stat_name, value in update_stats.items():
batch_update_stats[stat_name].append(value)
for stat, stat_list in batch_update_stats.items():
self._stats_reporter.add_stat(stat, np.mean(stat_list))
self.reward_signal_update_steps += 1
for stat, stat_list in batch_update_stats.items():
self._stats_reporter.add_stat(stat, np.mean(stat_list))
def add_policy(
self, parsed_behavior_id: BehaviorIdentifiers, policy: TFPolicy

3
ml-agents/mlagents/trainers/tests/test_reward_signals.py


max_steps: 5.0e4
memory_size: 256
normalize: false
num_update: 1
train_interval: 1
steps_per_update: 1
num_layers: 2
time_horizon: 64
sequence_length: 64

23
ml-agents/mlagents/trainers/tests/test_rl_trainer.py


import yaml
from unittest import mock
import pytest
import mlagents.trainers.tests.mock_brain as mb
from mlagents.trainers.trainer.rl_trainer import RLTrainer
from mlagents.trainers.tests.test_buffer import construct_fake_buffer

# Add concrete implementations of abstract methods
class FakeTrainer(RLTrainer):
def set_is_policy_updating(self, is_updating):
self.update_policy = is_updating
def get_policy(self, name_behavior_id):
return mock.Mock()

def _update_policy(self):
pass
return self.update_policy
def add_policy(self):
pass

def create_rl_trainer():
mock_brainparams = create_mock_brain()
trainer = FakeTrainer(mock_brainparams, dummy_config(), True, 0)
trainer.set_is_policy_updating(True)
return trainer

def test_advance(mocked_clear_update_buffer):
trainer = create_rl_trainer()
trajectory_queue = AgentManagerQueue("testbrain")
policy_queue = AgentManagerQueue("testbrain")
time_horizon = 15
trainer.publish_policy_queue(policy_queue)
time_horizon = 10
trajectory = mb.make_fake_trajectory(
length=time_horizon,
max_step_complete=True,

trajectory_queue.put(trajectory)
trainer.advance()
policy_queue.get_nowait()
for _ in range(0, 5):
trajectory_queue.put(trajectory)
trainer.advance()
# Check that there is stuff in the policy queue
policy_queue.get_nowait()
# Check that if the policy doesn't update, we don't push it to the queue
trainer.set_is_policy_updating(False)
# Check that there nothing in the policy queue
with pytest.raises(AgentManagerQueue.Empty):
policy_queue.get_nowait()
# Check that the buffer has been cleared
assert not trainer.should_still_train

32
ml-agents/mlagents/trainers/tests/test_sac.py


return yaml.safe_load(
"""
trainer: sac
batch_size: 32
batch_size: 8
buffer_size: 10240
buffer_init_steps: 0
hidden_units: 32

memory_size: 10
normalize: true
num_update: 1
train_interval: 1
steps_per_update: 1
num_layers: 1
time_horizon: 64
sequence_length: 16

trainer.add_policy(brain_params, policy)
def test_process_trajectory(dummy_config):
def test_advance(dummy_config):
dummy_config["steps_per_update"] = 20
policy_queue = AgentManagerQueue("testbrain")
trainer.publish_policy_queue(policy_queue)
trajectory = make_fake_trajectory(
length=15,

action_space=[2],
is_discrete=False,
)
trajectory_queue.put(trajectory)
trainer.advance()

# Add a terminal trajectory
trajectory = make_fake_trajectory(
length=15,
length=6,
is_discrete=False,
)
trajectory_queue.put(trajectory)
trainer.advance()

assert (
trainer.stats_reporter.get_stats_summaries("Policy/Extrinsic Reward").mean > 0
)
# Make sure there is a policy on the queue
policy_queue.get_nowait()
# Add another trajectory. Since this is less than 20 steps total (enough for)
# two updates, there should NOT be a policy on the queue.
trajectory = make_fake_trajectory(
length=5,
max_step_complete=False,
vec_obs_size=6,
num_vis_obs=0,
action_space=[2],
is_discrete=False,
)
trajectory_queue.put(trajectory)
trainer.advance()
with pytest.raises(AgentManagerQueue.Empty):
policy_queue.get_nowait()
def test_bad_config(dummy_config):

20
ml-agents/mlagents/trainers/tests/test_simple_rl.py


sequence_length: 64
summary_freq: 500
use_recurrent: false
threaded: false
reward_signals:
extrinsic:
strength: 1.0

{BRAIN_NAME}:
trainer: sac
batch_size: 8
buffer_size: 500
buffer_size: 5000
buffer_init_steps: 100
hidden_units: 16
init_entcoef: 0.01

normalize: false
num_update: 1
train_interval: 1
steps_per_update: 1
num_layers: 1
time_horizon: 64
sequence_length: 32

curiosity_enc_size: 128
demo_path: None
vis_encode_type: simple
threaded: false
reward_signals:
extrinsic:
strength: 1.0

StatsReporter.writers.clear() # Clear StatsReporters so we don't write to file
debug_writer = DebugWriter()
StatsReporter.add_writer(debug_writer)
# Make sure threading is turned off for determinism
trainer_config["threading"] = False
if env_manager is None:
env_manager = SimpleEnvManager(env, FloatPropertiesChannel())
trainer_factory = TrainerFactory(

override_vals = {
"batch_size": 64,
"use_recurrent": True,
"max_steps": 3000,
"max_steps": 5000,
"steps_per_update": 2,
}
config = generate_config(SAC_CONFIG, override_vals)
_check_environment_trains(env, config)

[BRAIN_NAME + "?team=0", brain_name_opp + "?team=1"], use_discrete=use_discrete
)
override_vals = {
"max_steps": 2000,
"max_steps": 4000,
"save_steps": 5000,
"swap_steps": 5000,
"team_change": 2000,
"save_steps": 10000,
"swap_steps": 10000,
"team_change": 4000,
},
}
config = generate_config(PPO_CONFIG, override_vals)

12
ml-agents/mlagents/trainers/tests/test_subprocess_env_manager.py


from mlagents_envs.exception import UnityEnvironmentException
from mlagents.trainers.tests.simple_test_envs import SimpleEnvironment
from mlagents.trainers.stats import StatsReporter
from mlagents.trainers.agent_processor import AgentManagerQueue
from mlagents.trainers.tests.test_simple_rl import (
_check_environment_trains,
PPO_CONFIG,

)
external_brains_mock.return_value = [brain_name]
agent_manager_mock = mock.Mock()
mock_policy = mock.Mock()
agent_manager_mock.policy_queue.get_nowait.side_effect = [
mock_policy,
mock_policy,
AgentManagerQueue.Empty(),
]
env_manager.set_agent_manager(brain_name, agent_manager_mock)
step_info_dict = {brain_name: (Mock(), Mock())}

)
# Test policy queue
mock_policy = mock.Mock()
agent_manager_mock.policy_queue.get_nowait.return_value = mock_policy
env_manager.advance()
assert env_manager.policies[brain_name] == mock_policy
assert agent_manager_mock.policy == mock_policy

env_manager = SubprocessEnvManager(
simple_env_factory, EngineConfig.default_config(), num_envs
)
trainer_config = generate_config(PPO_CONFIG)
trainer_config = generate_config(PPO_CONFIG, override_vals={"max_steps": 5000})
# Run PPO using env_manager
_check_environment_trains(
simple_env_factory(0, []),

3
ml-agents/mlagents/trainers/tests/test_trainer_controller.py


env_mock.reset.assert_not_called()
env_mock.advance.assert_called_once()
trainer_mock.advance.assert_called_once()
# May have been called many times due to thread
trainer_mock.advance.call_count > 0

14
ml-agents/mlagents/trainers/trainer/rl_trainer.py


return False
@abc.abstractmethod
def _update_policy(self):
def _update_policy(self) -> bool:
:return: Whether or not the policy was updated.
"""
pass

def advance(self) -> None:
"""
Steps the trainer, taking in trajectories and updates if ready.
Will block and wait briefly if there are no trajectories.
"""
with hierarchical_timer("process_trajectory"):
for traj_queue in self.trajectory_queues:

for _ in range(traj_queue.maxlen):
for _ in range(traj_queue.qsize()):
try:
t = traj_queue.get_nowait()
self._process_trajectory(t)

if self._is_ready_update():
with hierarchical_timer("_update_policy"):
self._update_policy()
for q in self.policy_queues:
# Get policies that correspond to the policy queue in question
q.put(self.get_policy(q.behavior_id))
if self._update_policy():
for q in self.policy_queues:
# Get policies that correspond to the policy queue in question
q.put(self.get_policy(q.behavior_id))
else:
self._clear_update_buffer()

10
ml-agents/mlagents/trainers/trainer/trainer.py


self.run_id = run_id
self.trainer_parameters = trainer_parameters
self.summary_path = trainer_parameters["summary_path"]
self._threaded = trainer_parameters.get("threaded", True)
self._stats_reporter = StatsReporter(self.summary_path)
self.is_training = training
self._reward_buffer: Deque[float] = deque(maxlen=reward_buff_cap)

:return: the step count of the trainer
"""
return self.step
@property
def threaded(self) -> bool:
"""
Whether or not to run the trainer in a thread. True allows the trainer to
update the policy while the environment is taking steps. Set to False to
enforce strict on-policy updates (i.e. don't update the policy when taking steps.)
"""
return self._threaded
@property
def should_still_train(self) -> bool:

31
ml-agents/mlagents/trainers/trainer_controller.py


import os
import sys
from typing import Dict, Optional, Set
import threading
from typing import Dict, Optional, Set, List
from collections import defaultdict
import numpy as np

:param training_seed: Seed to use for Numpy and Tensorflow random number generation.
:param sampler_manager: SamplerManager object handles samplers for resampling the reset parameters.
:param resampling_interval: Specifies number of simulation steps after which reset parameters are resampled.
:param threaded: Whether or not to run trainers in a separate thread. Disable for testing/debugging.
"""
self.trainers: Dict[str, Trainer] = {}
self.brain_name_to_identifier: Dict[str, Set] = defaultdict(set)

self.meta_curriculum = meta_curriculum
self.sampler_manager = sampler_manager
self.resampling_interval = resampling_interval
self.trainer_threads: List[threading.Thread] = []
self.kill_trainers = False
np.random.seed(training_seed)
tf.set_random_seed(training_seed)

trainer.publish_policy_queue(agent_manager.policy_queue)
trainer.subscribe_trajectory_queue(agent_manager.trajectory_queue)
if trainer.threaded:
# Start trainer thread
trainerthread = threading.Thread(
target=self.trainer_update_func, args=(trainer,), daemon=True
)
trainerthread.start()
self.trainer_threads.append(trainerthread)
def _create_trainers_and_managers(
self, env_manager: EnvManager, behavior_ids: Set[str]

self.reset_env_if_ready(env_manager, global_step)
if self._should_save_model(global_step):
self._save_model()
# Stop advancing trainers
self.kill_trainers = True
# Final save Tensorflow model
if global_step != 0 and self.train_model:
self._save_model()

UnityEnvironmentException,
) as ex:
self.kill_trainers = True
if self.train_model:
self._save_model_when_interrupted()

"Environment/Lesson", curr.lesson_num
)
# Advance trainers. This can be done in a separate loop in the future.
with hierarchical_timer("trainer_advance"):
for trainer in self.trainers.values():
trainer.advance()
for trainer in self.trainers.values():
if not trainer.threaded:
with hierarchical_timer("trainer_advance"):
trainer.advance()
def trainer_update_func(self, trainer: Trainer) -> None:
while not self.kill_trainers:
with hierarchical_timer("trainer_advance"):
trainer.advance()
正在加载...
取消
保存