gpt4 book ai didi

python - 在 for 循环中使用 continue 时出现 Numba "Use of unsupported opcode (CONTINUE_LOOP) found"错误

转载 作者:行者123 更新时间:2023-12-02 02:50:19 26 4
gpt4 key购买 nike

我在尝试对定义的函数启用 numba 优化时遇到错误。

这是简化的函数:

@jit
def monte_carlo(iterations):
key1 = []
key2 = []
score = []
for i in range(iterations):
random.seed(i)
temp_matrix = random.sample(matrix, length)

for j in range(iterations):
random.seed(j)
key2.append(i)
key1.append(j)

for x in range(...):
try: temp_matrix[x] = random.sample(matrix[x], len(matrix[x]))
except: continue


scores.append(...)
return scores, keyA, keyB

monte_carlo(1000)

然后我收到此错误,在使用 Cuda 而不是 Jit 时也遇到了问题。

Traceback (most recent call last):
File "..."
File ...\numba\dispatcher.py", line 404, in _compile_for_args
error_rewrite(e, 'unsupported_error')
File "...\numba\dispatcher.py", line 344, in error_rewrite
reraise(type(e), e, None)
File "...\numba\six.py", line 668, in reraise
raise value.with_traceback(tb)
numba.errors.UnsupportedError: Failed in nopython mode pipeline (step: analyzing bytecode)
**Use of unsupported opcode (CONTINUE_LOOP) found**

File "...py", line 32:
def monte_carlo(iterations):
<source elided>
try: temp_qa_matrix[x] = random.sample(input.qa_matrix[x], len(input.qa_matrix[x]))
except: continue
^

因此,尽管它是受支​​持的构造,但它并不真正喜欢循环中的 continue。

Nunba Supported Python features

最佳答案

我认为 Numba 的文档有点不完整。它可以处理普通的 continue 语句,该语句在底层使用 Python 操作码 JUMP_ABSOLUTE,但不能处理 try/except block 内的 continue 语句,该语句使用Python 操作码 CONTINUE_LOOP

这是一个简单函数的示例,该函数(不必要)使用 continue 并与 Numba 配合使用。它将数组中大于 0.5 的元素减半。

def halve(x):
for i in range(len(x)):
if x[i] <= 0.5:
continue
x[i] /= 2

如果我们导入 Python dis 模块并查看 dis.dis(halve) 的输出,我们会看到有两个 JUMP_ABSOLUTE 操作码。这是 Python 通常用于 continue 语句的内容。如果我们使用 Numba jit 这个函数并在数组中运行它,我们会发现它工作没有问题。

但是如果我们重写half来使用try/except:

def halve(x):
for i in range(len(x)):
try:
assert x[i] > 0.5
except:
continue
x[i] /= 2

然后查看 dis.dis(halve),我们看到其中一个 JUMP_ABSOLUTE 操作码已被 CONTINUE_LOOP 替换。我不知道底层的 Python 细节,但可以肯定的是,如果我们尝试 jit 这个函数,那么 Numba 会提示有一个不受支持的操作码。

所以,TLDR:看起来你不能在 Numba 的 try/except 中使用 continue,因为与 Python 实现相关的不明原因。

我怀疑几乎总是有解决方法,但由于您的代码不是完全独立的,所以我很难知道。

(旁注:如果您使用 NumPy 数组而不是列表,通常 Numba 会做得更好。)

关于python - 在 for 循环中使用 continue 时出现 Numba "Use of unsupported opcode (CONTINUE_LOOP) found"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62109830/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com