以下代码摘自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,所以上面的代码应该按顺序执行操作,即一个接一个地执行。如果是这样的话,这样做有什么意义呢?
发布于 2019-01-21 15:36:27
您是对的,只有一个Simulator参与者。step方法在执行元上被调用四次。这将创建四个任务,参与者将串行执行这些任务。
如果这就是应用程序所做的全部工作,那么与创建常规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)在此示例中,每个模拟器串行执行四个任务,但两个模拟器并行工作。您可以通过在step方法中放入一条time.sleep(1)语句并计时整个计算所需的时间来说明这一点。
https://stackoverflow.com/questions/54121047
复制相似问题