python - Python:*args 和远程函数中的列表之间的区别
问题描述
定义一个列表
g = [1, 2, 3, 4]
版本 1
@ray.remote
def f(*g):
return np.mean(g, axis=0)
f_ids = [f.remote(*g) for _ in range(10)]
print(ray.get(f.remote(*f_ids)))
版本 2
@ray.remote
def f(g): # g is object ID list
return np.mean(g, axis=0)
f_ids = [f.remote(g) for _ in range(10)]
print(ray.get(f.remote(f_ids)))
第一个代码工作正常,但版本 2 不起作用。错误信息是
ray.get(f.remote(f_ids)) + 不支持的操作数类型:“common.ObjectID”和“common.ObjectID”
我想做第 2 版之类的事情的原因是我实际上想做以下事情
@remote
def f(g1, g2): # g1 and g2 are object ID lists
... # do something here
我不知道如何制作g1
and g2
as *g1
,*g2
所以我想出了第 2 版。为什么第 2 版不起作用?我该如何解决?
参考代码在这里 https://ray.readthedocs.io/en/latest/example-parameter-server.html#synchronous-parameter-server
解决方案
当参数被传递到 Ray 远程函数时,任何类型的参数ray.ObjectID
都会自动替换为解压缩的值(意思ray.get
是在后台调用)。所有其他参数不变。
这就是为什么如果你定义一个远程函数
# Assuming you already called "import ray" and "ray.init()".
@ray.remote
def g(x):
print(x)
你会看到的
g.remote(1) # This prints '1'
g.remote(ray.put(1)) # This also prints '1'
g.remote([ray.put(1)]) # This prints '[ObjectID(feffffffe3f2116088b37cb305fbb2537b9783ee)]'
在第三行中,因为参数是一个列表,所以ObjectID
列表里面并没有被它对应的值替换。
在您的示例中,您有
@ray.remote
def f(*xs):
print(xs)
您的版本 1和版本 2之间的区别在于,在版本 1中,您传递了多个ObjectID
参数。在版本 2中,您传入一个参数,该参数是一个包含多个ObjectID
s 的列表。
xs = [ray.put(1), ray.put(2)]
f.remote(*xs) # This prints '(1, 2)'
f.remote(xs) # This prints '([ObjectID(fcffffffe3f2116088b37cb305fbb2537b9783ee), ObjectID(fbffffffe3f2116088b37cb305fbb2537b9783ee)],)'
为了做你想做的事,你可能需要做这样的事情(基本上将两个列表合二为一)。这不是最漂亮的,但它应该工作。
@ray.remote
def h(num_xs, *xs_and_ys):
xs = xs_and_ys[:num_xs]
ys = xs_and_ys[num_xs:]
print(xs, ys)
x_ids = [ray.put(1), ray.put(2)]
y_ids = [ray.put(3), ray.put(4), ray.put(5)]
h.remote(len(x_ids), *(x_ids + y_ids)) # This prints '(1, 2) (3, 4, 5)'
推荐阅读
- css - 使用 CSS 使空白更大
- javascript - 我可以得到选择输入值但无法得到输入值
- css - 如何更改ck editor 4的边框颜色、半径和粗细
- html - 使用 skrape{it} 从 html 获取数据
- angularjs - 量角器因防火墙而无法运行?
- ruby-on-rails - Rails:将模块中的模块称为 Enum 很奇怪
- java - 模型映射器应该只映射列表的第一个条目
- javascript - 上传后在图像上添加图像
- php - PHP:未捕获的 PDOException:SQLSTATE [3D000]:无效的目录名称:1046 未选择数据库
- elasticsearch - 启动 Sonarqube 时基于 ElasticSearch 的问题:944 main ERROR Unable to locate plugin type for IfFileName