在并行环境下运行OpenAI Gym环境

3
下面的代码摘自https://bair.berkeley.edu/blog/2018/01/09/ray/
import gym

@ray.remote
class Simulator(object):
    def __init__(self):
        self.env = gym.make("Pong-v0")
        self.env.reset()

    def step(self, action):
        return self.env.step(action)

# Create a simulator, this will start a remote process that will run
# all methods for this actor.
simulator = Simulator.remote()

observations = []
for _ in range(4):
    # Take action 0 in the simulator. This call does not block and
    # it returns a future.
    observations.append(simulator.step.remote(0))

当我阅读这段代码时,我感到非常困惑。这段代码真的并行运行吗?根据我的理解,只有一个env,所以上面的代码应该按顺序执行操作,即逐个执行操作。如果是这样,那么上面的代码有什么意义呢?

1个回答

1
你是正确的,有一个单独的模拟器角色。在角色上调用step方法四次。这将创建四个任务,角色将按顺序执行这些任务。
如果这是应用程序的全部内容,那么与创建常规Python对象并四次调用方法相比没有任何优势。但是,这种方法使您可以选择创建两个模拟器角色,并以并行方式调用它们的方法。例如,您可以编写以下内容。
# This assumes you've already called "import ray", "import gym",
# "ray.init()", and defined the Simulator class from the original
# post.

# Create two simulators.
simulator1 = Simulator.remote()
simulator2 = Simulator.remote()

# Step each of them four times.
observation_ids1 = []
observation_ids2 = []
for _ in range(4):
    observation_ids1.append(simulator1.step.remote(0))
    observation_ids2.append(simulator2.step.remote(0))

# Get the results.
observations1 = ray.get(observation_ids1)
observations2 = ray.get(observation_ids2)

在这个例子中,每个模拟器依次执行四个任务,但是两个模拟器是并行工作的。您可以通过在step方法中放置一个time.sleep(1)语句并计时整个计算需要多长时间来说明这一点。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接