我想在flask服务器上运行pyCUDA代码。该文件可以直接使用python3正确运行,但在使用flask调用相应函数时会失败。
相关代码如下:
cudaFlask.py:
import pycuda.autoinit
import pycuda.driver as drv
import numpy
from pycuda.compiler import SourceModule
def cudaTest():
mod = SourceModule("""
int x = 4;
""")
print ("done")
return
if __name__ == "__main__":
cudaTest()server.py (仅调用函数的部分):
@app.route('/bundle', methods=['POST'])
def bundle_edges():
cudaTest()
return "success"在运行python cudaFlask.py时,我得到了预期的输出done,但在启动服务器并在website/bundle上执行POST请求时,我在flask控制台上得到了以下错误:
pycuda._driver.LogicError: cuModuleLoadDataEx failed: invalid device context - 在mod = SourceModule...行上
我哪里错了?有一个similar question,但它还没有得到回答。
发布于 2018-06-19 11:48:50
解决了flask中的延迟加载和手动制作context的问题(即在PyCUDA中没有pycuda.autoinit )。
有关flask中的延迟加载,请参阅this。
我的views.py文件:
import numpy as np
import pycuda.driver as cuda
from pycuda.compiler import SourceModule
def index():
cuda.init()
device = cuda.Device(0) # enter your gpu id here
ctx = device.make_context()
mod = SourceModule("""
int x = 4;
""")
ctx.pop() # very important
print ("done")
return "success"发布于 2018-06-07 21:16:06
PyCUDA可能与WSGI web服务器上下文不兼容。如果您使用某种消息队列(如Celery ),您可能会让它工作,在这种队列中,HTTP请求将一个作业放在队列上,队列另一端的worker运行CUDA程序。
编辑:一种快速而简单的方法是使用Python Subprocess check_output function
在web请求中:
subprocess.check_output(['python', 'cudaFlask.py'])
发布于 2021-08-02 14:03:56
根据您的解决方案,我将代码从
def print_device_info():
(free,total)=drv.mem_get_info()
print("Global memory occupancy:%f%% free"%(free*100/total))
for devicenum in range(cuda.Device.count()):
device=drv.Device(devicenum)
attrs=device.get_attributes()
#Beyond this point is just pretty printing
print("\n===Attributes for device %d"%devicenum)
for (key,value) in attrs.iteritems():
print("%s:%s"%(str(key),str(value)))至
def print_device_info():
drv.init()
device = drv.Device(0) # enter your gpu id here
ctx = device.make_context()
(free,total)=drv.mem_get_info()
print("Global memory occupancy:%f%% free"%(free*100/total))
attrs=device.get_attributes()
#Beyond this point is just pretty printing
print("\n===Attributes for device %d"%0)
for (key,value) in attrs.items():
print("%s:%s"%(str(key),str(value)))
ctx.pop()它就像护身符一样起作用。非常感谢你分享你的解决方案,这真的让我很开心!
https://stackoverflow.com/questions/50601029
复制相似问题