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,所以上面的代码应该按顺序执行操作,即一个接一个地执行操作。如果是这样,那么做上述事情的意义何在?

4

1 回答 1

1

你是对的,只有一个Simulator演员。该step方法在actor上被调用了四次。这将创建四个任务,actor 将依次执行这些任务。

如果这就是应用程序正在做的所有事情,那么创建常规 Python 对象并调用四次方法没有任何优势。但是,这种方法使您可以选择创建两个Simulator参与者并在它们上并行调用方法。例如,您可以编写以下内容。

# 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)

在此示例中,每个模拟器串行执行四个任务,但两个模拟器并行工作。您可以通过在方法中添加一条time.sleep(1)语句step并确定整个计算需要多长时间来说明这一点。

于 2019-01-21T07:36:27.323 回答