diff --git a/.github/unittest/linux_libs/scripts_smacv2/environment.yml b/.github/unittest/linux_libs/scripts_smacv2/environment.yml new file mode 100644 index 00000000000..d1e1e1f5edc --- /dev/null +++ b/.github/unittest/linux_libs/scripts_smacv2/environment.yml @@ -0,0 +1,21 @@ +channels: + - pytorch + - defaults +dependencies: + - pip + - pip: + - cloudpickle + - gym + - gym-notices + - importlib-metadata + - zipp + - pytest + - pytest-cov + - pytest-mock + - pytest-instafail + - pytest-rerunfailures + - pytest-error-for-skips + - expecttest + - pyyaml + - numpy==1.23.0 + - git+https://github.com/oxwhirl/smacv2.git diff --git a/.github/unittest/linux_libs/scripts_smacv2/install.sh b/.github/unittest/linux_libs/scripts_smacv2/install.sh new file mode 100755 index 00000000000..cb36c7cc48a --- /dev/null +++ b/.github/unittest/linux_libs/scripts_smacv2/install.sh @@ -0,0 +1,46 @@ +#!/usr/bin/env bash + +unset PYTORCH_VERSION +# For unittest, nightly PyTorch is used as the following section, +# so no need to set PYTORCH_VERSION. +# In fact, keeping PYTORCH_VERSION forces us to hardcode PyTorch version in config. + +set -e + +eval "$(./conda/bin/conda shell.bash hook)" +conda activate ./env + +if [ "${CU_VERSION:-}" == cpu ] ; then + version="cpu" +else + if [[ ${#CU_VERSION} -eq 4 ]]; then + CUDA_VERSION="${CU_VERSION:2:1}.${CU_VERSION:3:1}" + elif [[ ${#CU_VERSION} -eq 5 ]]; then + CUDA_VERSION="${CU_VERSION:2:2}.${CU_VERSION:4:1}" + fi + echo "Using CUDA $CUDA_VERSION as determined by CU_VERSION ($CU_VERSION)" + version="$(python -c "print('.'.join(\"${CUDA_VERSION}\".split('.')[:2]))")" +fi + +# submodules +git submodule sync && git submodule update --init --recursive + +printf "Installing PyTorch with %s\n" "${CU_VERSION}" +if [ "${CU_VERSION:-}" == cpu ] ; then + # conda install -y pytorch torchvision cpuonly -c pytorch-nightly + # use pip to install pytorch as conda can frequently pick older release +# conda install -y pytorch cpuonly -c pytorch-nightly + pip3 install --pre torch --extra-index-url https://download.pytorch.org/whl/nightly/cpu --force-reinstall +else + pip3 install --pre torch --extra-index-url https://download.pytorch.org/whl/nightly/cu116 --force-reinstall +fi + +# install tensordict +pip install git+https://github.com/pytorch-labs/tensordict.git + +# smoke test +python -c "import tensordict" + +printf "* Installing torchrl\n" +python setup.py develop +python -c "import torchrl" diff --git a/.github/unittest/linux_libs/scripts_smacv2/post_process.sh b/.github/unittest/linux_libs/scripts_smacv2/post_process.sh new file mode 100755 index 00000000000..e97bf2a7b1b --- /dev/null +++ b/.github/unittest/linux_libs/scripts_smacv2/post_process.sh @@ -0,0 +1,6 @@ +#!/usr/bin/env bash + +set -e + +eval "$(./conda/bin/conda shell.bash hook)" +conda activate ./env diff --git a/.github/unittest/linux_libs/scripts_smacv2/run-clang-format.py b/.github/unittest/linux_libs/scripts_smacv2/run-clang-format.py new file mode 100755 index 00000000000..5783a885d86 --- /dev/null +++ b/.github/unittest/linux_libs/scripts_smacv2/run-clang-format.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python +""" +MIT License + +Copyright (c) 2017 Guillaume Papin + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +A wrapper script around clang-format, suitable for linting multiple files +and to use for continuous integration. + +This is an alternative API for the clang-format command line. +It runs over multiple files and directories in parallel. +A diff output is produced and a sensible exit code is returned. + +""" + +import argparse +import difflib +import fnmatch +import multiprocessing +import os +import signal +import subprocess +import sys +import traceback +from functools import partial + +try: + from subprocess import DEVNULL # py3k +except ImportError: + DEVNULL = open(os.devnull, "wb") + + +DEFAULT_EXTENSIONS = "c,h,C,H,cpp,hpp,cc,hh,c++,h++,cxx,hxx,cu" + + +class ExitStatus: + SUCCESS = 0 + DIFF = 1 + TROUBLE = 2 + + +def list_files(files, recursive=False, extensions=None, exclude=None): + if extensions is None: + extensions = [] + if exclude is None: + exclude = [] + + out = [] + for file in files: + if recursive and os.path.isdir(file): + for dirpath, dnames, fnames in os.walk(file): + fpaths = [os.path.join(dirpath, fname) for fname in fnames] + for pattern in exclude: + # os.walk() supports trimming down the dnames list + # by modifying it in-place, + # to avoid unnecessary directory listings. + dnames[:] = [ + x + for x in dnames + if not fnmatch.fnmatch(os.path.join(dirpath, x), pattern) + ] + fpaths = [x for x in fpaths if not fnmatch.fnmatch(x, pattern)] + for f in fpaths: + ext = os.path.splitext(f)[1][1:] + if ext in extensions: + out.append(f) + else: + out.append(file) + return out + + +def make_diff(file, original, reformatted): + return list( + difflib.unified_diff( + original, + reformatted, + fromfile=f"{file}\t(original)", + tofile=f"{file}\t(reformatted)", + n=3, + ) + ) + + +class DiffError(Exception): + def __init__(self, message, errs=None): + super().__init__(message) + self.errs = errs or [] + + +class UnexpectedError(Exception): + def __init__(self, message, exc=None): + super().__init__(message) + self.formatted_traceback = traceback.format_exc() + self.exc = exc + + +def run_clang_format_diff_wrapper(args, file): + try: + ret = run_clang_format_diff(args, file) + return ret + except DiffError: + raise + except Exception as e: + raise UnexpectedError(f"{file}: {e.__class__.__name__}: {e}", e) + + +def run_clang_format_diff(args, file): + try: + with open(file, encoding="utf-8") as f: + original = f.readlines() + except OSError as exc: + raise DiffError(str(exc)) + invocation = [args.clang_format_executable, file] + + # Use of utf-8 to decode the process output. + # + # Hopefully, this is the correct thing to do. + # + # It's done due to the following assumptions (which may be incorrect): + # - clang-format will returns the bytes read from the files as-is, + # without conversion, and it is already assumed that the files use utf-8. + # - if the diagnostics were internationalized, they would use utf-8: + # > Adding Translations to Clang + # > + # > Not possible yet! + # > Diagnostic strings should be written in UTF-8, + # > the client can translate to the relevant code page if needed. + # > Each translation completely replaces the format string + # > for the diagnostic. + # > -- http://clang.llvm.org/docs/InternalsManual.html#internals-diag-translation + + try: + proc = subprocess.Popen( + invocation, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + universal_newlines=True, + encoding="utf-8", + ) + except OSError as exc: + raise DiffError( + f"Command '{subprocess.list2cmdline(invocation)}' failed to start: {exc}" + ) + proc_stdout = proc.stdout + proc_stderr = proc.stderr + + # hopefully the stderr pipe won't get full and block the process + outs = list(proc_stdout.readlines()) + errs = list(proc_stderr.readlines()) + proc.wait() + if proc.returncode: + raise DiffError( + "Command '{}' returned non-zero exit status {}".format( + subprocess.list2cmdline(invocation), proc.returncode + ), + errs, + ) + return make_diff(file, original, outs), errs + + +def bold_red(s): + return "\x1b[1m\x1b[31m" + s + "\x1b[0m" + + +def colorize(diff_lines): + def bold(s): + return "\x1b[1m" + s + "\x1b[0m" + + def cyan(s): + return "\x1b[36m" + s + "\x1b[0m" + + def green(s): + return "\x1b[32m" + s + "\x1b[0m" + + def red(s): + return "\x1b[31m" + s + "\x1b[0m" + + for line in diff_lines: + if line[:4] in ["--- ", "+++ "]: + yield bold(line) + elif line.startswith("@@ "): + yield cyan(line) + elif line.startswith("+"): + yield green(line) + elif line.startswith("-"): + yield red(line) + else: + yield line + + +def print_diff(diff_lines, use_color): + if use_color: + diff_lines = colorize(diff_lines) + sys.stdout.writelines(diff_lines) + + +def print_trouble(prog, message, use_colors): + error_text = "error:" + if use_colors: + error_text = bold_red(error_text) + print(f"{prog}: {error_text} {message}", file=sys.stderr) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + "--clang-format-executable", + metavar="EXECUTABLE", + help="path to the clang-format executable", + default="clang-format", + ) + parser.add_argument( + "--extensions", + help=f"comma separated list of file extensions (default: {DEFAULT_EXTENSIONS})", + default=DEFAULT_EXTENSIONS, + ) + parser.add_argument( + "-r", + "--recursive", + action="store_true", + help="run recursively over directories", + ) + parser.add_argument("files", metavar="file", nargs="+") + parser.add_argument("-q", "--quiet", action="store_true") + parser.add_argument( + "-j", + metavar="N", + type=int, + default=0, + help="run N clang-format jobs in parallel (default number of cpus + 1)", + ) + parser.add_argument( + "--color", + default="auto", + choices=["auto", "always", "never"], + help="show colored diff (default: auto)", + ) + parser.add_argument( + "-e", + "--exclude", + metavar="PATTERN", + action="append", + default=[], + help="exclude paths matching the given glob-like pattern(s) from recursive search", + ) + + args = parser.parse_args() + + # use default signal handling, like diff return SIGINT value on ^C + # https://bugs.python.org/issue14229#msg156446 + signal.signal(signal.SIGINT, signal.SIG_DFL) + try: + signal.SIGPIPE + except AttributeError: + # compatibility, SIGPIPE does not exist on Windows + pass + else: + signal.signal(signal.SIGPIPE, signal.SIG_DFL) + + colored_stdout = False + colored_stderr = False + if args.color == "always": + colored_stdout = True + colored_stderr = True + elif args.color == "auto": + colored_stdout = sys.stdout.isatty() + colored_stderr = sys.stderr.isatty() + + version_invocation = [args.clang_format_executable, "--version"] + try: + subprocess.check_call(version_invocation, stdout=DEVNULL) + except subprocess.CalledProcessError as e: + print_trouble(parser.prog, str(e), use_colors=colored_stderr) + return ExitStatus.TROUBLE + except OSError as e: + print_trouble( + parser.prog, + f"Command '{subprocess.list2cmdline(version_invocation)}' failed to start: {e}", + use_colors=colored_stderr, + ) + return ExitStatus.TROUBLE + + retcode = ExitStatus.SUCCESS + files = list_files( + args.files, + recursive=args.recursive, + exclude=args.exclude, + extensions=args.extensions.split(","), + ) + + if not files: + return + + njobs = args.j + if njobs == 0: + njobs = multiprocessing.cpu_count() + 1 + njobs = min(len(files), njobs) + + if njobs == 1: + # execute directly instead of in a pool, + # less overhead, simpler stacktraces + it = (run_clang_format_diff_wrapper(args, file) for file in files) + pool = None + else: + pool = multiprocessing.Pool(njobs) + it = pool.imap_unordered(partial(run_clang_format_diff_wrapper, args), files) + while True: + try: + outs, errs = next(it) + except StopIteration: + break + except DiffError as e: + print_trouble(parser.prog, str(e), use_colors=colored_stderr) + retcode = ExitStatus.TROUBLE + sys.stderr.writelines(e.errs) + except UnexpectedError as e: + print_trouble(parser.prog, str(e), use_colors=colored_stderr) + sys.stderr.write(e.formatted_traceback) + retcode = ExitStatus.TROUBLE + # stop at the first unexpected error, + # something could be very wrong, + # don't process all files unnecessarily + if pool: + pool.terminate() + break + else: + sys.stderr.writelines(errs) + if outs == []: + continue + if not args.quiet: + print_diff(outs, use_color=colored_stdout) + if retcode == ExitStatus.SUCCESS: + retcode = ExitStatus.DIFF + return retcode + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.github/unittest/linux_libs/scripts_smacv2/run_test.sh b/.github/unittest/linux_libs/scripts_smacv2/run_test.sh new file mode 100755 index 00000000000..65fd7462df3 --- /dev/null +++ b/.github/unittest/linux_libs/scripts_smacv2/run_test.sh @@ -0,0 +1,32 @@ +#!/usr/bin/env bash + +set -e + +eval "$(./conda/bin/conda shell.bash hook)" +conda activate ./env +apt-get update && apt-get install -y git wget + + +export PYTORCH_TEST_WITH_SLOW='1' +python -m torch.utils.collect_env +# Avoid error: "fatal: unsafe repository" +git config --global --add safe.directory '*' + +root_dir="$(git rev-parse --show-toplevel)" +env_dir="${root_dir}/env" +lib_dir="${env_dir}/lib" +export SC2PATH="${root_dir}/StarCraftII" +echo 'SC2PATH is set to ' "$SC2PATH" + +# solves ImportError: /lib64/libstdc++.so.6: version `GLIBCXX_3.4.21' not found +export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$lib_dir +export MKL_THREADING_LAYER=GNU +# more logging +export MAGNUM_LOG=verbose MAGNUM_GPU_VALIDATION=ON + +# this workflow only tests the libs +python -c "import smacv2" + +python .github/unittest/helpers/coverage_run_parallel.py -m pytest test/test_libs.py --instafail -v --durations 200 --capture no -k TestSmacv2 --error-for-skips +coverage combine +coverage xml -i diff --git a/.github/unittest/linux_libs/scripts_smacv2/setup_env.sh b/.github/unittest/linux_libs/scripts_smacv2/setup_env.sh new file mode 100755 index 00000000000..04080cc8932 --- /dev/null +++ b/.github/unittest/linux_libs/scripts_smacv2/setup_env.sh @@ -0,0 +1,65 @@ +#!/usr/bin/env bash + +# This script is for setting up environment in which unit test is ran. +# To speed up the CI time, the resulting environment is cached. +# +# Do not install PyTorch and torchvision here, otherwise they also get cached. + +set -e + +this_dir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )" +# Avoid error: "fatal: unsafe repository" +git config --global --add safe.directory '*' +root_dir="$(git rev-parse --show-toplevel)" +conda_dir="${root_dir}/conda" +env_dir="${root_dir}/env" + +cd "${root_dir}" + +case "$(uname -s)" in + Darwin*) os=MacOSX;; + *) os=Linux +esac + +# 1. Install conda at ./conda +if [ ! -d "${conda_dir}" ]; then + printf "* Installing conda\n" + wget -O miniconda.sh "http://repo.continuum.io/miniconda/Miniconda3-latest-${os}-x86_64.sh" + bash ./miniconda.sh -b -f -p "${conda_dir}" +fi +eval "$(${conda_dir}/bin/conda shell.bash hook)" + +# 2. Create test environment at ./env +printf "python: ${PYTHON_VERSION}\n" +if [ ! -d "${env_dir}" ]; then + printf "* Creating a test environment\n" + conda create --prefix "${env_dir}" -y python="$PYTHON_VERSION" +fi +conda activate "${env_dir}" + +# 4. Install Conda dependencies +printf "* Installing dependencies (except PyTorch)\n" +echo " - python=${PYTHON_VERSION}" >> "${this_dir}/environment.yml" +cat "${this_dir}/environment.yml" + +pip install pip --upgrade + +conda env update --file "${this_dir}/environment.yml" --prune + +# 5. Install StarCraft 2 with SMACv2 maps +starcraft_path="${root_dir}/StarCraftII" +map_dir="${starcraft_path}/Maps" +printf "* Installing StarCraft 2 and SMACv2 maps into ${starcraft_path}\n" +cd "${root_dir}" +# TODO: discuss how we can cache it to avoid downloading ~4 GB on each run. +# e.g adding this into the image learn( which one is used and how it is maintained) +wget https://blzdistsc2-a.akamaihd.net/Linux/SC2.4.10.zip +# The archive contains StarCraftII folder. Password comes from the documentation. +unzip -qo -P iagreetotheeula SC2.4.10.zip +mkdir -p "${map_dir}" +# Install Maps +wget https://github.com/oxwhirl/smacv2/releases/download/maps/SMAC_Maps.zip +unzip SMAC_Maps.zip +mkdir "${map_dir}/SMAC_Maps" +mv *.SC2Map "${map_dir}/SMAC_Maps" +printf "StarCraft II and SMAC are installed." diff --git a/.github/workflows/test-linux-smacv2.yml b/.github/workflows/test-linux-smacv2.yml new file mode 100644 index 00000000000..159c93fb1a1 --- /dev/null +++ b/.github/workflows/test-linux-smacv2.yml @@ -0,0 +1,41 @@ +name: SMACv2 Tests on Linux + +on: + pull_request: + push: + branches: + - nightly + - main + - release/* + workflow_dispatch: + +concurrency: + # Documentation suggests ${{ github.head_ref }}, but that's only available on pull_request/pull_request_target triggers, so using ${{ github.ref }}. + # On master, we want all builds to complete even if merging happens faster to make it easier to discover at which point something broke. + group: ${{ github.workflow }}-${{ github.ref == 'refs/heads/main' && format('ci-master-{0}', github.sha) || format('ci-{0}', github.ref) }} + cancel-in-progress: true + +jobs: + unittests: + if: ${{ github.event_name == 'push' || contains(github.event.pull_request.labels.*.name, 'Environments') }} + uses: pytorch/test-infra/.github/workflows/linux_job.yml@main + with: + repository: pytorch/rl + runner: "linux.g5.4xlarge.nvidia.gpu" + gpu-arch-type: cuda + gpu-arch-version: "11.7" + timeout: 120 + script: | + set -euo pipefail + export PYTHON_VERSION="3.9" + export CU_VERSION="11.7" + export TAR_OPTIONS="--no-same-owner" + export UPLOAD_CHANNEL="nightly" + export TF_CPP_MIN_LOG_LEVEL=0 + + nvidia-smi + + bash .github/unittest/linux_libs/scripts_smacv2/setup_env.sh + bash .github/unittest/linux_libs/scripts_smacv2/install.sh + bash .github/unittest/linux_libs/scripts_smacv2/run_test.sh + bash .github/unittest/linux_libs/scripts_smacv2/post_process.sh diff --git a/docs/source/reference/envs.rst b/docs/source/reference/envs.rst index 6527418ea75..26b5cb00e6b 100644 --- a/docs/source/reference/envs.rst +++ b/docs/source/reference/envs.rst @@ -500,6 +500,54 @@ to be able to create this other composition: VIPRewardTransform VIPTransform +Environments with masked actions +-------------------------------- + +In some environments with discrete actions, the actions available to the agent might change throughout execution. +In such cases the environments will output an action mask (under the ``"action_mask"`` key by default). +This mask needs to be used to filter out unavailable actions for that step. + +If you are using a custom policy you can pass this mask to your probability distribution like so: + +.. code-block:: + :caption: Categorical policy with action mask + + >>> from tensordict.nn import TensorDictModule, ProbabilisticTensorDictModule, TensorDictSequential + >>> import torch.nn as nn + >>> from torchrl.modules import MaskedCategorical + >>> module = TensorDictModule( + >>> nn.Linear(in_feats, out_feats), + >>> in_keys=["observation"], + >>> out_keys=["logits"], + >>> ) + >>> dist = ProbabilisticTensorDictModule( + >>> in_keys={"logits": "logits", "mask": "action_mask"}, + >>> out_keys=["action"], + >>> distribution_class=MaskedCategorical, + >>> ) + >>> actor = TensorDictSequential(module, dist) + +If you want to use a default policy, you will need to wrap your environment in the :class:`~torchrl.envs.transforms.ActionMask` +transform. This transform can take care of updating the action mask in the action spec in order for the default policy +to always know what the latest available actions are. You can do this like so: + +.. code-block:: + :caption: How to use the action mask transform + + >>> from tensordict.nn import TensorDictModule, ProbabilisticTensorDictModule, TensorDictSequential + >>> import torch.nn as nn + >>> from torchrl.envs.transforms import TransformedEnv, ActionMask + >>> env = TransformedEnv( + >>> your_base_env + >>> ActionMask(action_key="action", mask_key="action_mask"), + >>> ) + +.. note:: + In case you are using a parallel environment it is important to add the transform to the parallel enviornment itself + and not to its sub-environments. + + + Recorders --------- @@ -639,5 +687,7 @@ the following function will return ``1`` when queried: openml.OpenMLEnv pettingzoo.PettingZooEnv pettingzoo.PettingZooWrapper + smacv2.SMACv2Env + smacv2.SMACv2Wrapper vmas.VmasEnv vmas.VmasWrapper diff --git a/test/test_libs.py b/test/test_libs.py index 1d6b341b710..b17c84de455 100644 --- a/test/test_libs.py +++ b/test/test_libs.py @@ -4,6 +4,9 @@ # LICENSE file in the root directory of this source tree. import importlib +from torchrl.envs.transforms import ActionMask, TransformedEnv +from torchrl.modules import MaskedCategorical + _has_isaac = importlib.util.find_spec("isaacgym") is not None if _has_isaac: @@ -35,6 +38,11 @@ ) from packaging import version from tensordict import LazyStackedTensorDict +from tensordict.nn import ( + ProbabilisticTensorDictModule, + TensorDictModule, + TensorDictSequential, +) from tensordict.tensordict import assert_allclose_td, TensorDict from torch import nn from torchrl._utils import implement_for @@ -76,6 +84,7 @@ _has_sklearn = importlib.util.find_spec("sklearn") is not None +from torchrl.envs.libs.smacv2 import _has_smacv2, SMACv2Env if _has_gym: try: @@ -1878,6 +1887,87 @@ def test_robohive(self, envname, from_pixels): check_env_specs(env) +@pytest.mark.skipif(not _has_smacv2, reason="SMACv2 not found") +class TestSmacv2: + def test_env_procedural(self): + distribution_config = { + "n_units": 5, + "n_enemies": 6, + "team_gen": { + "dist_type": "weighted_teams", + "unit_types": ["marine", "marauder", "medivac"], + "exception_unit_types": ["medivac"], + "weights": [0.5, 0.2, 0.3], + "observe": True, + }, + "start_positions": { + "dist_type": "surrounded_and_reflect", + "p": 0.5, + "n_enemies": 5, + "map_x": 32, + "map_y": 32, + }, + } + env = SMACv2Env( + map_name="10gen_terran", + capability_config=distribution_config, + seed=0, + ) + check_env_specs(env, seed=None) + env.close() + + @pytest.mark.parametrize("categorical_actions", [True, False]) + @pytest.mark.parametrize("map", ["MMM2", "3s_vs_5z"]) + def test_env(self, map: str, categorical_actions): + env = SMACv2Env( + map_name=map, + categorical_actions=categorical_actions, + seed=0, + ) + check_env_specs(env, seed=None) + env.close() + + def test_parallel_env(self): + env = TransformedEnv( + ParallelEnv( + num_workers=2, + create_env_fn=lambda: SMACv2Env( + map_name="3s_vs_5z", + seed=0, + ), + ), + ActionMask( + action_key=("agents", "action"), mask_key=("agents", "action_mask") + ), + ) + check_env_specs(env, seed=None) + env.close() + + def test_collector(self): + env = SMACv2Env(map_name="MMM2", seed=0, categorical_actions=True) + in_feats = env.observation_spec["agents", "observation"].shape[-1] + out_feats = env.action_spec.space.n + + module = TensorDictModule( + nn.Linear(in_feats, out_feats), + in_keys=[("agents", "observation")], + out_keys=[("agents", "logits")], + ) + prob = ProbabilisticTensorDictModule( + in_keys={"logits": ("agents", "logits"), "mask": ("agents", "action_mask")}, + out_keys=[("agents", "action")], + distribution_class=MaskedCategorical, + ) + actor = TensorDictSequential(module, prob) + + collector = SyncDataCollector( + env, policy=actor, frames_per_batch=20, total_frames=40 + ) + for _ in collector: + break + collector.shutdown() + + if __name__ == "__main__": args, unknown = argparse.ArgumentParser().parse_known_args() pytest.main([__file__, "--capture", "no", "--exitfirst"] + unknown) diff --git a/torchrl/envs/libs/smacv2.py b/torchrl/envs/libs/smacv2.py new file mode 100644 index 00000000000..0c0bda35d28 --- /dev/null +++ b/torchrl/envs/libs/smacv2.py @@ -0,0 +1,633 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. +import importlib +import re + +from typing import Dict, Optional + +import torch +from tensordict import TensorDict, TensorDictBase + +from torchrl.data import ( + BoundedTensorSpec, + CompositeSpec, + DiscreteTensorSpec, + OneHotDiscreteTensorSpec, + UnboundedContinuousTensorSpec, +) +from torchrl.envs.common import _EnvWrapper + +from torchrl.envs.utils import ACTION_MASK_ERROR + + +_has_smacv2 = importlib.util.find_spec("smacv2") is not None + + +def _get_envs(): + if not _has_smacv2: + return [] + from smacv2.env.starcraft2.maps import smac_maps + + return list(smac_maps.get_smac_map_registry().keys()) + + +class SMACv2Wrapper(_EnvWrapper): + """SMACv2 (StarCraft Multi-Agent Challenge v2) environment wrapper. + + To install the environment follow the following `guide `__. + + Examples: + >>> from torchrl.envs.libs.smacv2 import SMACv2Wrapper + >>> import smacv2 + >>> print(SMACv2Wrapper.available_envs) + ['10gen_terran', '10gen_zerg', '10gen_protoss', '3m', '8m', '25m', '5m_vs_6m', '8m_vs_9m', '10m_vs_11m', + '27m_vs_30m', 'MMM', 'MMM2', '2s3z', '3s5z', '3s5z_vs_3s6z', '3s_vs_3z', '3s_vs_4z', '3s_vs_5z', '1c3s5z', + '2m_vs_1z', 'corridor', '6h_vs_8z', '2s_vs_1sc', 'so_many_baneling', 'bane_vs_bane', '2c_vs_64zg'] + >>> # You can use old SMAC maps + >>> env = SMACv2Wrapper(smacv2.env.StarCraft2Env(map_name="MMM2"), categorical_actions=False) + >>> print(env.rollout(5)) + TensorDict( + fields={ + agents: TensorDict( + fields={ + action: Tensor(shape=torch.Size([5, 10, 18]), device=cpu, dtype=torch.int64, is_shared=False), + action_mask: Tensor(shape=torch.Size([5, 10, 18]), device=cpu, dtype=torch.bool, is_shared=False), + observation: Tensor(shape=torch.Size([5, 10, 176]), device=cpu, dtype=torch.float32, is_shared=False)}, + batch_size=torch.Size([5, 10]), + device=cpu, + is_shared=False), + done: Tensor(shape=torch.Size([5, 1]), device=cpu, dtype=torch.bool, is_shared=False), + info: TensorDict( + fields={ + battle_won: Tensor(shape=torch.Size([5]), device=cpu, dtype=torch.bool, is_shared=False), + dead_allies: Tensor(shape=torch.Size([5]), device=cpu, dtype=torch.int64, is_shared=False), + dead_enemies: Tensor(shape=torch.Size([5]), device=cpu, dtype=torch.int64, is_shared=False), + episode_limit: Tensor(shape=torch.Size([5]), device=cpu, dtype=torch.bool, is_shared=False)}, + batch_size=torch.Size([5]), + device=cpu, + is_shared=False), + next: TensorDict( + fields={ + agents: TensorDict( + fields={ + action_mask: Tensor(shape=torch.Size([5, 10, 18]), device=cpu, dtype=torch.bool, is_shared=False), + observation: Tensor(shape=torch.Size([5, 10, 176]), device=cpu, dtype=torch.float32, is_shared=False)}, + batch_size=torch.Size([5, 10]), + device=cpu, + is_shared=False), + done: Tensor(shape=torch.Size([5, 1]), device=cpu, dtype=torch.bool, is_shared=False), + info: TensorDict( + fields={ + battle_won: Tensor(shape=torch.Size([5]), device=cpu, dtype=torch.bool, is_shared=False), + dead_allies: Tensor(shape=torch.Size([5]), device=cpu, dtype=torch.int64, is_shared=False), + dead_enemies: Tensor(shape=torch.Size([5]), device=cpu, dtype=torch.int64, is_shared=False), + episode_limit: Tensor(shape=torch.Size([5]), device=cpu, dtype=torch.bool, is_shared=False)}, + batch_size=torch.Size([5]), + device=cpu, + is_shared=False), + reward: Tensor(shape=torch.Size([5, 1]), device=cpu, dtype=torch.float32, is_shared=False), + state: Tensor(shape=torch.Size([5, 322]), device=cpu, dtype=torch.float32, is_shared=False)}, + batch_size=torch.Size([5]), + device=cpu, + is_shared=False), + state: Tensor(shape=torch.Size([5, 322]), device=cpu, dtype=torch.float32, is_shared=False)}, + batch_size=torch.Size([5]), + device=cpu, + is_shared=False) + >>> # Or the new features for procedural generation + >>> distribution_config = { + ... "n_units": 5, + ... "n_enemies": 6, + ... "team_gen": { + ... "dist_type": "weighted_teams", + ... "unit_types": ["marine", "marauder", "medivac"], + ... "exception_unit_types": ["medivac"], + ... "weights": [0.5, 0.2, 0.3], + ... "observe": True, + ... }, + ... "start_positions": { + ... "dist_type": "surrounded_and_reflect", + ... "p": 0.5, + ... "n_enemies": 5, + ... "map_x": 32, + ... "map_y": 32, + ... }, + ... } + >>> env = SMACv2Wrapper( + ... smacv2.env.StarCraft2Env( + ... map_name="10gen_terran", + ... capability_config=distribution_config, + ... ) + ... ) + >>> print(env.rollout(4)) + TensorDict( + fields={ + agents: TensorDict( + fields={ + action: Tensor(shape=torch.Size([4, 5, 12]), device=cpu, dtype=torch.int64, is_shared=False), + action_mask: Tensor(shape=torch.Size([4, 5, 12]), device=cpu, dtype=torch.bool, is_shared=False), + observation: Tensor(shape=torch.Size([4, 5, 88]), device=cpu, dtype=torch.float32, is_shared=False)}, + batch_size=torch.Size([4, 5]), + device=cpu, + is_shared=False), + done: Tensor(shape=torch.Size([4, 1]), device=cpu, dtype=torch.bool, is_shared=False), + info: TensorDict( + fields={ + battle_won: Tensor(shape=torch.Size([4]), device=cpu, dtype=torch.bool, is_shared=False), + dead_allies: Tensor(shape=torch.Size([4]), device=cpu, dtype=torch.int64, is_shared=False), + dead_enemies: Tensor(shape=torch.Size([4]), device=cpu, dtype=torch.int64, is_shared=False), + episode_limit: Tensor(shape=torch.Size([4]), device=cpu, dtype=torch.bool, is_shared=False)}, + batch_size=torch.Size([4]), + device=cpu, + is_shared=False), + next: TensorDict( + fields={ + agents: TensorDict( + fields={ + action_mask: Tensor(shape=torch.Size([4, 5, 12]), device=cpu, dtype=torch.bool, is_shared=False), + observation: Tensor(shape=torch.Size([4, 5, 88]), device=cpu, dtype=torch.float32, is_shared=False)}, + batch_size=torch.Size([4, 5]), + device=cpu, + is_shared=False), + done: Tensor(shape=torch.Size([4, 1]), device=cpu, dtype=torch.bool, is_shared=False), + info: TensorDict( + fields={ + battle_won: Tensor(shape=torch.Size([4]), device=cpu, dtype=torch.bool, is_shared=False), + dead_allies: Tensor(shape=torch.Size([4]), device=cpu, dtype=torch.int64, is_shared=False), + dead_enemies: Tensor(shape=torch.Size([4]), device=cpu, dtype=torch.int64, is_shared=False), + episode_limit: Tensor(shape=torch.Size([4]), device=cpu, dtype=torch.bool, is_shared=False)}, + batch_size=torch.Size([4]), + device=cpu, + is_shared=False), + reward: Tensor(shape=torch.Size([4, 1]), device=cpu, dtype=torch.float32, is_shared=False), + state: Tensor(shape=torch.Size([4, 131]), device=cpu, dtype=torch.float32, is_shared=False)}, + batch_size=torch.Size([4]), + device=cpu, + is_shared=False), + state: Tensor(shape=torch.Size([4, 131]), device=cpu, dtype=torch.float32, is_shared=False)}, + batch_size=torch.Size([4]), + device=cpu, + is_shared=False) + """ + + git_url = "https://github.com/oxwhirl/smacv2" + libname = "smacv2" + available_envs = _get_envs() + + def __init__( + self, + env: "smacv2.env.StarCraft2Env" = None, # noqa: F821 + categorical_actions: bool = True, + **kwargs, + ): + if env is not None: + kwargs["env"] = env + self.categorical_actions = categorical_actions + + super().__init__(**kwargs) + + @property + def lib(self): + import smacv2 + + return smacv2 + + def _check_kwargs(self, kwargs: Dict): + import smacv2 + + if "env" not in kwargs: + raise TypeError("Could not find environment key 'env' in kwargs.") + env = kwargs["env"] + if not isinstance(env, smacv2.env.StarCraft2Env): + raise TypeError("env is not of type 'smacv2.env.StarCraft2Env'.") + + def _build_env( + self, + env: "smacv2.env.StarCraft2Env", # noqa: F821 + ): + if len(self.batch_size): + raise RuntimeError( + f"SMACv2 does not support custom batch_size {self.batch_size}." + ) + + return env + + def _make_specs(self, env: "smacv2.env.StarCraft2Env") -> None: # noqa: F821 + self.group_map = {"agents": [str(i) for i in range(self.n_agents)]} + self.reward_spec = UnboundedContinuousTensorSpec( + shape=torch.Size((1,)), + device=self.device, + ) + self.done_spec = DiscreteTensorSpec( + n=2, + shape=torch.Size((1,)), + dtype=torch.bool, + device=self.device, + ) + self.action_spec = self._make_action_spec() + self.observation_spec = self._make_observation_spec() + + def _init_env(self) -> None: + self._env.reset() + self._update_action_mask() + + def _make_action_spec(self) -> CompositeSpec: + if self.categorical_actions: + action_spec = DiscreteTensorSpec( + self.n_actions, + shape=torch.Size((self.n_agents,)), + device=self.device, + dtype=torch.long, + ) + else: + action_spec = OneHotDiscreteTensorSpec( + self.n_actions, + shape=torch.Size((self.n_agents, self.n_actions)), + device=self.device, + dtype=torch.long, + ) + spec = CompositeSpec( + { + "agents": CompositeSpec( + {"action": action_spec}, shape=torch.Size((self.n_agents,)) + ) + } + ) + return spec + + def _make_observation_spec(self) -> CompositeSpec: + obs_spec = BoundedTensorSpec( + minimum=-1.0, + maximum=1.0, + shape=torch.Size([self.n_agents, self.get_obs_size()]), + device=self.device, + dtype=torch.float32, + ) + info_spec = CompositeSpec( + { + "battle_won": DiscreteTensorSpec( + 2, dtype=torch.bool, device=self.device + ), + "episode_limit": DiscreteTensorSpec( + 2, dtype=torch.bool, device=self.device + ), + "dead_allies": BoundedTensorSpec( + minimum=0, + maximum=self.n_agents, + dtype=torch.long, + device=self.device, + shape=(), + ), + "dead_enemies": BoundedTensorSpec( + minimum=0, + maximum=self.n_enemies, + dtype=torch.long, + device=self.device, + shape=(), + ), + } + ) + mask_spec = DiscreteTensorSpec( + 2, + torch.Size([self.n_agents, self.n_actions]), + device=self.device, + dtype=torch.bool, + ) + spec = CompositeSpec( + { + "agents": CompositeSpec( + {"observation": obs_spec, "action_mask": mask_spec}, + shape=torch.Size((self.n_agents,)), + ), + "state": BoundedTensorSpec( + minimum=-1.0, + maximum=1.0, + shape=torch.Size((self.get_state_size(),)), + device=self.device, + dtype=torch.float32, + ), + "info": info_spec, + } + ) + return spec + + def _set_seed(self, seed: Optional[int]): + if seed is not None: + raise NotImplementedError( + "Seed cannot be changed once environment was created." + ) + + def get_obs(self): + obs = self._env.get_obs() + return self._to_tensor(obs) + + def get_state(self): + state = self._env.get_state() + return self._to_tensor(state) + + def _to_tensor(self, value): + return torch.tensor(value, device=self.device, dtype=torch.float32) + + def _reset( + self, tensordict: Optional[TensorDictBase] = None, **kwargs + ) -> TensorDictBase: + + obs, state = self._env.reset() + + # collect outputs + obs = self._to_tensor(obs) + state = self._to_tensor(state) + info = self.observation_spec["info"].zero() + + mask = self._update_action_mask() + + # build results + agents_td = TensorDict( + {"observation": obs, "action_mask": mask}, batch_size=(self.n_agents,) + ) + tensordict_out = TensorDict( + source={"agents": agents_td, "state": state, "info": info}, + batch_size=(), + device=self.device, + ) + + return tensordict_out + + def _step(self, tensordict: TensorDictBase) -> TensorDictBase: + # perform actions + action = tensordict.get(("agents", "action")) + action_np = self.action_spec.to_numpy(action) + + # Actions are validated by the environment. + try: + reward, done, info = self._env.step(action_np) + except AssertionError as err: + if re.match(r"Agent . cannot perform action .", str(err)): + raise ACTION_MASK_ERROR + else: + raise err + + # collect outputs + obs = self.get_obs() + state = self.get_state() + info = self.observation_spec["info"].encode(info) + if "episode_limit" not in info.keys(): + info["episode_limit"] = self.observation_spec["info"][ + "episode_limit" + ].zero() + + reward = torch.tensor( + reward, device=self.device, dtype=torch.float32 + ).unsqueeze(-1) + done = torch.tensor(done, device=self.device, dtype=torch.bool).unsqueeze(-1) + + mask = self._update_action_mask() + + # build results + agents_td = TensorDict( + {"observation": obs, "action_mask": mask}, batch_size=(self.n_agents,) + ) + + tensordict_out = TensorDict( + source={ + "agents": agents_td, + "state": state, + "info": info, + "reward": reward, + "done": done, + }, + batch_size=(), + device=self.device, + ) + + return tensordict_out + + def _update_action_mask(self): + mask = torch.tensor( + self.get_avail_actions(), dtype=torch.bool, device=self.device + ) + self.action_spec.update_mask(mask) + return mask + + def close(self): + # Closes StarCraft II + self._env.close() + + def get_agent_type(self, agent_index: int) -> str: + """Get the agent type string. + + Given the agent index, get its unit type name. + + Args: + agent_index (int): the index of the agent to get the type of + + """ + if agent_index < 0 or agent_index >= self.n_agents: + raise ValueError(f"Agent index out of range, {self.n_agents} available") + + agent_info = self.agents[agent_index] + if agent_info.unit_type == self.marine_id: + return "marine" + elif agent_info.unit_type == self.marauder_id: + return "marauder" + elif agent_info.unit_type == self.medivac_id: + return "medivac" + elif agent_info.unit_type == self.hydralisk_id: + return "hydralisk" + elif agent_info.unit_type == self.zergling_id: + return "zergling" + elif agent_info.unit_type == self.baneling_id: + return "baneling" + elif agent_info.unit_type == self.stalker_id: + return "stalker" + elif agent_info.unit_type == self.colossus_id: + return "colossus" + elif agent_info.unit_type == self.zealot_id: + return "zealot" + else: + raise AssertionError(f"Agent type {agent_info.unit_type} unidentified") + + +class SMACv2Env(SMACv2Wrapper): + """SMACv2 (StarCraft Multi-Agent Challenge v2) environment wrapper. + + To install the environment follow the following `guide `__. + + Examples: + >>> from torchrl.envs.libs.smacv2 import SMACv2Env + >>> print(SMACv2Env.available_envs) + ['10gen_terran', '10gen_zerg', '10gen_protoss', '3m', '8m', '25m', '5m_vs_6m', '8m_vs_9m', '10m_vs_11m', + '27m_vs_30m', 'MMM', 'MMM2', '2s3z', '3s5z', '3s5z_vs_3s6z', '3s_vs_3z', '3s_vs_4z', '3s_vs_5z', '1c3s5z', + '2m_vs_1z', 'corridor', '6h_vs_8z', '2s_vs_1sc', 'so_many_baneling', 'bane_vs_bane', '2c_vs_64zg'] + >>> # You can use old SMAC maps + >>> env = SMACv2Env(map_name="MMM2") + >>> print(env.rollout(5) + TensorDict( + fields={ + agents: TensorDict( + fields={ + action: Tensor(shape=torch.Size([5, 10, 18]), device=cpu, dtype=torch.int64, is_shared=False), + action_mask: Tensor(shape=torch.Size([5, 10, 18]), device=cpu, dtype=torch.bool, is_shared=False), + observation: Tensor(shape=torch.Size([5, 10, 176]), device=cpu, dtype=torch.float32, is_shared=False)}, + batch_size=torch.Size([5, 10]), + device=cpu, + is_shared=False), + done: Tensor(shape=torch.Size([5, 1]), device=cpu, dtype=torch.bool, is_shared=False), + info: TensorDict( + fields={ + battle_won: Tensor(shape=torch.Size([5]), device=cpu, dtype=torch.bool, is_shared=False), + dead_allies: Tensor(shape=torch.Size([5]), device=cpu, dtype=torch.int64, is_shared=False), + dead_enemies: Tensor(shape=torch.Size([5]), device=cpu, dtype=torch.int64, is_shared=False), + episode_limit: Tensor(shape=torch.Size([5]), device=cpu, dtype=torch.bool, is_shared=False)}, + batch_size=torch.Size([5]), + device=cpu, + is_shared=False), + next: TensorDict( + fields={ + agents: TensorDict( + fields={ + action_mask: Tensor(shape=torch.Size([5, 10, 18]), device=cpu, dtype=torch.bool, is_shared=False), + observation: Tensor(shape=torch.Size([5, 10, 176]), device=cpu, dtype=torch.float32, is_shared=False)}, + batch_size=torch.Size([5, 10]), + device=cpu, + is_shared=False), + done: Tensor(shape=torch.Size([5, 1]), device=cpu, dtype=torch.bool, is_shared=False), + info: TensorDict( + fields={ + battle_won: Tensor(shape=torch.Size([5]), device=cpu, dtype=torch.bool, is_shared=False), + dead_allies: Tensor(shape=torch.Size([5]), device=cpu, dtype=torch.int64, is_shared=False), + dead_enemies: Tensor(shape=torch.Size([5]), device=cpu, dtype=torch.int64, is_shared=False), + episode_limit: Tensor(shape=torch.Size([5]), device=cpu, dtype=torch.bool, is_shared=False)}, + batch_size=torch.Size([5]), + device=cpu, + is_shared=False), + reward: Tensor(shape=torch.Size([5, 1]), device=cpu, dtype=torch.float32, is_shared=False), + state: Tensor(shape=torch.Size([5, 322]), device=cpu, dtype=torch.float32, is_shared=False)}, + batch_size=torch.Size([5]), + device=cpu, + is_shared=False), + state: Tensor(shape=torch.Size([5, 322]), device=cpu, dtype=torch.float32, is_shared=False)}, + batch_size=torch.Size([5]), + device=cpu, + is_shared=False) + >>> # Or the new features for procedural generation + >>> distribution_config = { + ... "n_units": 5, + ... "n_enemies": 6, + ... "team_gen": { + ... "dist_type": "weighted_teams", + ... "unit_types": ["marine", "marauder", "medivac"], + ... "exception_unit_types": ["medivac"], + ... "weights": [0.5, 0.2, 0.3], + ... "observe": True, + ... }, + ... "start_positions": { + ... "dist_type": "surrounded_and_reflect", + ... "p": 0.5, + ... "n_enemies": 5, + ... "map_x": 32, + ... "map_y": 32, + ... }, + ... } + >>> env = SMACv2Env( + ... map_name="10gen_terran", + ... capability_config=distribution_config, + ... categorical_actions=False, + ... ) + >>> print(env.rollout(4)) + TensorDict( + fields={ + agents: TensorDict( + fields={ + action: Tensor(shape=torch.Size([4, 5, 12]), device=cpu, dtype=torch.int64, is_shared=False), + action_mask: Tensor(shape=torch.Size([4, 5, 12]), device=cpu, dtype=torch.bool, is_shared=False), + observation: Tensor(shape=torch.Size([4, 5, 88]), device=cpu, dtype=torch.float32, is_shared=False)}, + batch_size=torch.Size([4, 5]), + device=cpu, + is_shared=False), + done: Tensor(shape=torch.Size([4, 1]), device=cpu, dtype=torch.bool, is_shared=False), + info: TensorDict( + fields={ + battle_won: Tensor(shape=torch.Size([4]), device=cpu, dtype=torch.bool, is_shared=False), + dead_allies: Tensor(shape=torch.Size([4]), device=cpu, dtype=torch.int64, is_shared=False), + dead_enemies: Tensor(shape=torch.Size([4]), device=cpu, dtype=torch.int64, is_shared=False), + episode_limit: Tensor(shape=torch.Size([4]), device=cpu, dtype=torch.bool, is_shared=False)}, + batch_size=torch.Size([4]), + device=cpu, + is_shared=False), + next: TensorDict( + fields={ + agents: TensorDict( + fields={ + action_mask: Tensor(shape=torch.Size([4, 5, 12]), device=cpu, dtype=torch.bool, is_shared=False), + observation: Tensor(shape=torch.Size([4, 5, 88]), device=cpu, dtype=torch.float32, is_shared=False)}, + batch_size=torch.Size([4, 5]), + device=cpu, + is_shared=False), + done: Tensor(shape=torch.Size([4, 1]), device=cpu, dtype=torch.bool, is_shared=False), + info: TensorDict( + fields={ + battle_won: Tensor(shape=torch.Size([4]), device=cpu, dtype=torch.bool, is_shared=False), + dead_allies: Tensor(shape=torch.Size([4]), device=cpu, dtype=torch.int64, is_shared=False), + dead_enemies: Tensor(shape=torch.Size([4]), device=cpu, dtype=torch.int64, is_shared=False), + episode_limit: Tensor(shape=torch.Size([4]), device=cpu, dtype=torch.bool, is_shared=False)}, + batch_size=torch.Size([4]), + device=cpu, + is_shared=False), + reward: Tensor(shape=torch.Size([4, 1]), device=cpu, dtype=torch.float32, is_shared=False), + state: Tensor(shape=torch.Size([4, 131]), device=cpu, dtype=torch.float32, is_shared=False)}, + batch_size=torch.Size([4]), + device=cpu, + is_shared=False), + state: Tensor(shape=torch.Size([4, 131]), device=cpu, dtype=torch.float32, is_shared=False)}, + batch_size=torch.Size([4]), + device=cpu, + is_shared=False) + """ + + def __init__( + self, + map_name: str, + capability_config: Optional[Dict] = None, + seed: Optional[int] = None, + categorical_actions: bool = True, + **kwargs, + ): + if not _has_smacv2: + raise ImportError( + f"smacv2 python package was not found. Please install this dependency. " + f"More info: {self.git_url}." + ) + kwargs["map_name"] = map_name + kwargs["capability_config"] = capability_config + kwargs["seed"] = seed + kwargs["categorical_actions"] = categorical_actions + + super().__init__(**kwargs) + + def _check_kwargs(self, kwargs: Dict): + if "map_name" not in kwargs: + raise TypeError("Expected 'map_name' to be part of kwargs") + + def _build_env( + self, + map_name: str, + capability_config: Optional[Dict] = None, + seed: Optional[int] = None, + **kwargs, + ) -> "smacv2.env.StarCraft2Env": # noqa: F821 + import smacv2 + + if capability_config is not None: + env = smacv2.env.StarCraftCapabilityEnvWrapper( + capability_config=capability_config, + map_name=map_name, + seed=seed, + **kwargs, + ) + else: + env = smacv2.env.StarCraft2Env(map_name=map_name, seed=seed, **kwargs) + + return super()._build_env(env) diff --git a/torchrl/envs/utils.py b/torchrl/envs/utils.py index e4d41d14bfa..7f6d3341867 100644 --- a/torchrl/envs/utils.py +++ b/torchrl/envs/utils.py @@ -47,6 +47,15 @@ DONE_AFTER_RESET_ERROR = RuntimeError( "Env was done after reset on specified '_reset' dimensions. This is (currently) not allowed." ) +ACTION_MASK_ERROR = RuntimeError( + "An out-of-bounds actions has been provided to an env with an 'action_mask' output." + " If you are using a custom policy, make sure to take the action mask into account when computing the output." + " If you are using a default policy, please add the torchrl.envs.transforms.ActionMask transform to your environment." + "If you are using a ParallelEnv or another batched inventor, " + "make sure to add the transform to the ParallelEnv (and not to the sub-environments)." + " For more info on using action masks, see the docs at: " + "https://pytorch.org/rl/reference/envs.html#environments-with-masked-actions" +) def _convert_exploration_type(*, exploration_mode, exploration_type): @@ -419,8 +428,9 @@ def check_env_specs(env, return_contiguous=True, check_dtype=True, seed=0): of an experiment and as such should be kept out of training scripts. """ - torch.manual_seed(seed) - env.set_seed(seed) + if seed is not None: + torch.manual_seed(seed) + env.set_seed(seed) fake_tensordict = env.fake_tensordict() real_tensordict = env.rollout(3, return_contiguous=return_contiguous)