facebookresearch / nle

The NetHack Learning Environment
Other
939 stars 113 forks source link

Save and load game #372

Closed BartekCupial closed 2 months ago

BartekCupial commented 3 months ago

Summary

This PR adds the ability to save and load game state for environments. This allows games to be paused and resumed from the saved state.

This leverages how save scumming can be done, as described here https://nethackwiki.com/wiki/Save_scumming basically all the files from HACKDIR are copied to separate directory. Then if someone wants to load the game it's enough to copy back the files and create new nethack game. Unfortunately game has to be turned off and on to do so.

Disclaimer: I am not sure if my changes in _new_dl don't break something else, I don't really understand what is happening there and why.

Example usage (from added test)

    def test_save_and_load(self, env_name, rollout_len):
        """Tests rollout_len steps (or until termination) of random policy."""
        with tempfile.TemporaryDirectory() as gamesavedir:
            env = gym.make(env_name, gamesavedir=gamesavedir)

            obs = env.reset()
            for _ in range(rollout_len):
                action = env.action_space.sample()
                obs, _, done, _ = env.step(action)
                if done:
                    obs = env.reset()

            env.save()

            env = gym.make(env_name, gameloaddir=gamesavedir)
            obsload = env.reset()

            assert (obsload["blstats"] == obs["blstats"]).all()
            assert (obsload["glyphs"] == obs["glyphs"]).all()

Use cases

I used this to evaluate trained agents starting from different levels in the dungeon. For example Sokoban https://nethackwiki.com/wiki/Sokoban. I thought I could share my code and contribute back to the community.