メインコンテンツまでスキップ

F順序配列の修正

問題のステートメント

NumPy配列がF順序の場合、Protobufのエンコード/デコードが失敗する

テスト

from mcbackend.npproto.utils import ndarray_to_numpy, ndarray_from_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)),
)

コード差分

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
@@ -1,23 +1,23 @@
"""
A framework agnostic implementation for storage of MCMC draws.
"""
from .backends.numpy import NumPyBackend
from .core import Backend, Chain, Run
from .meta import ChainMeta, Coordinate, DataVariable, ExtendedValue, RunMeta, Variable

# Backends
try:
from .backends import clickhouse
from .backends.clickhouse import ClickHouseBackend
except ModuleNotFoundError:
pass

# Adapters
try:
from .adapters import pymc
from .adapters.pymc import TraceBackend
except ModuleNotFoundError:
pass


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

mcbackend/npproto/utils.py

diff --git a/mcbackend/npproto/utils.py b/mcbackend/npproto/utils.py
index 27bc98c..8ae5396 100644
--- a/mcbackend/npproto/utils.py
+++ b/mcbackend/npproto/utils.py
@@ -1,40 +1,46 @@
"""
Helper functions such as converters between ``ndarray`` and ``Ndarray``.
"""
import numpy

from . import Ndarray


def ndarray_from_numpy(arr: numpy.ndarray) -> Ndarray:
dt = str(arr.dtype)
if "datetime64" in dt:
# datetime64 doesn't support the buffer protocol.
# See https://github.com/numpy/numpy/issues/4983
# This is a hack that automatically encodes it as int64.
arr = arr.astype("int64")
+ # With non-C-ordered arrays (e.g. Fortran-ordered) the underlying buffer
+ # does not match the strides of the original array anymore, because
+ # ``bytes(arr.data)`` always returns the data in C-order.
+ # Therefore, the array is made C-contiguous before extracting data and strides.
+ if not arr.flags.c_contiguous:
+ arr = numpy.ascontiguousarray(arr)
return Ndarray(
shape=list(arr.shape),
dtype=dt,
data=bytes(arr.data),
strides=list(arr.strides),
)


def ndarray_to_numpy(nda: Ndarray) -> numpy.ndarray:
arr: numpy.ndarray
if "datetime64" in nda.dtype:
# Backwards conversion: The data was stored as int64.
arr = numpy.ndarray(
buffer=nda.data,
shape=nda.shape,
dtype="int64",
strides=nda.strides,
).astype(nda.dtype)
else:
arr = numpy.ndarray(
buffer=nda.data,
shape=nda.shape,
dtype=numpy.dtype(nda.dtype),
strides=nda.strides,
)

mcbackend/test_npproto.py

diff --git a/mcbackend/test_npproto.py b/mcbackend/test_npproto.py
index fc88d29..fd88e7c 100644
--- a/mcbackend/test_npproto.py
+++ b/mcbackend/test_npproto.py
@@ -1,45 +1,48 @@
from datetime import datetime

import numpy
import pytest

from mcbackend import npproto
from mcbackend.npproto import utils


class TestUtils:
@pytest.mark.parametrize(
"arr",
[
numpy.arange(5),
numpy.random.uniform(size=(2, 3)),
numpy.array(5),
numpy.array(["hello", "world"]),
numpy.array([datetime(2020, 3, 4, 5, 6, 7, 8), datetime(2020, 3, 4, 5, 6, 7, 9)]),
numpy.array(
[datetime(2020, 3, 4, 5, 6, 7, 8), datetime(2020, 3, 4, 5, 6, 7, 9)],
dtype="datetime64",
),
numpy.array([(1, 2), (3, 2, 1)], dtype=object),
+ numpy.array([[1, 2, 3], [4, 5, 6]], order="C"),
+ numpy.array([[1, 2, 3], [4, 5, 6]], order="F"),
+ numpy.arange(12).reshape(3, 4)[::2, ::2],
],
)
def test_conversion(self, arr: numpy.ndarray):
nda = utils.ndarray_from_numpy(arr)
enc = bytes(nda)
dec = npproto.Ndarray().parse(enc)
assert isinstance(dec.data, bytes)
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

コミットメッセージ

非連続なNumPy配列のエンコードを修正

`bytes(arr.data)`は常にバッファの内容をC順序で返しますが、
Fortran順序(または他の非C連続)配列をエンコードすると、
`ndarray_from_numpy`と`ndarray_to_numpy`間のラウンドトリップでデータが破損します。
元のストライドが保存されると、配列がスクランブルされます。

ストライドとデータを抽出する前に、`numpy.ascontiguousarray`を使用して
配列をC連続にします。これで、バッファとストライドの整合性が保たれます。

Closes #2124

注:バージョン`0.2.4`では、C順序、F順序、および非連続配列のラウンドトリップテストが追加されています。

プルリクエスト

概要

NumPy配列のProtobufラウンドトリップは、ソース配列がC連続でない場合(たとえば、Fortran順序)、暗黙のうちにデータを破損させます。この修正により、すべてのメモリレイアウトがエンコード/デコードサイクルを正常に通過できるようになります。

arrF = numpy.array([[1, 2, 3], [4, 5, 6]], order="F")
numpy.testing.assert_array_equal(
arrF,
ndarray_to_numpy(ndarray_from_numpy(arrF)), # この修正前は失敗しました
)

根本原因

ndarray_from_numpyのエンコードパスは、入力配列の生バッファとストライドの両方を格納します。問題は、この2つの不一致です。

  1. エンコード: bytes(arr.data)は基礎となるメモリバッファをコピーします。非C連続配列の場合、このコピーは暗黙のうちにC順序に並べ替えられます。
  2. そのまま保存されるストライド: 付属のstridesは、並べ替えが適用されないため、元の(非C)形式で保存されます。
  3. デコード: numpy.ndarray(buffer=..., strides=...)は、元のストライドを使用してC順序バッファを解釈することで配列を再構築し、この不一致によりスクランブルされた配列が生成されます。

修正

バッファとストライドを抽出する前にnumpy.ascontiguousarrayを呼び出し、両方が同じメモリレイアウトを反映するようにします。

  • mcbackend/npproto/utils.py: datastridesを抽出する前に、配列をC連続にします。格納されたストライドは、常に格納されたバッファレイアウトと一致するようになりました。すでにC連続である配列は影響を受けません。
  • mcbackend/test_npproto.py: C順序、F順序、および非連続(スライスされた)配列の明示的なラウンドトリップテストケースを追加します。

テスト

TestUtils.test_conversionのテストマトリックスは以下をカバーするようになりました。

  • numpy.array([[1, 2, 3], [4, 5, 6]], order="C")
  • numpy.array([[1, 2, 3], [4, 5, 6]], order="F")
  • numpy.arange(12).reshape(3, 4)[::2, ::2](非連続ビュー)

既存のすべてのdtypeケース(int、float、str、datetime、object)は変更なく通過します。

ノート

  • バージョンを0.2.4に上げます。
  • ndarray_to_numpyは変更されていません。デコード側の変更は必要ありません。

テスト方法

  1. pytest mcbackend/test_npproto.pyを実行します。3つの新しいパラメータ化されたケース(C順序、F順序、非連続スライス)がパスするはずです。
  2. 既存のすべてのdtypeケース(int、float、str、datetime、object)が変更なくパスすることを確認します。