繁体   English   中英

转换为 32 位 integer 后 Cython function 中的神秘翻转位

[英]Mysteriously flipped bits in a Cython function after casting to 32-bit integer

我有一个古怪的 Cython function,它在过去 72 小时内开始表现得很奇怪。

我们正在使用稀疏的 COO 矩阵做一些事情,这需要遍历矩阵的 COO 表示的列索引。 因为我想快速执行此操作,所以我将提取的列值粘贴到键入的 C 变量中,如下所示:

ranked_groups = A[local_ranked,:].tocoo()
ranked_groups_col_c = ranked_groups.col.astype(np.int32)

奇怪的是, ranked_groups_col_c的内容有时会被打乱。 也就是说, ranked_groups_col_c应该只能包含从 0 到变量A列的值。 例如,如果 A 是 100x100,我们预计ranked_groups_col_c的值在 0 到 99 之间。

使用调试器,我已经确认预制变量ranked_groups的列内容确实受列数的限制。

虽然 10 次中大约有 9 次我们使用此代码,但ranked_groups_col_c中的一些值(在转换后)在我看来就像它们有随机加扰的位。 例如,对于 208621 列的 COO 矩阵,我记录了这样的案例:

>>> 280205 208621
>>> 1120897 208621
>>> 891677560 208621
>>> 891677560 208621

其中第一个数字是ranked_groups_col_c中的索引(不应超过列数),第二个数字是源矩阵中的列数作为参考。

我已经尝试将 NumPy 升级到最新版本和过去的版本,并且这种情况一直在发生。 我们还联系了我们的云提供商,他们没有回信。 我不得不认为这是一些非常低级的错误,但我不清楚那可能是什么。

更新:我们有点犹豫是否要发布整个 function,但这里有一个包含变量声明的片段:

# the matrix A is an argument of the function

ranked = np.argsort(-scores).astype(np.int32)

seen = np.zeros(A.shape[1], dtype=np.int32)
cdef int[:] seen_c = seen
cdef int[:] local_ranked_c
cdef int[:] ranked_groups_col_c

for i in range(n):
    local_ranked = ranked[i,:]
    local_ranked_c = local_ranked

    ranked_groups = A[local_ranked,:].tocoo()
    ranked_groups_col_c = ranked_groups.col.astype(np.int32)

    for pos in range(m):
        j = local_ranked_c[pos]
        k = ranked_groups_col_c[pos]

        if seen_c[k]:
            pass

根据 Python 安装(即它是 64 位安装吗?),转换为 32 位整数可能会出现问题。 对于 64 位 Python 解释器,整数是 64 位宽的(与例如 x86_64 C 编译器的int不同,它是 32 位宽)。 If a single 64-bit Python integer is cast to 32 bits on a machine with little endian ordering (such as 64-bit Intel), the 32 higher bits are simply chopped off, which is fine if the integer isn't larger than 2 31 -1 或小于 -2 31 (对于正整数或负整数,高位应全部为零或一)。 但是,如果出现更大幅度的整数,32 位转换将导致错误。 如果代码的 C 部分应访问 64 位宽的 Python 整数数组作为 32 位整数数组,则除第 0 个元素的索引之外的所有元素都是错误的。

是在 Linux 和 OSX 的 64 位安装上转换为long ,还是在 64 位 MS Windows 安装上转换为long long

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM