【问题标题】:Numba, Jitclass w/ nopython mode and dictionariesNumba,带有 nopython 模式和字典的 Jitclass
【发布时间】:2017-08-28 17:45:04
【问题描述】:

试图弄清楚如何在使用 jitclass 时跳过类方法。

有一个相当大的递归模型(几乎是一个巨大的 for 循环),它 - 给定路径相关的计算,不能用直接 Numpy 向量化。

该类通过一系列 numpy 数组运行,通常具有 numba 友好的语法,但是我有一个部分以有序的方式调用一些方法:

def operations(self, i, ops_order_config):

    ops_dict = self.ops_dict

    for index in range(len(waterfall_config)):
        try:
            if isinstance(ops_config[index], tuple):
                ops_dict[ops_config[index][0]](i, ops_config[index][1])
            else:
                ops_dict[ops_config[index]](i)
        except KeyError:
            pass

模型的这一部分对于灵活性非常重要——“配置”是一个有序的元组列表,其中包含要调用的适当方法和相应的参数。 ops_dict 包含实际的自我。从配置中调用,带有适当的参数。

如果我正在制作一个 jitclass,有什么办法可以跳过这个字典方面的 jitting 吗?

【问题讨论】:

    标签: python numpy dictionary numba


    【解决方案1】:

    不,如果您创建 jitclass,则必须键入每个属性,并且从 numba 0.34 开始不支持包含函数的字典或列表/元组(即使是 jitted)。例如尝试使用dictobject 作为类型:

    import numpy as np
    from numba import jitclass
    
    spec = [('dct', dict)]
    
    @jitclass(spec)
    class ClsWithObject(object):
        def __init__(self, value):
            self.dct = {}
    

    抛出TypeError

    TypeError: spec values should be Numba type instances, got <class 'dict'>

    此外,使用 isinstance 以及 tryexcept 在 nopython 模式下也不起作用。

    您最好的选择是使用从纯 Python 类中调用的 jitted 函数。

    【讨论】:

    • 谢谢。当 jitclass 被使用和工作时,是否可以安全地假设正在应用 nopython 模式?
    • @user7038639 是的。该类的所有方法都将在 nopython 模式下编译。 docs 明确提到:“ jitclass 的所有方法都编译为 nopython 函数。jitclass 实例的数据作为 C 兼容结构在堆上分配,因此任何编译后的函数都可以直接访问底层数据,绕过翻译。” :)
    • 废话,看过这些文档 10 次,似乎错过了。谢谢!
    【解决方案2】:

    关于在 Numba 编译函数中使用字典,正如 MSeifert 所说,Numba 不支持这一点。在我自己的工作中,我遇到了这个问题,并在 Numba 中找到了一个很好的字典实现(不是我创建的),它的 GitHub 存储库可以在 here 找到。

    【讨论】:

    • Numba 现在支持字典,而且速度很快。
    猜你喜欢
    • 2017-08-08
    • 1970-01-01
    • 2020-06-15
    • 2017-05-24
    • 2019-08-15
    • 2020-05-09
    • 2016-12-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多