使用 Flask 时 PyCUDA 上下文错误

clo*_*ayx 8 python image-processing flask pycuda server

我正在使用 PyCUDA 来实现 smooth_local_affine,如下所示。当我简单地在Linux上运行该程序时,它运行得很好。但是当我尝试在 Flask 上下文下导入它时:

from smooth_local_affine import smooth_local_affine
from flask import Flask
app = Flask(_name_)
...
Run Code Online (Sandbox Code Playgroud)

出现以下错误:

-------------------------------------------------------------------  
PyCUDA ERROR: The context stack was not empty upon module cleanup.
-------------------------------------------------------------------   
A context was still active when the context stack was being cleaned up.  
At this point in our execution, CUDA may already have been deinitialized, 
so there is no way we can finish cleanly. The program will be aborted now. 
Use Context.pop() to avoid this problem.
Run Code Online (Sandbox Code Playgroud)

然后我尝试添加context.pop(),然后又出现错误;

atexit._run_exitfuncs 中的错误:回溯(最近一次调用):
文件“/home/yifang/anaconda3/envs/python3/lib/python3.6/site-packages/pycuda-2017.1-py3.6-linux-x86_64.egg /pycuda/autoinit.py",第 14 行,在 _finish_up context.pop() pycuda._driver.LogicError: context::pop failed: 无效的设备上下文 - 无法弹出非当前上下文

有人知道如何在 Flask 环境中运行 PyCuda 吗?或者也许有其他方法可以在不使用 PyCuda 的情况下使用 smooth_local_affine 功能?

afo*_*rdz 4

让我在这里提出一种解决方案,因为我已经尝试了很多解决方案但仍然不起作用。幸运的是我找到了一个正确的答案。

一些解决方案,例如

import pycuda.autoinit
Run Code Online (Sandbox Code Playgroud)

或者

cuda.init 
device = cuda.Device(0) 
ctx = device.make_context() 
inputs, outputs, bindings, stream = allocate_buffer() 
ctx.pop()
Run Code Online (Sandbox Code Playgroud)

如果您将脚本作为简单程序运行,这些可能会起作用,但如果您使用 Flask 或其他 Web 服务器运行,则会引发上下文错误。根据我的搜索,原因可能是 Flask 服务器在收到请求时会产生新线程。

在这种情况下,真正的解决方案非常简单,您应该添加如下代码:

with engine.create_execution_context() as context:
    ctx = cuda.Context.attach()
    inputs, outputs, bindings, stream = allocate_buffer()
    ctx.detach()
Run Code Online (Sandbox Code Playgroud)

这对我有用