浏览代码

update yamato tests from master

/r2v-yamato-linux
Chris Elion 4 年前
当前提交
7f8258a8
共有 17 个文件被更改,包括 406 次插入213 次删除
  1. 12
      .pre-commit-config.yaml
  2. 4
      .yamato/com.unity.ml-agents-pack.yml
  3. 2
      .yamato/com.unity.ml-agents-test.yml
  4. 20
      .yamato/gym-interface-test.yml
  5. 43
      .yamato/protobuf-generation-test.yml
  6. 27
      .yamato/python-ll-api-test.yml
  7. 40
      .yamato/standalone-build-test.yml
  8. 51
      .yamato/training-int-tests.yml
  9. 8
      Project/Assets/ML-Agents/Editor/Tests/StandaloneBuildTest.cs
  10. 3
      ml-agents-envs/mlagents_envs/environment.py
  11. 10
      ml-agents/tests/yamato/check_coverage_percent.py
  12. 8
      ml-agents/tests/yamato/scripts/run_gym.py
  13. 49
      ml-agents/tests/yamato/scripts/run_llapi.py
  14. 17
      ml-agents/tests/yamato/standalone_build_tests.py
  15. 130
      ml-agents/tests/yamato/training_int_tests.py
  16. 142
      ml-agents/tests/yamato/yamato_utils.py
  17. 53
      ml-agents/tests/yamato/scripts/run_compressed_sensor.py

12
.pre-commit-config.yaml


hooks:
- id: python-check-mock-methods
- repo: https://github.com/pre-commit/mirrors-pylint
rev: v2.4.4
hooks:
- id: pylint
exclude: >
(?x)^(
.*_pb2.py|
.*_pb2_grpc.py|
.*/tests/.*
)$
args: [--score=n]
- repo: https://github.com/mattlqx/pre-commit-search-and-replace
rev: v1.0.3
hooks:

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


pack:
name: Pack
agent:
type: Unity::VM::osx
image: package-ci/mac:stable
type: Unity::VM
image: package-ci/ubuntu:stable
flavor: b1.small
commands:
- npm install upm-ci-utils@stable -g --registry https://artifactory.prd.cds.internal.unity3d.com/artifactory/api/npm/upm-npm

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


- .yamato/com.unity.ml-agents-pack.yml#pack
triggers:
cancel_old_ci: true
{% if platform.name == "mac" %}
{% if platform.name == "linux" %}
changes:
only:
- "com.unity.ml-agents/**"

20
.yamato/gym-interface-test.yml


---
{% for editor in test_editors %}
test_gym_interface_{{ editor.version }}:
name: Test Mac Gym Interface {{ editor.version }}
name: Test Linux Gym Interface {{ editor.version }}
type: Unity::VM::osx
image: ml-agents/ml-agents-bokken-mac:0.1.4-492264
flavor: b1.small
type: Unity::VM
image: package-ci/ubuntu:stable
flavor: b1.medium
- pip install pyyaml --index-url https://artifactory.prd.it.unity3d.com/artifactory/api/pypi/pypi/simple
- python -u -m ml-agents.tests.yamato.setup_venv
- ./venv/bin/python ml-agents/tests/yamato/scripts/run_gym.py --env=artifacts/testPlayer-Basic
- |
sudo apt-get update && sudo apt-get install -y python3-venv
python3 -m venv venv && source venv/bin/activate
python -m pip install wheel --index-url https://artifactory.prd.it.unity3d.com/artifactory/api/pypi/pypi/simple
python -m pip install pyyaml --index-url https://artifactory.prd.it.unity3d.com/artifactory/api/pypi/pypi/simple
python -u -m ml-agents.tests.yamato.setup_venv
python ml-agents/tests/yamato/scripts/run_gym.py --env=artifacts/testPlayer-Basic
- .yamato/standalone-build-test.yml#test_mac_standalone_{{ editor.version }}
- .yamato/standalone-build-test.yml#test_linux_standalone_{{ editor.version }}
triggers:
cancel_old_ci: true
expression: |

43
.yamato/protobuf-generation-test.yml


test_mac_protobuf_generation:
test_linux_protobuf_generation:
type: Unity::VM::osx
image: ml-agents/ml-agents-bokken-mac:0.1.4-492264
flavor: b1.small
type: Unity::VM
image: package-ci/ubuntu:stable
flavor: b1.large
brew install nuget
sudo apt-get update && sudo apt-get install -y python3-venv nuget
python3 -m venv venv && source venv/bin/activate
python3 -m venv venv
. venv/bin/activate
pip install --upgrade pip --index-url https://artifactory.prd.it.unity3d.com/artifactory/api/pypi/pypi/simple
pip install grpcio==1.28.1 grpcio-tools==1.13.0 protobuf==3.11.3 six==1.14.0 mypy-protobuf==1.16.0 --progress-bar=off --index-url https://artifactory.prd.it.unity3d.com/artifactory/api/pypi/pypi/simple
cd protobuf-definitions
chmod +x Grpc.Tools.$GRPC_VERSION/tools/macosx_x64/protoc
chmod +x Grpc.Tools.$GRPC_VERSION/tools/macosx_x64/grpc_csharp_plugin
COMPILER=Grpc.Tools.$GRPC_VERSION/tools/macosx_x64 ./make.sh
python3 -m pip install --upgrade pip --index-url https://artifactory.prd.it.unity3d.com/artifactory/api/pypi/pypi/simple
python3 -m pip install grpcio==1.28.1 grpcio-tools==1.13.0 protobuf==3.11.3 six==1.14.0 mypy-protobuf==1.16.0 --progress-bar=off --index-url https://artifactory.prd.it.unity3d.com/artifactory/api/pypi/pypi/simple
pushd protobuf-definitions
chmod +x Grpc.Tools.$GRPC_VERSION/tools/linux_x64/protoc
chmod +x Grpc.Tools.$GRPC_VERSION/tools/linux_x64/grpc_csharp_plugin
COMPILER=Grpc.Tools.$GRPC_VERSION/tools/linux_x64 ./make.sh
popd
mkdir -p artifacts
touch artifacts/proto.patch
git diff --exit-code -- :/ ":(exclude,top)$CS_PROTO_PATH/*.meta" \

triggers:
cancel_old_ci: true
changes:
only:
- "protobuf-definitions/**"
- ".yamato/protobuf-generation-test.yml"
except:
- "protobuf-definitions/*.md"
- "protobuf-definitions/**/*.md"
expression: |
(pull_request.target eq "master" OR
pull_request.target match "release.+") AND
NOT pull_request.draft AND
(pull_request.changes.any match "protobuf-definitions/**" OR
pull_request.changes.any match "com.unity.ml-agents/Runtime/Grpc/CommunicatorObjects/**" OR
pull_request.changes.any match "ml-agents-envs/mlagents_envs/communicator_objects/**" OR
pull_request.changes.any match ".yamato/protobuf-generation-test.yml") AND
NOT pull_request.changes.all match "protobuf-definitions/**/*.md"
artifacts:
patch:
paths:

27
.yamato/python-ll-api-test.yml


- version: 2019.3
---
{% for editor in test_editors %}
test_mac_ll_api_{{ editor.version }}:
name: Test Mac LL-API {{ editor.version }}
test_linux_ll_api_{{ editor.version }}:
name: Test Linux LL-API {{ editor.version }}
type: Unity::VM::osx
image: ml-agents/ml-agents-bokken-mac:0.1.4-492264
flavor: b1.small
type: Unity::VM
image: package-ci/ubuntu:stable
flavor: b1.medium
- pip install pyyaml --index-url https://artifactory.prd.it.unity3d.com/artifactory/api/pypi/pypi/simple
- python -u -m ml-agents.tests.yamato.setup_venv
- ./venv/bin/python ml-agents/tests/yamato/scripts/run_llapi.py
- ./venv/bin/python ml-agents/tests/yamato/scripts/run_llapi.py --env=artifacts/testPlayer-Basic
- ./venv/bin/python ml-agents/tests/yamato/scripts/run_llapi.py --env=artifacts/testPlayer-WallJump
- ./venv/bin/python ml-agents/tests/yamato/scripts/run_llapi.py --env=artifacts/testPlayer-Bouncer
- |
sudo apt-get update && sudo apt-get install -y python3-venv
python3 -m venv venv && source venv/bin/activate
python -m pip install pyyaml --index-url https://artifactory.prd.it.unity3d.com/artifactory/api/pypi/pypi/simple
python -u -m ml-agents.tests.yamato.setup_venv
python ml-agents/tests/yamato/scripts/run_llapi.py
python ml-agents/tests/yamato/scripts/run_llapi.py --env=artifacts/testPlayer-Basic
python ml-agents/tests/yamato/scripts/run_llapi.py --env=artifacts/testPlayer-WallJump
python ml-agents/tests/yamato/scripts/run_llapi.py --env=artifacts/testPlayer-Bouncer
- .yamato/standalone-build-test.yml#test_mac_standalone_{{ editor.version }}
- .yamato/standalone-build-test.yml#test_linux_standalone_{{ editor.version }}
triggers:
cancel_old_ci: true
expression: |

40
.yamato/standalone-build-test.yml


- version: 2019.3
---
{% for editor in test_editors %}
test_mac_standalone_{{ editor.version }}:
name: Test Mac Standalone {{ editor.version }}
test_linux_standalone_{{ editor.version }}:
name: Test Linux Standalone {{ editor.version }}
type: Unity::VM::osx
image: ml-agents/ml-agents-bokken-mac:0.1.4-492264
flavor: i1.small
type: Unity::VM
image: package-ci/ubuntu:stable
flavor: b1.large
- pip install pyyaml --index-url https://artifactory.prd.it.unity3d.com/artifactory/api/pypi/pypi/simple
- python -u -m ml-agents.tests.yamato.standalone_build_tests
- python -u -m ml-agents.tests.yamato.standalone_build_tests --scene=Assets/ML-Agents/Examples/Basic/Scenes/Basic.unity
- python -u -m ml-agents.tests.yamato.standalone_build_tests --scene=Assets/ML-Agents/Examples/Bouncer/Scenes/Bouncer.unity
- python -u -m ml-agents.tests.yamato.standalone_build_tests --scene=Assets/ML-Agents/Examples/WallJump/Scenes/WallJump.unity
- python3 -m pip install pyyaml --index-url https://artifactory.prd.it.unity3d.com/artifactory/api/pypi/pypi/simple
- python3 -m pip install unity-downloader-cli --index-url https://artifactory.prd.it.unity3d.com/artifactory/api/pypi/pypi/simple --upgrade
- unity-downloader-cli -u {{ editor.version }} -c editor --wait --fast
- python3 -u -m ml-agents.tests.yamato.standalone_build_tests --build-target=linux
- python3 -u -m ml-agents.tests.yamato.standalone_build_tests --build-target=linux --scene=Assets/ML-Agents/Examples/Basic/Scenes/Basic.unity
- python3 -u -m ml-agents.tests.yamato.standalone_build_tests --build-target=linux --scene=Assets/ML-Agents/Examples/Bouncer/Scenes/Bouncer.unity
- python3 -u -m ml-agents.tests.yamato.standalone_build_tests --build-target=linux --scene=Assets/ML-Agents/Examples/WallJump/Scenes/WallJump.unity
changes:
only:
- "com.unity.ml-agents/**"
- "Project/**"
- ".yamato/standalone-build-test.yml"
except:
- "*.md"
- "com.unity.ml-agents/*.md"
- "com.unity.ml-agents/**/*.md"
expression: |
(pull_request.target eq "master" OR
pull_request.target match "release.+") AND
NOT pull_request.draft AND
(pull_request.changes.any match "com.unity.ml-agents/**" OR
pull_request.changes.any match "com.unity.ml-agents.extensions/**" OR
pull_request.changes.any match ".yamato/standalone-build-test.yml") AND
NOT pull_request.changes.all match "**/*.md"
artifacts:
logs:
paths:

- "artifacts/testPlayer*/**"
- "artifacts/**/UnityPlayer.so"
{% endfor %}

51
.yamato/training-int-tests.yml


- version: 2019.3
---
{% for editor in test_editors %}
test_mac_training_int_{{ editor.version }}:
name: Test Mac Fast Training {{ editor.version }}
test_linux_training_int_{{ editor.version }}:
name: Test Linux Fast Training {{ editor.version }}
type: Unity::VM::osx
image: ml-agents/ml-agents-bokken-mac:0.1.4-492264
flavor: b1.small
type: Unity::VM
image: package-ci/ubuntu:stable
flavor: b1.medium
- pip install pyyaml --index-url https://artifactory.prd.it.unity3d.com/artifactory/api/pypi/pypi/simple
- python -u -m ml-agents.tests.yamato.training_int_tests
# Backwards-compatibility tests.
# If we make a breaking change to the communication protocol, these will need
# to be disabled until the next release.
# - python -u -m ml-agents.tests.yamato.training_int_tests --python=0.15.0
# - python -u -m ml-agents.tests.yamato.training_int_tests --csharp=0.15.0
- |
sudo apt-get update && sudo apt-get install -y python3-venv
python3 -m venv venv && source venv/bin/activate
python -m pip install pyyaml --index-url https://artifactory.prd.it.unity3d.com/artifactory/api/pypi/pypi/simple
python -u -m ml-agents.tests.yamato.training_int_tests
- .yamato/standalone-build-test.yml#test_mac_standalone_{{ editor.version }}
- .yamato/standalone-build-test.yml#test_linux_standalone_{{ editor.version }}
changes:
only:
- "com.unity.ml-agents/**"
- "Project/**"
- "ml-agents/**"
- "ml-agents-envs/**"
- ".yamato/training-int-tests.yml"
except:
- "*.md"
- "com.unity.ml-agents/*.md"
- "com.unity.ml-agents/**/*.md"
expression: |
(pull_request.target eq "master" OR
pull_request.target match "release.+") AND
NOT pull_request.draft AND
(pull_request.changes.any match "com.unity.ml-agents/**" OR
pull_request.changes.any match "com.unity.ml-agents.extensions/**" OR
pull_request.changes.any match "Project/**" OR
pull_request.changes.any match "ml-agents/**" OR
pull_request.changes.any match "ml-agents-envs/**" OR
pull_request.changes.any match ".yamato/training-int-tests.yml") AND
NOT pull_request.changes.all match "**/*.md"
- "artifacts/inference.nn.txt"
- "artifacts/inference.onnx.txt"
- "artifacts/testplayer*/**"
- "artifacts/testPlayer*/**"
- "artifacts/models/**"
{% endfor %}

8
Project/Assets/ML-Agents/Editor/Tests/StandaloneBuildTest.cs


{
const string k_OutputCommandLineFlag = "--mlagents-build-output-path";
const string k_SceneCommandLineFlag = "--mlagents-build-scene-path";
const string k_BuildTargetFlag = "--mlagents-build-target";
public static void BuildStandalonePlayerOSX()
{

var buildTarget = BuildTarget.StandaloneOSX;
var args = Environment.GetCommandLineArgs();
for (var i = 0; i < args.Length - 1; i++)

{
scenePath = args[i + 1];
}
else if (args[i] == k_BuildTargetFlag)
{
buildTarget = (BuildTarget) Enum.Parse(typeof(BuildTarget), args[i + 1], ignoreCase: true);
}
}
string[] scenes = { scenePath };

BuildTarget.StandaloneOSX,
buildTarget,
BuildOptions.None
);
var isOk = buildResult.summary.result == BuildResult.Succeeded;

3
ml-agents-envs/mlagents_envs/environment.py


candidates = glob.glob(env_path + ".x86_64")
if len(candidates) == 0:
candidates = glob.glob(env_path + ".x86")
if len(candidates) == 0:
if os.path.isfile(env_path):
candidates = [env_path]
if len(candidates) > 0:
launch_string = candidates[0]

10
ml-agents/tests/yamato/check_coverage_percent.py


SUMMARY_XML_FILENAME = "Summary.xml"
# Note that this is python2 compatible, since that's currently what's installed on most CI images.
def check_coverage(root_dir, min_percentage):
# Walk the root directory looking for the summary file that

pct = float(pct)
if pct < min_percentage:
print(
"Coverage {} is below the min percentage of {}.".format(
pct, min_percentage
)
f"Coverage {pct} is below the min percentage of {min_percentage}."
"Coverage {} is above the min percentage of {}.".format(
pct, min_percentage
)
f"Coverage {pct} is above the min percentage of {min_percentage}."
)
sys.exit(0)

8
ml-agents/tests/yamato/scripts/run_gym.py


:param env_name: Name of the Unity environment binary to launch
"""
u_env = UnityEnvironment(env_name, worker_id=1, no_graphics=True)
env = UnityToGymWrapper(u_env, use_visual=False)
env = UnityToGymWrapper(u_env)
try:
# Examine environment parameters

try:
env1 = UnityToGymWrapper(
UnityEnvironment(env_name, worker_id=1, no_graphics=True), use_visual=False
UnityEnvironment(env_name, worker_id=1, no_graphics=True)
UnityEnvironment(env_name, worker_id=1, no_graphics=True), use_visual=False
UnityEnvironment(env_name, worker_id=1, no_graphics=True)
UnityEnvironment(env_name, worker_id=2, no_graphics=True), use_visual=False
UnityEnvironment(env_name, worker_id=2, no_graphics=True)
)
env2.reset()
finally:

49
ml-agents/tests/yamato/scripts/run_llapi.py


import argparse
import numpy as np
from mlagents_envs.environment import UnityEnvironment
from mlagents_envs.side_channel.engine_configuration_channel import (

file_name=env_name,
side_channels=[engine_configuration_channel],
no_graphics=True,
args=["-logFile", "-"],
additional_args=["-logFile", "-"],
)
try:

# Set the default brain to work with
group_name = env.get_behavior_names()[0]
group_spec = env.get_behavior_spec(group_name)
group_name = list(env.behavior_specs.keys())[0]
group_spec = env.behavior_specs[group_name]
# Set the time scale of the engine
engine_configuration_channel.set_configuration_parameters(time_scale=3.0)

# Examine the number of observations per Agent
print("Number of observations : ", len(group_spec.observation_shapes))
print("Number of observations : ", len(group_spec.observation_specs))
vis_obs = any(len(shape) == 3 for shape in group_spec.observation_shapes)
vis_obs = any(
len(obs_spec.shape) == 3 for obs_spec in group_spec.observation_specs
)
print("Is there a visual observation ?", vis_obs)
# Examine the state space for the first observation for the first agent

episode_rewards = 0
tracked_agent = -1
while not done:
if group_spec.is_action_continuous():
action = np.random.randn(
len(decision_steps), group_spec.action_size
)
elif group_spec.is_action_discrete():
branch_size = group_spec.discrete_action_branches
action = np.column_stack(
[
np.random.randint(
0, branch_size[i], size=(len(decision_steps))
)
for i in range(len(branch_size))
]
)
else:
# Should never happen
action = None
action_tuple = group_spec.action_spec.random_action(len(decision_steps))
env.set_actions(group_name, action)
env.set_actions(group_name, action_tuple)
env.step()
decision_steps, terminal_steps = env.get_steps(group_name)
done = False

"""
try:
env1 = UnityEnvironment(
file_name=env_name, base_port=5006, no_graphics=True, args=["-logFile", "-"]
file_name=env_name,
base_port=5006,
no_graphics=True,
additional_args=["-logFile", "-"],
file_name=env_name, base_port=5006, no_graphics=True, args=["-logFile", "-"]
file_name=env_name,
base_port=5006,
no_graphics=True,
additional_args=["-logFile", "-"],
file_name=env_name, base_port=5007, no_graphics=True, args=["-logFile", "-"]
file_name=env_name,
base_port=5007,
no_graphics=True,
additional_args=["-logFile", "-"],
)
env2.reset()
finally:

17
ml-agents/tests/yamato/standalone_build_tests.py


import os
import sys
import argparse

def main(scene_path):
def main(scene_path, build_target):
executable_name = None
executable_name = "testPlayer"
executable_name = scene_path.strip(".unity")
executable_name = os.path.splitext(scene_path)[0] # Remove extension
print(f"Executable name {executable_name}")
base_path, output_path=executable_name, scene_path=scene_path
base_path,
output_path=executable_name,
scene_path=scene_path,
build_target=build_target,
log_output_path=None, # Log to stdout so we get timestamps on the logs
)
if returncode == 0:

if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--scene", default=None)
parser.add_argument("--build-target", default="mac", choices=["mac", "linux"])
main(args.scene)
main(args.scene, args.build_target)

130
ml-agents/tests/yamato/training_int_tests.py


import argparse
import os
import shutil
from typing import Any
find_executables,
override_legacy_config_file,
def run_training(python_version, csharp_version):
def run_training(python_version: str, csharp_version: str) -> bool:
nn_file_expected = f"./models/{run_id}/3DBall.nn"
if os.path.exists(nn_file_expected):
output_dir = "models" if python_version else "results"
onnx_file_expected = f"./{output_dir}/{run_id}/3DBall.onnx"
if os.path.exists(onnx_file_expected):
sys.exit(1)
return False
base_path = get_base_path()
print(f"Running in base path {base_path}")

build_returncode = run_standalone_build(base_path)
if build_returncode != 0:
print("Standalone build FAILED!")
sys.exit(build_returncode)
print(f"Standalone build FAILED! with return code {build_returncode}")
return False
# Now rename the newly-built executable, and restore the old one
os.rename(full_player_path, final_player_path)

standalone_player_path = "testPlayer"
venv_path = init_venv(python_version)
init_venv(python_version)
override_config_file(
"config/trainer_config.yaml",
"override.yaml",
max_steps=100,
batch_size=10,
buffer_size=10,
)
yaml_out = "override.yaml"
if python_version:
overrides: Any = {"max_steps": 100, "batch_size": 10, "buffer_size": 10}
override_legacy_config_file(
python_version, "config/trainer_config.yaml", yaml_out, **overrides
)
else:
overrides = {
"hyperparameters": {"batch_size": 10, "buffer_size": 10},
"max_steps": 100,
}
override_config_file("config/ppo/3DBall.yaml", yaml_out, overrides)
log_output_path = f"{get_base_output_path()}/training.log"
env_path = os.path.join(get_base_output_path(), standalone_player_path)
mla_learn_cmd = [
"mlagents-learn",
yaml_out,
"--force",
"--env",
env_path,
"--run-id",
str(run_id),
"--no-graphics",
"--env-args",
"-logFile",
log_output_path,
]
mla_learn_cmd = (
f"mlagents-learn override.yaml --train --env="
f"{os.path.join(get_base_output_path(), standalone_player_path)} "
f"--run-id={run_id} --no-graphics --env-args -logFile -"
) # noqa
res = subprocess.run(
f"source {venv_path}/bin/activate; {mla_learn_cmd}", shell=True
)
res = subprocess.run(mla_learn_cmd)
if res.returncode != 0 or not os.path.exists(nn_file_expected):
# Save models as artifacts (only if we're using latest python and C#)
if csharp_version is None and python_version is None:
model_artifacts_dir = os.path.join(get_base_output_path(), "models")
os.makedirs(model_artifacts_dir, exist_ok=True)
if os.path.exists(onnx_file_expected):
shutil.copy(onnx_file_expected, model_artifacts_dir)
if res.returncode != 0 or not os.path.exists(onnx_file_expected):
sys.exit(1)
print("Command line: " + " ".join(mla_learn_cmd))
subprocess.run(["cat", log_output_path])
return False
if csharp_version is None and python_version is None:
# Use abs path so that loading doesn't get confused
model_path = os.path.abspath(os.path.dirname(onnx_file_expected))
inference_ok = run_inference(env_path, model_path, "onnx")
if not inference_ok:
return False
sys.exit(0)
return True
def run_inference(env_path: str, output_path: str, model_extension: str) -> bool:
start_time = time.time()
exes = find_executables(env_path)
if len(exes) != 1:
print(f"Can't determine the player executable in {env_path}. Found {exes}.")
return False
log_output_path = f"{get_base_output_path()}/inference.{model_extension}.txt"
exe_path = exes[0]
args = [
exe_path,
"-nographics",
"-batchmode",
"-logfile",
log_output_path,
"--mlagents-override-model-directory",
output_path,
"--mlagents-quit-on-load-failure",
"--mlagents-quit-after-episodes",
"1",
"--mlagents-override-model-extension",
model_extension,
]
print(f"Starting inference with args {' '.join(args)}")
timeout = 15 * 60 # 15 minutes for inference is more than enough
res = subprocess.run(args, timeout=timeout)
end_time = time.time()
if res.returncode != 0:
print("Error running inference!")
print("Command line: " + " ".join(args))
subprocess.run(["cat", log_output_path])
return False
else:
print(f"Inference succeeded! Took {end_time - start_time} seconds")
return True
def main():

args = parser.parse_args()
try:
run_training(args.python, args.csharp)
ok = run_training(args.python, args.csharp)
if not ok:
sys.exit(1)
finally:
# Cleanup - this gets executed even if we hit sys.exit()
undo_git_checkout()

142
ml-agents/tests/yamato/yamato_utils.py


import shutil
import subprocess
import yaml
from sys import platform
UNITY_VERSION = os.environ["UNITY_VERSION"]
BOKKEN_UNITY = f"/Users/bokken/{UNITY_VERSION}/Unity.app/Contents/MacOS/Unity"
HUB_UNITY = (
f"/Applications/Unity/Hub/Editor/{UNITY_VERSION}/Unity.app/Contents/MacOS/Unity"
)
if os.path.exists(BOKKEN_UNITY):
return BOKKEN_UNITY
if os.path.exists(HUB_UNITY):
return HUB_UNITY
raise FileNotFoundError("Can't find bokken or hub executables")
if platform == "darwin":
downloader_install_path = "./.Editor/Unity.app/Contents/MacOS/Unity"
else: # if platform == "linux":
downloader_install_path = "./.Editor/Unity"
if os.path.exists(downloader_install_path):
return downloader_install_path
raise FileNotFoundError("Can't find executable from unity-downloader-cli")
def get_base_path():

verbose: bool = False,
output_path: str = None,
scene_path: str = None,
log_output_path: str = f"{get_base_output_path()}/standalone_build.txt",
build_target: str = None,
log_output_path: Optional[str] = f"{get_base_output_path()}/standalone_build.txt",
artifacts/standalone_build/testPlayer.
artifacts/standalonebuild/testPlayer.
print(f"Running BuildStandalonePlayerOSX via {unity_exe}")
print(f"Running BuildStandalonePlayer via {unity_exe}")
# enum values from https://docs.unity3d.com/2019.4/Documentation/ScriptReference/BuildTarget.html
build_target_to_enum = {
"mac": "StandaloneOSX",
"osx": "StandaloneOSX",
"linux": "StandaloneLinux64",
}
test_args = [
unity_exe,

"Unity.MLAgents.StandaloneBuildTest.BuildStandalonePlayerOSX",
]
os.makedirs(os.path.dirname(log_output_path), exist_ok=True)
subprocess.run(["touch", log_output_path])
test_args += ["-logfile", log_output_path]
if log_output_path:
os.makedirs(os.path.dirname(log_output_path), exist_ok=True)
subprocess.run(["touch", log_output_path])
test_args += ["-logfile", log_output_path]
else:
# Log to stdout
test_args += ["-logfile", "-"]
if output_path is not None:
output_path = os.path.join(get_base_output_path(), output_path)

test_args += ["--mlagents-build-scene-path", scene_path]
if build_target is not None:
test_args += ["--mlagents-build-target", build_target_to_enum[build_target]]
print(f"{' '.join(test_args)} ...")
timeout = 30 * 60 # 30 minutes, just in case

if output_path is None and res.returncode == 0:
exe_name = "testPlayer.app" if platform == "darwin" else "testPlayer"
os.path.join(base_path, "Project", "testPlayer.app"),
os.path.join(get_base_output_path(), "testPlayer.app"),
os.path.join(base_path, "Project", exe_name),
os.path.join(get_base_output_path(), exe_name),
subprocess.run(["cat", log_output_path])
if log_output_path:
subprocess.run(["cat", log_output_path])
def find_executables(root_dir: str) -> List[str]:
"""
Try to find the player executable. This seems to vary between Unity versions.
"""
ignored_extension = frozenset([".dll", ".dylib", ".bundle"])
ignored_files = frozenset(["macblas"])
exes = []
for root, _, files in os.walk(root_dir):
for filename in files:
file_root, ext = os.path.splitext(filename)
if ext in ignored_extension or filename in ignored_files:
continue
file_path = os.path.join(root, filename)
if os.access(file_path, os.X_OK):
exes.append(file_path)
# Also check the input path
if os.access(root_dir, os.X_OK):
exes.append(root_dir)
return exes
) -> str:
) -> None:
Set up the virtual environment, and return the venv path.
Install the necessary packages for the venv
# Use a different venv path for different versions
venv_path = "venv"
if mlagents_python_version:
venv_path += "_" + mlagents_python_version
# Set up the venv and install mlagents
subprocess.check_call(f"python -m venv {venv_path}", shell=True)
pip_commands = [
"--upgrade pip",
"--upgrade setuptools",
# TODO build these and publish to internal pypi
"~/tensorflow_pkg/tensorflow-2.0.0-cp37-cp37m-macosx_10_14_x86_64.whl",
]
pip_commands = ["--upgrade pip", "--upgrade setuptools"]
if platform != "darwin":
raise RuntimeError("Yamato can only run tensorflow on mac platforms!")
# TODO build these and publish to internal pypi
"~/tensorflow_pkg/tensorflow-2.0.0-cp37-cp37m-macosx_10_14_x86_64.whl",
"tf2onnx==1.6.1",
]
else:
# Local install

print(f'Running "python3 -m pip install -q {cmd} {pip_index_url}"')
f"source {venv_path}/bin/activate; python -m pip install -q {cmd} {pip_index_url}",
shell=True,
f"python3 -m pip install -q {cmd} {pip_index_url}", shell=True
return venv_path
def checkout_csharp_version(csharp_version):

if csharp_version is None:
return
csharp_dirs = ["com.unity.ml-agents", "Project"]
csharp_tag = f"com.unity.ml-agents_{csharp_version}"
csharp_dirs = ["com.unity.ml-agents", "com.unity.ml-agents.extensions", "Project"]
subprocess.check_call(
f"git checkout {csharp_version} -- {csharp_dir}", shell=True
)
# Allow the checkout to fail, since the extensions folder isn't availabe in 1.0.0
subprocess.call(f"git checkout {csharp_tag} -- {csharp_dir}", shell=True)
def undo_git_checkout():

subprocess.check_call("rm -rf Project/Library", shell=True)
def override_config_file(src_path, dest_path, **kwargs):
def override_config_file(src_path, dest_path, overrides):
with open(src_path) as f:
configs = yaml.safe_load(f)
behavior_configs = configs["behaviors"]
for config in behavior_configs.values():
_override_config_dict(config, overrides)
with open(dest_path, "w") as f:
yaml.dump(configs, f)
def _override_config_dict(config, overrides):
for key, val in overrides.items():
if isinstance(val, dict):
_override_config_dict(config[key], val)
else:
config[key] = val
def override_legacy_config_file(python_version, src_path, dest_path, **kwargs):
"""
Override settings in a trainer config file, using an old version of the src_path. For example,
override_config_file("0.16.0", src_path, dest_path, max_steps=42)
will sync the file at src_path from version 0.16.0, copy it to dest_path, and override the
max_steps field to 42 for all brains.
"""
# Sync the old version of the file
python_tag = f"python-packages_{python_version}"
subprocess.check_call(f"git checkout {python_tag} -- {src_path}", shell=True)
with open(src_path) as f:
configs = yaml.safe_load(f)

53
ml-agents/tests/yamato/scripts/run_compressed_sensor.py


import argparse
import numpy as np
from mlagents_envs.environment import UnityEnvironment
EPSILON = 0.001
def test_run_environment(env_name):
"""
Run the low-level API test of compressed sensors using the specified environment
:param env_name: Name of the Unity environment binary to launch
"""
env = UnityEnvironment(
file_name=env_name, no_graphics=True, additional_args=["-logFile", "-"]
)
try:
# Reset the environment
env.reset()
env.step()
# Set the default brain to work with
group_name = list(env.behavior_specs.keys())[0]
# Get the state of the agents
decision_steps, _ = env.get_steps(group_name)
# One observation comes from compressed sensor while the other comes
# from an uncompressed sensor
obs_1 = decision_steps.obs[0][0, :, :, :]
obs_2 = decision_steps.obs[0][1, :, :, :]
diff = np.abs(obs_1 - obs_2)
# make sure both are identical
assert np.max(diff) < EPSILON
# make sure an actual observation was collected
assert np.max(obs_1) > EPSILON
print("Observations were identical")
finally:
env.close()
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--env", default="artifacts/testPlayer")
args = parser.parse_args()
test_run_environment(args.env)
正在加载...
取消
保存