Repository: sail-sg/envpool (language: python)

Issue:
[Feature Request] Mujoco integration
https://github.com/openai/gym/tree/master/gym/envs/mujoco

Env List:

- [x] Ant-v4 (#74)
- [x] HalfCheetah-v4 (#75)
- [x] Hopper-v4 (#76)
- [x] Humanoid-v4 (#77)
- [x] HumanoidStandup-v4 (#78)
- [x] InvertedDoublePendulum-v4 (@Benjamin-eecs, #83)
- [x] InvertedPendulum-v4 (#79)
- [x] Pusher-v4 (#82)
- [x] Reacher-v4 (#81)
- [x] Swimmer-v4 (#80)
- [x] Walker2d-v4 (@Benjamin-eecs, #86)
- [x] add other options to align with gym (#93)

Road Map:

- [x] Get comfortable with current codebase, go through https://envpool.readthedocs.io/en/latest/pages/env.html and add a toy environment by yourself locally;
- [x] Download Mujoco and run on your local machine [1] [5], try with different env settings and see the actual behavior;
- [x] Go through their code [1] [2] (I think it's better to go through both openai and deepmind versions, but only use deepmind's solution as reference), understand their ctype APIs and what we can use to bind with EnvPool APIs [3];
- [x] Integrate only one game and let it work;
- [x] Add some unit tests (good to submit the first PR here);
- [x] Integrate other environments (submit another PR) and related tests.

Resources:
1. https://github.com/openai/mujoco-py 
2. https://github.com/deepmind/dm_control/tree/master/dm_control/mujoco 
3. https://github.com/deepmind/mujoco/blob/main/doc/programming.rst
4. It is quite similar with Atari games which we have already integrated: https://github.com/mgbellemare/Arcade-Learning-Environment
5. First install gym and mujoco, then run with
```python
import gym
env = gym.make("Ant-v3")
env.reset()
for _ in range(10):
  env.step(env.action_space.sample())
  env.render()
```
6. https://github.com/ikostrikov/gym_dmc/blob/master/compare.py a checker


Discussion / hints:

Fix patch:
diff --git a/docs/api/mujoco.rst b/docs/api/mujoco.rst
index d9e8bcea..3fe870da 100644
--- a/docs/api/mujoco.rst
+++ b/docs/api/mujoco.rst
@@ -12,8 +12,11 @@ You can set ``post_constraint`` to ``False`` to disable the bug fix with
 environments' standard approach.
 
 
-Ant-v4
-------
+Ant-v3/4
+--------
+
+`gym Ant-v3 source code
+<https://github.com/openai/gym/blob/master/gym/envs/mujoco/ant_v3.py>`_
 
 `gym Ant-v4 source code
 <https://github.com/openai/gym/blob/master/gym/envs/mujoco/ant_v4.py>`_
@@ -24,8 +27,11 @@ Ant-v4
 - Action space: ``(8)``, with range ``[-1, 1]``.
 
 
-HalfCheetah-v4
---------------
+HalfCheetah-v3/4
+----------------
+
+`gym HalfCheetah-v3 source code
+<https://github.com/openai/gym/blob/master/gym/envs/mujoco/half_cheetah_v3.py>`_
 
 `gym HalfCheetah-v4 source code
 <https://github.com/openai/gym/blob/master/gym/envs/mujoco/half_cheetah_v4.py>`_
@@ -35,8 +41,11 @@ HalfCheetah-v4
 - Action space: ``(6)``, with range ``[-1, 1]``.
 
 
-Hopper-v4
----------
+Hopper-v3/4
+-----------
+
+`gym Hopper-v3 source code
+<https://github.com/openai/gym/blob/master/gym/envs/mujoco/hopper_v3.py>`_
 
 `gym Hopper-v4 source code
 <https://github.com/openai/gym/blob/master/gym/envs/mujoco/hopper_v4.py>`_
@@ -46,12 +55,18 @@ Hopper-v4
 - Action space: ``(3)``, with range ``[-1, 1]``.
 
 
-Humanoid-v4, HumanoidStandup-v4
--------------------------------
+Humanoid-v3/4, HumanoidStandup-v2/4
+-----------------------------------
+
+`gym Humanoid-v3 source code
+<https://github.com/openai/gym/blob/master/gym/envs/mujoco/humanoid_v3.py>`_
 
 `gym Humanoid-v4 source code
 <https://github.com/openai/gym/blob/master/gym/envs/mujoco/humanoid_v4.py>`_
 
+`gym HumanoidStandup-v2 source code
+<https://github.com/openai/gym/blob/master/gym/envs/mujoco/humanoidstandup.py>`_
+
 `gym HumanoidStandup-v4 source code
 <https://github.com/openai/gym/blob/master/gym/envs/mujoco/humanoidstandup_v4.py>`_
 
@@ -63,8 +78,11 @@ Humanoid-v4, HumanoidStandup-v4
 - Action space: ``(17)``, with range ``[-0.4, 0.4]``.
 
 
-InvertedPendulum-v4
--------------------
+InvertedPendulum-v2/4
+---------------------
+
+`gym InvertedPendulum-v2 source code
+<https://github.com/openai/gym/blob/master/gym/envs/mujoco/inverted_pendulum.py>`_
 
 `gym InvertedPendulum-v4 source code
 <https://github.com/openai/gym/blob/master/gym/envs/mujoco/inverted_pendulum_v4.py>`_
@@ -72,3 +90,17 @@ InvertedPendulum-v4
 - Observation space: ``(4)``, first 2 elements for ``qpos``, next 2 elements
   for ``qvel``;
 - Action space: ``(1)``, with range ``[-3, 3]``.
+
+
+Swimmer-v3/4
+------------
+
+`gym Swimmer-v3 source code
+<https://github.com/openai/gym/blob/master/gym/envs/mujoco/swimmer_v3.py>`_
+
+`gym Swimmer-v4 source code
+<https://github.com/openai/gym/blob/master/gym/envs/mujoco/swimmer_v4.py>`_
+
+- Observation space: ``(8)``, first 3 elements for ``qpos[2:]``, next 5
+  elements for ``qvel``;
+- Action space: ``(2)``, with range ``[-1, 1]``.
diff --git a/envpool/mujoco/BUILD b/envpool/mujoco/BUILD
index 755e9efd..8dbc9c73 100644
--- a/envpool/mujoco/BUILD
+++ b/envpool/mujoco/BUILD
@@ -82,6 +82,15 @@ cc_library(
     ],
 )
 
+cc_library(
+    name = "swimmer",
+    hdrs = ["swimmer.h"],
+    deps = [
+        ":mujoco_env",
+        "//envpool/core:async_envpool",
+    ],
+)
+
 pybind_extension(
     name = "mujoco_envpool",
     srcs = ["mujoco_envpool.cc"],
@@ -92,6 +101,7 @@ pybind_extension(
         ":humanoid",
         ":humanoid_standup",
         ":inverted_pendulum",
+        ":swimmer",
         "//envpool/core:py_envpool",
     ],
 )
diff --git a/envpool/mujoco/__init__.py b/envpool/mujoco/__init__.py
index f7aa8a7c..db183a4a 100644
--- a/envpool/mujoco/__init__.py
+++ b/envpool/mujoco/__init__.py
@@ -28,6 +28,8 @@
   _HumanoidStandupEnvSpec,
   _InvertedPendulumEnvPool,
   _InvertedPendulumEnvSpec,
+  _SwimmerEnvPool,
+  _SwimmerEnvSpec,
 )
 
 AntEnvSpec, AntDMEnvPool, AntGymEnvPool = py_env(_AntEnvSpec, _AntEnvPool)
@@ -44,11 +46,21 @@
   _HumanoidEnvSpec, _HumanoidEnvPool
 )
 
-HumanoidStandupEnvSpec, HumanoidStandupDMEnvPool, HumanoidStandupGymEnvPool \
-  = py_env(_HumanoidStandupEnvSpec, _HumanoidStandupEnvPool)
+(
+  HumanoidStandupEnvSpec,
+  HumanoidStandupDMEnvPool,
+  HumanoidStandupGymEnvPool,
+) = py_env(_HumanoidStandupEnvSpec, _HumanoidStandupEnvPool)
 
-InvertedPendulumEnvSpec, InvertedPendulumDMEnvPool, InvertedPendulumGymEnvPool\
-  = py_env(_InvertedPendulumEnvSpec, _InvertedPendulumEnvPool)
+(
+  InvertedPendulumEnvSpec,
+  InvertedPendulumDMEnvPool,
+  InvertedPendulumGymEnvPool,
+) = py_env(_InvertedPendulumEnvSpec, _InvertedPendulumEnvPool)
+
+SwimmerEnvSpec, SwimmerDMEnvPool, SwimmerGymEnvPool = py_env(
+  _SwimmerEnvSpec, _SwimmerEnvPool
+)
 
 __all__ = [
   "AntEnvSpec",
@@ -69,4 +81,7 @@
   "InvertedPendulumEnvSpec",
   "InvertedPendulumDMEnvPool",
   "InvertedPendulumGymEnvPool",
+  "SwimmerEnvSpec",
+  "SwimmerDMEnvPool",
+  "SwimmerGymEnvPool",
 ]
diff --git a/envpool/mujoco/mujoco_envpool.cc b/envpool/mujoco/mujoco_envpool.cc
index 68736161..c364e980 100644
--- a/envpool/mujoco/mujoco_envpool.cc
+++ b/envpool/mujoco/mujoco_envpool.cc
@@ -19,6 +19,7 @@
 #include "envpool/mujoco/humanoid.h"
 #include "envpool/mujoco/humanoid_standup.h"
 #include "envpool/mujoco/inverted_pendulum.h"
+#include "envpool/mujoco/swimmer.h"
 
 typedef PyEnvSpec<mujoco::AntEnvSpec> AntEnvSpec;
 typedef PyEnvPool<mujoco::AntEnvPool> AntEnvPool;
@@ -38,6 +39,9 @@ typedef PyEnvPool<mujoco::HumanoidStandupEnvPool> HumanoidStandupEnvPool;
 typedef PyEnvSpec<mujoco::InvertedPendulumEnvSpec> InvertedPendulumEnvSpec;
 typedef PyEnvPool<mujoco::InvertedPendulumEnvPool> InvertedPendulumEnvPool;
 
+typedef PyEnvSpec<mujoco::SwimmerEnvSpec> SwimmerEnvSpec;
+typedef PyEnvPool<mujoco::SwimmerEnvPool> SwimmerEnvPool;
+
 PYBIND11_MODULE(mujoco_envpool, m) {
   REGISTER(m, AntEnvSpec, AntEnvPool)
   REGISTER(m, HalfCheetahEnvSpec, HalfCheetahEnvPool)
@@ -45,4 +49,5 @@ PYBIND11_MODULE(mujoco_envpool, m) {
   REGISTER(m, HumanoidEnvSpec, HumanoidEnvPool)
   REGISTER(m, HumanoidStandupEnvSpec, HumanoidStandupEnvPool)
   REGISTER(m, InvertedPendulumEnvSpec, InvertedPendulumEnvPool)
+  REGISTER(m, SwimmerEnvSpec, SwimmerEnvPool)
 }
diff --git a/envpool/mujoco/registration.py b/envpool/mujoco/registration.py
index 8c654210..5b1a9de6 100644
--- a/envpool/mujoco/registration.py
+++ b/envpool/mujoco/registration.py
@@ -19,66 +19,31 @@
 
 base_path = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
 
-register(
-  task_id="Ant-v4",
-  import_path="envpool.mujoco",
-  spec_cls="AntEnvSpec",
-  dm_cls="AntDMEnvPool",
-  gym_cls="AntGymEnvPool",
-  max_episode_steps=1000,
-  reward_threshold=6000.0,
-  base_path=base_path,
-)
-
-register(
-  task_id="HalfCheetah-v4",
-  import_path="envpool.mujoco",
-  spec_cls="HalfCheetahEnvSpec",
-  dm_cls="HalfCheetahDMEnvPool",
-  gym_cls="HalfCheetahGymEnvPool",
-  max_episode_steps=1000,
-  reward_threshold=4800.0,
-  base_path=base_path,
-)
-
-register(
-  task_id="Hopper-v4",
-  import_path="envpool.mujoco",
-  spec_cls="HopperEnvSpec",
-  dm_cls="HopperDMEnvPool",
-  gym_cls="HopperGymEnvPool",
-  max_episode_steps=1000,
-  reward_threshold=3800.0,
-  base_path=base_path,
-)
-
-register(
-  task_id="Humanoid-v4",
-  import_path="envpool.mujoco",
-  spec_cls="HumanoidEnvSpec",
-  dm_cls="HumanoidDMEnvPool",
-  gym_cls="HumanoidGymEnvPool",
-  max_episode_steps=1000,
-  base_path=base_path,
-)
-
-register(
-  task_id="HumanoidStandup-v4",
-  import_path="envpool.mujoco",
-  spec_cls="HumanoidStandupEnvSpec",
-  dm_cls="HumanoidStandupDMEnvPool",
-  gym_cls="HumanoidStandupGymEnvPool",
-  max_episode_steps=1000,
-  base_path=base_path,
-)
-
-register(
-  task_id="InvertedPendulum-v4",
-  import_path="envpool.mujoco",
-  spec_cls="InvertedPendulumEnvSpec",
-  dm_cls="InvertedPendulumDMEnvPool",
-  gym_cls="InvertedPendulumGymEnvPool",
-  max_episode_steps=1000,
-  reward_threshold=950.0,
-  base_path=base_path,
-)
+mujoco_envs = [
+  ("Ant", "v3", False),
+  ("Ant", "v4", True),
+  ("HalfCheetah", "v3", False),
+  ("HalfCheetah", "v4", True),
+  ("Hopper", "v3", False),
+  ("Hopper", "v4", True),
+  ("Humanoid", "v3", False),
+  ("Humanoid", "v4", True),
+  ("HumanoidStandup", "v2", False),
+  ("HumanoidStandup", "v4", True),
+  ("InvertedPendulum", "v2", False),
+  ("InvertedPendulum", "v4", True),
+  ("Swimmer", "v3", False),
+  ("Swimmer", "v4", True),
+]
+
+for task, version, post_constraint in mujoco_envs:
+  register(
+    task_id=f"{task}-{version}",
+    import_path="envpool.mujoco",
+    spec_cls=f"{task}EnvSpec",
+    dm_cls=f"{task}DMEnvPool",
+    gym_cls=f"{task}GymEnvPool",
+    max_episode_steps=1000,
+    base_path=base_path,
+    post_constraint=post_constraint,
+  )
diff --git a/envpool/mujoco/swimmer.h b/envpool/mujoco/swimmer.h
new file mode 100644
index 00000000..991ac618
--- /dev/null
+++ b/envpool/mujoco/swimmer.h
@@ -0,0 +1,158 @@
+/*
+ * Copyright 2022 Garena Online Private Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef ENVPOOL_MUJOCO_SWIMMER_H_
+#define ENVPOOL_MUJOCO_SWIMMER_H_
+
+#include <algorithm>
+#include <limits>
+#include <memory>
+#include <string>
+
+#include "envpool/core/async_envpool.h"
+#include "envpool/core/env.h"
+#include "envpool/mujoco/mujoco_env.h"
+
+namespace mujoco {
+
+class SwimmerEnvFns {
+ public:
+  static decltype(auto) DefaultConfig() {
+    return MakeDict(
+        "max_episode_steps"_.bind(1000), "reward_threshold"_.bind(360.0),
+        "frame_skip"_.bind(4), "post_constraint"_.bind(true),
+        "forward_reward_weight"_.bind(1.0), "ctrl_cost_weight"_.bind(1e-4),
+        "reset_noise_scale"_.bind(0.1));
+  }
+  template <typename Config>
+  static decltype(auto) StateSpec(const Config& conf) {
+    mjtNum inf = std::numeric_limits<mjtNum>::infinity();
+    return MakeDict("obs"_.bind(Spec<mjtNum>({8}, {-inf, inf})),
+                    "info:reward_fwd"_.bind(Spec<mjtNum>({-1})),
+                    "info:reward_ctrl"_.bind(Spec<mjtNum>({-1})),
+                    "info:x_position"_.bind(Spec<mjtNum>({-1})),
+                    "info:y_position"_.bind(Spec<mjtNum>({-1})),
+                    "info:distance_from_origin"_.bind(Spec<mjtNum>({-1})),
+                    "info:x_velocity"_.bind(Spec<mjtNum>({-1})),
+                    "info:y_velocity"_.bind(Spec<mjtNum>({-1})),
+                    // TODO(jiayi): remove these two lines for speed
+                    "info:qpos0"_.bind(Spec<mjtNum>({5})),
+                    "info:qvel0"_.bind(Spec<mjtNum>({5})));
+  }
+  template <typename Config>
+  static decltype(auto) ActionSpec(const Config& conf) {
+    return MakeDict("action"_.bind(Spec<mjtNum>({-1, 2}, {-1.0f, 1.0f})));
+  }
+};
+
+typedef class EnvSpec<SwimmerEnvFns> SwimmerEnvSpec;
+
+class SwimmerEnv : public Env<SwimmerEnvSpec>, public MujocoEnv {
+ protected:
+  int max_episode_steps_, elapsed_step_;
+  mjtNum ctrl_cost_weight_, forward_reward_weight_;
+  std::unique_ptr<mjtNum> qpos0_, qvel0_;  // for align check
+  std::uniform_real_distribution<> dist_;
+  bool done_;
+
+ public:
+  SwimmerEnv(const Spec& spec, int env_id)
+      : Env<SwimmerEnvSpec>(spec, env_id),
+        MujocoEnv(spec.config["base_path"_] + "/mujoco/assets/swimmer.xml",
+                  spec.config["frame_skip"_], spec.config["post_constraint"_]),
+        max_episode_steps_(spec.config["max_episode_steps"_]),
+        elapsed_step_(max_episode_steps_ + 1),
+        ctrl_cost_weight_(spec.config["ctrl_cost_weight"_]),
+        forward_reward_weight_(spec.config["forward_reward_weight"_]),
+        qpos0_(new mjtNum[model_->nq]),
+        qvel0_(new mjtNum[model_->nv]),
+        dist_(-spec.config["reset_noise_scale"_],
+              spec.config["reset_noise_scale"_]),
+        done_(true) {}
+
+  void MujocoResetModel() {
+    for (int i = 0; i < model_->nq; ++i) {
+      data_->qpos[i] = qpos0_.get()[i] = init_qpos_[i] + dist_(gen_);
+    }
+    for (int i = 0; i < model_->nv; ++i) {
+      data_->qvel[i] = qvel0_.get()[i] = init_qvel_[i] + dist_(gen_);
+    }
+  }
+
+  bool IsDone() override { return done_; }
+
+  void Reset() override {
+    done_ = false;
+    elapsed_step_ = 0;
+    MujocoReset();
+    WriteObs(0.0f, 0, 0, 0, 0, 0);
+  }
+
+  void Step(const Action& action) override {
+    // step
+    mjtNum* act = static_cast<mjtNum*>(action["action"_].data());
+    mjtNum x_before = data_->qpos[0], y_before = data_->qpos[1];
+    MujocoStep(act);
+    mjtNum x_after = data_->qpos[0], y_after = data_->qpos[1];
+
+    // ctrl_cost
+    mjtNum ctrl_cost = 0.0;
+    for (int i = 0; i < model_->nu; ++i) {
+      ctrl_cost += ctrl_cost_weight_ * act[i] * act[i];
+    }
+    // xv and yv
+    mjtNum dt = frame_skip_ * model_->opt.timestep;
+    mjtNum xv = (x_after - x_before) / dt;
+    mjtNum yv = (y_after - y_before) / dt;
+
+    // reward and done
+    float reward = xv * forward_reward_weight_ - ctrl_cost;
+    done_ = (++elapsed_step_ >= max_episode_steps_);
+    WriteObs(reward, xv, yv, ctrl_cost, x_after, y_after);
+  }
+
+ private:
+  void WriteObs(float reward, mjtNum xv, mjtNum yv, mjtNum ctrl_cost,
+                mjtNum x_after, mjtNum y_after) {
+    State state = Allocate();
+    state["reward"_] = reward;
+    // obs
+    mjtNum* obs = static_cast<mjtNum*>(state["obs"_].data());
+    for (int i = 2; i < model_->nq; ++i) {
+      *(obs++) = data_->qpos[i];
+    }
+    for (int i = 0; i < model_->nv; ++i) {
+      *(obs++) = data_->qvel[i];
+    }
+    // info
+    state["info:reward_fwd"_] = xv * forward_reward_weight_;
+    state["info:reward_ctrl"_] = -ctrl_cost;
+    state["info:x_position"_] = x_after;
+    state["info:y_position"_] = y_after;
+    state["info:distance_from_origin"_] =
+        std::sqrt(x_after * x_after + y_after * y_after);
+    state["info:x_velocity"_] = xv;
+    state["info:y_velocity"_] = yv;
+    state["info:qpos0"_].Assign(qpos0_.get(), model_->nq);
+    state["info:qvel0"_].Assign(qvel0_.get(), model_->nv);
+  }
+};
+
+typedef AsyncEnvPool<SwimmerEnv> SwimmerEnvPool;
+
+}  // namespace mujoco
+
+#endif  // ENVPOOL_MUJOCO_SWIMMER_H_


Test patch:
diff --git a/envpool/make_test.py b/envpool/make_test.py
index ad591db6..9bc4f93a 100644
--- a/envpool/make_test.py
+++ b/envpool/make_test.py
@@ -92,12 +92,20 @@ def test_make_toytext(self) -> None:
   def test_make_mujoco(self) -> None:
     self.check_step(
       [
+        "Ant-v3",
         "Ant-v4",
+        "HalfCheetah-v3",
         "HalfCheetah-v4",
+        "Hopper-v3",
         "Hopper-v4",
+        "Humanoid-v3",
         "Humanoid-v4",
+        "HumanoidStandup-v2",
         "HumanoidStandup-v4",
+        "InvertedPendulum-v2",
         "InvertedPendulum-v4",
+        "Swimmer-v3",
+        "Swimmer-v4",
       ]
     )
 
diff --git a/envpool/mujoco/mujoco_test.py b/envpool/mujoco/mujoco_test.py
index 8c788221..253475f4 100644
--- a/envpool/mujoco/mujoco_test.py
+++ b/envpool/mujoco/mujoco_test.py
@@ -34,6 +34,8 @@
   HumanoidStandupGymEnvPool,
   InvertedPendulumEnvSpec,
   InvertedPendulumGymEnvPool,
+  SwimmerEnvSpec,
+  SwimmerGymEnvPool,
 )
 
 
@@ -165,6 +167,13 @@ def test_inverted_pendulum(self) -> None:
       InvertedPendulumEnvSpec, InvertedPendulumGymEnvPool
     )
 
+  def test_swimmer(self) -> None:
+    env0 = mjc_mwe.SwimmerEnv()
+    env1 = SwimmerGymEnvPool(SwimmerEnvSpec(SwimmerEnvSpec.gen_config()))
+    self.run_space_check(env0, env1)
+    self.run_align_check(env0, env1, no_time_limit=True)
+    self.run_deterministic_check(SwimmerEnvSpec, SwimmerGymEnvPool)
+
 
 if __name__ == "__main__":
   absltest.main()