跳到主要内容

F-排序数组的修复

问题陈述​

如果 NumPy 数组是 F-排序的,则其 Protobuf 编码/解码会失败

测试​

import numpy

from mcbackend.npproto.utils import ndarray_from_numpy, ndarray_to_numpy

arrC = numpy.array([
[1,2,3],
[4,5,6],
], order="C")

arrF = numpy.array([
[1,2,3],
[4,5,6],
], order="F")

assert arrC.strides != arrF.strides

numpy.testing.assert_array_equal(
arrC,
ndarray_to_numpy(ndarray_from_numpy(arrC)),
)
numpy.testing.assert_array_equal(
arrF,
ndarray_to_numpy(ndarray_from_numpy(arrF)),
)

代码差异​

protobufs/npproto/ndarray.proto​

diff --git a/protobufs/npproto/ndarray.proto b/protobufs/npproto/ndarray.proto
index fee734c..0a7d399 100644
--- a/protobufs/npproto/ndarray.proto
+++ b/protobufs/npproto/ndarray.proto
@@ -9,4 +9,5 @@ message ndarray {
string dtype = 2;
repeated int64 shape = 3;
repeated int64 strides = 4;
+ string order = 5;
}

mcbackend/npproto/__init__.py​

diff --git a/mcbackend/npproto/__init__.py b/mcbackend/npproto/__init__.py
index 4554e02..e3d99a6 100644
--- a/mcbackend/npproto/__init__.py
+++ b/mcbackend/npproto/__init__.py
@@ -18,3 +18,4 @@ class Ndarray(betterproto.Message):
dtype: str = betterproto.string_field(2)
shape: List[int] = betterproto.int64_field(3)
strides: List[int] = betterproto.int64_field(4)
+ order: str = betterproto.string_field(5)

mcbackend/npproto/utils.py​

diff --git a/mcbackend/npproto/utils.py b/mcbackend/npproto/utils.py
index 27bc98c..2dd0536 100644
--- a/mcbackend/npproto/utils.py
+++ b/mcbackend/npproto/utils.py
@@ -18,6 +18,7 @@ def ndarray_from_numpy(arr: numpy.ndarray) -> Ndarray:
dtype=dt,
data=bytes(arr.data),
strides=list(arr.strides),
+ order="CF"[arr.flags.f_contiguous],
)


@@ -38,4 +39,12 @@ def ndarray_to_numpy(nda: Ndarray) -> numpy.ndarray:
dtype=numpy.dtype(nda.dtype),
strides=nda.strides,
)
+ # The code that reads the bytes(arr.data) always results in C-ordered data.
+ # Passing `to the `np.ndarray(order=...)` call has no effect.
+ # This is where below workaround comes into play:
+ # It reshapes arrays that were originally in Fortran order.
+ # F-ordered arrays that were encoded with mcbackend < 0.2.4 default
+ # to `nda.order == ""` and there is nothing we can do for these.
+ if nda.order == "F":
+ arr = arr.T.reshape(arr.shape)
return arr

mcbackend/test_npproto.py​

diff --git a/mcbackend/test_npproto.py b/mcbackend/test_npproto.py
index 0ec5053..fc88d29 100644
--- a/mcbackend/test_npproto.py
+++ b/mcbackend/test_npproto.py
@@ -31,3 +31,15 @@ class TestUtils:
result = utils.ndarray_to_numpy(dec)
numpy.testing.assert_array_equal(result, arr)
pass
+
+ @pytest.mark.parametrize("shape", [(5,), (2, 3), (2, 3, 5), (5, 2, 1, 7)])
+ @pytest.mark.parametrize("order", "CF")
+ def test_byteorders(self, shape, order):
+ arr = numpy.arange(numpy.prod(shape)).reshape(shape, order=order)
+
+ nda = utils.ndarray_from_numpy(arr)
+ assert nda.order == "CF"[arr.flags.f_contiguous]
+
+ dec = utils.ndarray_to_numpy(nda)
+ numpy.testing.assert_array_equal(arr, dec)
+ pass

mcbackend/__init__.py​

diff --git a/mcbackend/__init__.py b/mcbackend/__init__.py
index 35ef7b9..c6a43eb 100644
--- a/mcbackend/__init__.py
+++ b/mcbackend/__init__.py
@@ -20,4 +20,4 @@ except ModuleNotFoundError:
pass


-__version__ = "0.2.3"
+__version__ = "0.2.4"

提交信息​

修复 F-排序 NumPy 数组的编码/解码问题

`bytes(arr.data)`会将缓冲区内容按C语言顺序具体化,因此对按Fortran顺序排列的数组进行编码时,会将按C语言顺序排列的字节与Fortran步长配对。解码时,系统会以错误的步长读取这些字节,从而返回一个顺序混乱的数组。

将内存顺序记录在`Ndarray`消息的新`order`字段中,当该字段报告“F”时,让`ndarray_to_numpy`进行转置和重塑。在0.2.4之前编码的缓冲区其`order`字段为空,因此解码后会得到C顺序数组。

Closes #63

拉取请求​

摘要​

Protobuf 的往返传输会导致采用 Fortran 顺序的 NumPy 数组数据损坏。采用 Fortran 顺序的数组在返回时,其值的位置会发生错乱。解码器不会抛出任何异常,而调用方则会接受一个顺序混乱的数组。

Round-trip test
arrF = numpy.array([[1, 2, 3], [4, 5, 6]], order="F")
numpy.testing.assert_array_equal(
arrF,
ndarray_to_numpy(ndarray_from_numpy(arrF)), # returns [[1, 3, 5], [2, 4, 6]] without the fix
)

根本原因​

ndarray_from_numpy 将原始缓冲区存储在数组步长旁边,而这两个值描述了不同的内存布局:

  1. 编码:bytes(arr.data) 会将缓冲区按 C 顺序具体化,因此按 Fortran 顺序排列的源数组会生成按 C 顺序排列的字节。
  2. 步长:ndarray_from_numpy 会原样复制 strides,因此它们仍然描述 Fortran 的布局。
  3. 解码:numpy.ndarray(buffer=..., strides=...)会将 Fortran 步长应用于 C 字节序的数组。这些偏移量指向了错误的单元格,并返回了错误的值。

修复​

在编码过程中记录内存顺序。在解码过程中重放该顺序。

  • protobufs/npproto/ndarray.proto 和生成的 mcbackend/npproto/__init__.py 在 Ndarray 消息中新增了一个 order 字符串字段(标签 5)。
  • mcbackend/npproto/utils.py在编码过程中写入order="CF"[arr.flags.f_contiguous]。Fortran顺序的数组存储"F"。在解码过程中,当nda.order == "F"时,ndarray_to_numpy会进行转置和重塑。该步骤会根据C顺序的字节重建Fortran布局。
  • mcbackend/test_npproto.py 添加了 test_byteorders,该函数将 shape 和 order 作为参数一起处理。

测试​

TestUtils.test_byteorders 同时对 shape 和 order 进行参数化。(5,)、(2, 3)、(2, 3, 5) 和 (5, 2, 1, 7) 每个组合都会运行两次,每种内存顺序各运行一次。每个测试用例都会断言 nda.order 与 arr.flags.f_contiguous 匹配,然后将数组通过编码和解码进行一次往返处理。

TestUtils.test_conversion 仍然涵盖了 int、float、scalar、string、object 和 datetime 这几种数据类型。

注释​

  • 将版本号更新为0.2.4。
  • ndarray_to_numpy 增加了转置步骤,并保留了现有的缓冲区和数据类型处理机制。
  • 在0.2.4之前编码的缓冲区其order字段为空。解码此类缓冲区将得到一个按C顺序排列的数组。

如何测试​

Verify the fix
pytest mcbackend/test_npproto.py

该测试套件在两种内存顺序下运行了新的test_byteorders测试用例,并重新运行了现有的dtype测试用例。