【问题标题】:How to clear cache (or force recompilation) in numba如何在 numba 中清除缓存(或强制重新编译)
【发布时间】:2017-10-23 05:20:32
【问题描述】:

我有一个用 numba 编写的相当大的代码库,我注意到当为调用另一个文件中的另一个 numba 编译函数的函数启用缓存时,当被调用函数发生更改时,被调用函数的更改不会被拾取.当我有两个文件时会出现这种情况:

测试文件2:

import numba

@numba.njit(cache=True)
def function1(x):
    return x * 10

测试文件:

import numba
from tests import file1

@numba.njit(cache=True)
def function2(x, y):
    return y + file1.function1(x)

如果在 jupyter 笔记本中,我运行以下命令:

# INSIDE JUPYTER NOTEBOOK
import sys
sys.path.insert(1, "path/to/files/")
from tests import testfile

testfile.function2(3, 4)
>>> 34   # good value

但是,如果我更改,则将 testfile2 更改为以下内容:

import numba

@numba.njit(cache=True)
def function1(x):
    return x * 1

然后我重新启动 jupyter notebook 内核并重新运行 notebook,我得到以下内容

import sys
sys.path.insert(1, "path/to/files/")
from tests import testfile

testfile.function2(3, 4)
>>> 34   # bad value, should be 7

将这两个文件导入笔记本对不良结果没有影响。此外,仅在 function1 上设置 cache=False 也无效。起作用的是在所有 njit 的函数上设置 cache=False,然后重新启动内核,然后重新运行。

我相信 LLVM 可能是内联了一些被调用的函数,然后不再检查它们。

我查看了源代码,发现有一个方法返回缓存对象numba.caching.NullCache(),实例化了一个缓存对象并运行以下内容:

cache = numba.caching.NullCache()
cache.flush()

不幸的是,这似乎没有效果。

是否有 numba 环境设置,或者我可以手动清除 conda env 中的所有缓存函数的其他方式?还是我只是做错了什么?

我在 Mac OS X 10.12.3 上使用 Anaconda Python 3.6 运行 numba 0.33。

【问题讨论】:

  • 更新:杀死 __pycache__ 目录中的所有文件 numba 使用 does 似乎有效。不过,不确定是否有更好的方法。

标签: anaconda numba


【解决方案1】:

在看到 Josh 的回答后,我通过在项目方法中创建一个实用程序来杀死缓存,从而用 hack 解决方案“解决”了这个问题。

可能有更好的方法,但这可行。如果有人这样做的方式不那么老套,我会留下这个问题。

import os


def kill_files(folder):
    for the_file in os.listdir(folder):
        file_path = os.path.join(folder, the_file)
        try:
            if os.path.isfile(file_path):
                os.unlink(file_path)
        except Exception as e:
            print("failed on filepath: %s" % file_path)


def kill_numba_cache():

    root_folder = os.path.realpath(__file__ + "/../../")

    for root, dirnames, filenames in os.walk(root_folder):
        for dirname in dirnames:
            if dirname == "__pycache__":
                try:
                    kill_files(root + "/" + dirname)
                except Exception as e:
                    print("failed on %s", root)

【讨论】:

  • 几年后,我还没有找到更好的方法,我仍在使用上述功能没有问题,所以我将其标记为正确的。任何来自 numba 项目的人有更好的方法,请告诉我!
【解决方案2】:

这有点小技巧,但这是我以前用过的东西。如果你把这个函数放在你的 numba 函数所在的顶层(对于这个例子,在testfile),它应该重新编译所有东西:

import inspect
import sys

def recompile_nb_code():
    this_module = sys.modules[__name__]
    module_members = inspect.getmembers(this_module)

    for member_name, member in module_members:
        if hasattr(member, 'recompile') and hasattr(member, 'inspect_llvm'):
            member.recompile()

然后在你想强制重新编译时从你的 jupyter notebook 调用它。需要注意的是,它仅适用于该函数所在模块中的文件及其依赖项。可能有另一种方法来概括它。

【讨论】:

  • 谢谢乔希。它对我来说不太奏效,因为我有一个包含大量文件和包的大型项目。但是赞成,因为我的这个想法是用另一个“黑客”解决方案来解决它,我把它放在下面。
猜你喜欢
  • 1970-01-01
  • 2021-09-03
  • 2014-12-23
  • 2020-09-05
  • 1970-01-01
  • 1970-01-01
  • 2017-05-19
  • 1970-01-01
  • 2019-10-21
相关资源
最近更新 更多