Newer
Older
TongueSegModel / tests / export / test_check.py
"""書き出した ONNX の確認の判定(`export/check.py`)のテスト.

期待値は SPEC_02「ONNX の書き出し」の表(入力 `(1, 3, 256, 256)` float32・出力
`(1, 2, 256, 256)` float32・opset 11)と,確認の項目(onnxruntime で読めること・入出力の形と型・
PyTorch の出力との最大の絶対差を,PyTorch の出力の最大の絶対値(下限 1.0)との比 1e-4 で判定する
こと・2 値のマスクの違う画素が画素の 0.1% 以下であること)を基準にする.すべて純関数なので
ファイルを作らない.
"""

from __future__ import annotations

import json
import math
from pathlib import Path
from typing import Any

import numpy as np
import pytest

from tongue_seg_model.export.check import (
    CHECK_INPUT_SEED,
    MAX_DIFF_RATIO_TOLERANCE,
    MAX_MASK_MISMATCH_RATIO,
    OUTPUT_SCALE_FLOOR,
    OnnxModelInfo,
    TensorSpec,
    allowed_max_abs_diff,
    build_export_record,
    count_mask_mismatch,
    export_input_shape,
    export_output_shape,
    find_export_problems,
    make_check_input,
    max_abs_diff,
    max_abs_diff_ratio,
    max_mask_mismatch,
    output_max_abs,
)
from tongue_seg_model.training.metrics import write_metrics_json

IN_SHAPE = (1, 3, 256, 256)
OUT_SHAPE = (1, 2, 256, 256)
MASK_LIMIT = 65  # 256×256 の 0.1%(65.536)の切り捨て


def _info(
    *,
    opset: int | None = 11,
    inputs: tuple[TensorSpec, ...] | None = None,
    outputs: tuple[TensorSpec, ...] | None = None,
) -> OnnxModelInfo:
    return OnnxModelInfo(
        opset=opset,
        inputs=(TensorSpec("input.1", IN_SHAPE, "float32"),) if inputs is None else inputs,
        outputs=(TensorSpec("269", OUT_SHAPE, "float32"),) if outputs is None else outputs,
    )


def _problems(info: OnnxModelInfo | None = None, **overrides: Any) -> list[str]:
    kwargs: dict[str, Any] = {
        "opset": 11,
        "input_shape": IN_SHAPE,
        "output_shape": OUT_SHAPE,
        "runtime_output_shape": OUT_SHAPE,
        "runtime_output_dtype": "float32",
        "diff": 0.0,
        "output_scale": 0.5,
        "mask_mismatch": 0,
        "mask_mismatch_limit": MASK_LIMIT,
    }
    kwargs.update(overrides)
    return find_export_problems(_info() if info is None else info, **kwargs)


# ---------------------------------------------------------------------------
# 定数・形
# ---------------------------------------------------------------------------


def test_tolerance_and_seed_constants() -> None:
    assert MAX_DIFF_RATIO_TOLERANCE == 1e-4
    assert OUTPUT_SCALE_FLOOR == 1.0
    assert MAX_MASK_MISMATCH_RATIO == 1e-3
    assert CHECK_INPUT_SEED == 0


class TestShapes:
    def test_default_input_shape_matches_spec02(self) -> None:
        assert export_input_shape((256, 256)) == IN_SHAPE

    def test_default_output_shape_matches_spec02(self) -> None:
        assert export_output_shape((256, 256), 2) == OUT_SHAPE

    def test_height_then_width(self) -> None:
        assert export_input_shape((64, 128)) == (1, 3, 64, 128)
        assert export_output_shape((64, 128), 2) == (1, 2, 64, 128)

    def test_accepts_list(self) -> None:
        assert export_input_shape([32, 64]) == (1, 3, 32, 64)

    def test_shape_values_are_python_ints(self) -> None:
        shape = export_input_shape((np.int64(64), np.int64(64)))
        assert all(type(v) is int for v in shape)


# ---------------------------------------------------------------------------
# 比較用の入力
# ---------------------------------------------------------------------------


class TestMakeCheckInput:
    def test_shape_and_dtype(self) -> None:
        x = make_check_input(IN_SHAPE, 0)
        assert x.shape == IN_SHAPE
        assert x.dtype == np.float32

    def test_values_in_unit_interval(self) -> None:
        # 実際の入力(BGR を 255 で割った値)と同じ値域
        x = make_check_input((1, 3, 64, 64), 0)
        assert float(x.min()) >= 0.0
        assert float(x.max()) < 1.0
        assert float(x.std()) > 0.1  # 定数ではない

    def test_same_seed_reproduces(self) -> None:
        np.testing.assert_array_equal(
            make_check_input((1, 3, 32, 32), 0), make_check_input((1, 3, 32, 32), 0)
        )

    def test_different_seed_differs(self) -> None:
        assert not np.array_equal(
            make_check_input((1, 3, 32, 32), 0), make_check_input((1, 3, 32, 32), 1)
        )

    def test_independent_of_global_random_state(self) -> None:
        state = np.random.get_state()
        try:
            np.random.seed(123)
            a = make_check_input((1, 3, 16, 16), CHECK_INPUT_SEED)
            np.random.seed(456)
            np.random.random(10)
            b = make_check_input((1, 3, 16, 16), CHECK_INPUT_SEED)
        finally:
            np.random.set_state(state)
        np.testing.assert_array_equal(a, b)

    def test_does_not_advance_global_random_state(self) -> None:
        state = np.random.get_state()
        try:
            np.random.seed(7)
            expected = np.random.random(3)
            np.random.seed(7)
            make_check_input((1, 3, 16, 16), 0)
            np.testing.assert_array_equal(np.random.random(3), expected)
        finally:
            np.random.set_state(state)


# ---------------------------------------------------------------------------
# 最大の絶対差
# ---------------------------------------------------------------------------


class TestMaxAbsDiff:
    def test_identical_is_zero(self) -> None:
        a = make_check_input((1, 2, 8, 8), 0)
        assert max_abs_diff(a, a.copy()) == 0.0

    def test_known_value(self) -> None:
        a = np.array([[0.0, 1.0], [2.0, -3.0]], dtype=np.float32)
        b = np.array([[0.5, 1.0], [2.0, -1.0]], dtype=np.float32)
        assert max_abs_diff(a, b) == pytest.approx(2.0)

    def test_symmetric(self) -> None:
        a = np.array([1.0, -2.0, 3.0], dtype=np.float32)
        b = np.array([1.5, -2.25, 2.0], dtype=np.float32)
        assert max_abs_diff(a, b) == max_abs_diff(b, a) == pytest.approx(1.0)

    def test_returns_python_float(self) -> None:
        a = np.zeros((2, 2), dtype=np.float32)
        assert type(max_abs_diff(a, a)) is float

    def test_small_float32_difference_is_not_lost(self) -> None:
        a = np.array([1.0], dtype=np.float32)
        b = np.nextafter(a, np.float32(2.0))
        assert max_abs_diff(a, b) == pytest.approx(float(b[0]) - 1.0)
        assert max_abs_diff(a, b) > 0.0

    def test_nan_propagates(self) -> None:
        a = np.array([0.0, 1.0], dtype=np.float32)
        b = np.array([0.0, np.nan], dtype=np.float32)
        assert math.isnan(max_abs_diff(a, b))

    def test_shape_mismatch_raises(self) -> None:
        with pytest.raises(RuntimeError):
            max_abs_diff(np.zeros((1, 2, 4, 4)), np.zeros((1, 2, 4, 5)))

    def test_empty_is_zero(self) -> None:
        assert max_abs_diff(np.zeros((0, 2)), np.zeros((0, 2))) == 0.0


# ---------------------------------------------------------------------------
# 問題の検出
# ---------------------------------------------------------------------------


class TestFindExportProblems:
    def test_spec_conforming_export_has_no_problems(self) -> None:
        assert _problems() == []

    def test_accepts_sequences_for_shapes(self) -> None:
        assert (
            _problems(
                input_shape=list(IN_SHAPE),
                output_shape=list(OUT_SHAPE),
                runtime_output_shape=list(OUT_SHAPE),
            )
            == []
        )

    @pytest.mark.parametrize("opset", [10, 12, 18, None])
    def test_opset_mismatch(self, opset: int | None) -> None:
        problems = _problems(_info(opset=opset))
        assert len(problems) == 1
        assert "opset" in problems[0]

    def test_opset_compared_to_requested(self) -> None:
        # 設定の export.opset を 13 にしたなら 13 が正しい
        assert _problems(_info(opset=13), opset=13) == []
        assert len(_problems(_info(opset=11), opset=13)) == 1

    @pytest.mark.parametrize("count", [0, 2])
    def test_input_count_must_be_one(self, count: int) -> None:
        spec = TensorSpec("input.1", IN_SHAPE, "float32")
        problems = _problems(_info(inputs=(spec,) * count))
        assert len(problems) == 1
        assert "入力" in problems[0]

    @pytest.mark.parametrize("count", [0, 2])
    def test_output_count_must_be_one(self, count: int) -> None:
        spec = TensorSpec("269", OUT_SHAPE, "float32")
        problems = _problems(_info(outputs=(spec,) * count))
        assert len(problems) == 1
        assert "出力" in problems[0]

    @pytest.mark.parametrize(
        "shape",
        [
            (1, 3, 256, 255),
            (2, 3, 256, 256),
            (1, 1, 256, 256),
            (3, 256, 256),
            ("batch", 3, 256, 256),
            (1, 3, "height", "width"),
        ],
    )
    def test_input_shape_mismatch(self, shape: tuple[int | str, ...]) -> None:
        problems = _problems(_info(inputs=(TensorSpec("input.1", shape, "float32"),)))
        assert len(problems) == 1
        assert "入力の形" in problems[0]

    @pytest.mark.parametrize(
        "shape", [(1, 1, 256, 256), (1, 2, 128, 128), ("batch", 2, 256, 256), (1, 2, 256)]
    )
    def test_output_shape_mismatch(self, shape: tuple[int | str, ...]) -> None:
        problems = _problems(_info(outputs=(TensorSpec("269", shape, "float32"),)))
        assert len(problems) == 1
        assert "出力の形" in problems[0]

    @pytest.mark.parametrize("dtype", ["float64", "float16", "uint8", "onnx:16"])
    def test_input_dtype_mismatch(self, dtype: str) -> None:
        problems = _problems(_info(inputs=(TensorSpec("input.1", IN_SHAPE, dtype),)))
        assert len(problems) == 1
        assert "入力の型" in problems[0]

    @pytest.mark.parametrize("dtype", ["float64", "float16", "int64"])
    def test_output_dtype_mismatch(self, dtype: str) -> None:
        problems = _problems(_info(outputs=(TensorSpec("269", OUT_SHAPE, dtype),)))
        assert len(problems) == 1
        assert "出力の型" in problems[0]

    def test_shape_and_dtype_both_reported(self) -> None:
        problems = _problems(_info(inputs=(TensorSpec("input.1", (1, 3, 8, 8), "float64"),)))
        assert len(problems) == 2

    def test_names_are_not_checked(self) -> None:
        # SPEC_02: 入出力の名前は記録するが合わせ込みはしない(名前の違いは問題にしない)
        info = _info(
            inputs=(TensorSpec("x", IN_SHAPE, "float32"),),
            outputs=(TensorSpec("conv2d_32", OUT_SHAPE, "float32"),),
        )
        assert _problems(info) == []

    def test_runtime_output_shape_mismatch(self) -> None:
        problems = _problems(runtime_output_shape=(1, 2, 128, 128))
        assert len(problems) == 1
        assert "onnxruntime" in problems[0]

    def test_runtime_output_dtype_mismatch(self) -> None:
        problems = _problems(runtime_output_dtype="float64")
        assert len(problems) == 1
        assert "onnxruntime" in problems[0]

    def test_diff_equal_to_tolerance_is_ok(self) -> None:
        # 出力の最大の絶対値が下限 1.0 以下なら,許容値は絶対差 1e-4(従来と同じ)
        assert _problems(diff=MAX_DIFF_RATIO_TOLERANCE) == []

    def test_diff_just_above_tolerance_is_problem(self) -> None:
        above = float(np.nextafter(MAX_DIFF_RATIO_TOLERANCE, 1.0))
        problems = _problems(diff=above)
        assert len(problems) == 1
        assert "絶対差" in problems[0]

    def test_typical_float32_rounding_is_ok(self) -> None:
        # 実測の差(4.77e-07)程度は通ること
        assert _problems(diff=4.77e-07) == []

    @pytest.mark.parametrize("diff", [math.nan, math.inf, 1.0, 1e-3])
    def test_large_or_nan_diff_is_problem(self, diff: float) -> None:
        problems = _problems(diff=diff)
        assert len(problems) == 1
        assert "絶対差" in problems[0]

    def test_default_tolerance_is_constant(self) -> None:
        assert _problems(diff=MAX_DIFF_RATIO_TOLERANCE * 1.5) != []
        assert _problems(diff=MAX_DIFF_RATIO_TOLERANCE * 0.5) == []

    def test_custom_tolerance(self) -> None:
        assert _problems(diff=0.01, ratio_tolerance=0.1) == []
        assert len(_problems(diff=0.2, ratio_tolerance=0.1)) == 1

    def test_negative_tolerance_rejects_even_zero_diff(self) -> None:
        assert len(_problems(diff=0.0, ratio_tolerance=-1.0)) == 1

    # --- 出力の大きさとの比 ---

    def test_ratio_exactly_at_tolerance_is_ok(self) -> None:
        scale = 200.0
        assert _problems(diff=MAX_DIFF_RATIO_TOLERANCE * scale, output_scale=scale) == []

    def test_ratio_just_above_tolerance_is_problem(self) -> None:
        scale = 200.0
        above = float(np.nextafter(MAX_DIFF_RATIO_TOLERANCE * scale, 1.0))
        problems = _problems(diff=above, output_scale=scale)
        assert len(problems) == 1
        assert "絶対差" in problems[0]

    def test_trained_weights_measurement_is_ok(self) -> None:
        # 原本の重みの実測(TEST_01: 出力の最大の絶対値 122.5・最大の絶対差 3.06e-4)は通る
        assert _problems(diff=3.06e-4, output_scale=122.5) == []

    @pytest.mark.parametrize("scale", [0.0, 1e-6, 0.5, 1.0])
    def test_scale_up_to_floor_uses_absolute_tolerance(self, scale: float) -> None:
        # 出力が小さいときは下限 1.0 を基準にする(従来の絶対差 1e-4 と同じ厳しさ)
        assert _problems(diff=1e-4, output_scale=scale) == []
        assert len(_problems(diff=float(np.nextafter(1e-4, 1.0)), output_scale=scale)) == 1

    def test_scale_above_floor_uses_ratio(self) -> None:
        assert _problems(diff=2e-4, output_scale=2.0) == []
        assert len(_problems(diff=float(np.nextafter(2e-4, 1.0)), output_scale=2.0)) == 1

    def test_custom_scale_floor(self) -> None:
        assert _problems(diff=1e-3, output_scale=0.5, scale_floor=10.0) == []
        assert len(_problems(diff=1e-3, output_scale=0.5, scale_floor=1.0)) == 1

    @pytest.mark.parametrize("scale", [math.nan, math.inf])
    def test_nan_or_inf_scale_is_problem(self, scale: float) -> None:
        problems = _problems(diff=0.0, output_scale=scale)
        assert len(problems) == 1
        assert "絶対差" in problems[0]

    # --- 2 値のマスク ---

    def test_mask_mismatch_at_limit_is_ok(self) -> None:
        assert _problems(mask_mismatch=MASK_LIMIT) == []

    def test_mask_mismatch_one_above_limit_is_problem(self) -> None:
        problems = _problems(mask_mismatch=MASK_LIMIT + 1)
        assert len(problems) == 1
        assert "マスク" in problems[0]

    def test_mask_not_compared_is_problem(self) -> None:
        problems = _problems(mask_mismatch=None)
        assert len(problems) == 1
        assert "マスク" in problems[0]

    def test_mask_and_diff_reported_separately(self) -> None:
        assert len(_problems(diff=1.0, mask_mismatch=MASK_LIMIT + 1)) == 2

    def test_all_problems_reported_together(self) -> None:
        info = OnnxModelInfo(opset=9, inputs=(), outputs=())
        problems = _problems(
            info,
            runtime_output_shape=(1, 1, 8, 8),
            runtime_output_dtype="float64",
            diff=math.nan,
            mask_mismatch=None,
        )
        assert len(problems) == 7


# ---------------------------------------------------------------------------
# 書き出しの記録
# ---------------------------------------------------------------------------


def _record(**overrides: Any) -> dict[str, Any]:
    kwargs: dict[str, Any] = {
        "onnx_file": "checkpoints/ResUNet.onnx",
        "exporter": "torchscript",
        "torch_version": "2.15.0",
        "check_input_seed": 0,
        "diff": 4.77e-07,
        "output_scale": 0.5,
        "mask_mismatch": 1,
        "mask_mismatch_limit": MASK_LIMIT,
        "file_bytes": 71_000_000,
        "elapsed_seconds": 2.5,
    }
    kwargs.update(overrides)
    return build_export_record(_info(), **kwargs)


class TestBuildExportRecord:
    def test_contents(self) -> None:
        assert _record() == {
            "onnx_file": "checkpoints/ResUNet.onnx",
            "exporter": "torchscript",
            "torch_version": "2.15.0",
            "opset": 11,
            "inputs": [{"name": "input.1", "shape": [1, 3, 256, 256], "dtype": "float32"}],
            "outputs": [{"name": "269", "shape": [1, 2, 256, 256], "dtype": "float32"}],
            "check_input_seed": 0,
            "max_abs_diff": 4.77e-07,
            "output_max_abs": 0.5,
            "output_scale_floor": 1.0,
            "max_abs_diff_ratio": 4.77e-07,
            "max_abs_diff_ratio_tolerance": 1e-4,
            "max_abs_diff_limit": 1e-4,
            "mask_mismatch_pixels": 1,
            "mask_mismatch_limit": MASK_LIMIT,
            "file_bytes": 71_000_000,
            "elapsed_seconds": 2.5,
        }

    def test_tensor_spec_to_dict_keeps_dim_names(self) -> None:
        spec = TensorSpec("x", ("batch", 3, 64, 64), "float32")
        assert spec.to_dict() == {"name": "x", "shape": ["batch", 3, 64, 64], "dtype": "float32"}

    def test_written_as_strict_json(self, tmp_path: Path) -> None:
        path = write_metrics_json(tmp_path / "metrics.json", {"export": _record()})
        assert json.loads(path.read_text(encoding="utf-8"))["export"] == _record()

    def test_nan_diff_is_written_as_null(self, tmp_path: Path) -> None:
        path = write_metrics_json(tmp_path / "metrics.json", {"export": _record(diff=math.nan)})
        assert json.loads(path.read_text(encoding="utf-8"))["export"]["max_abs_diff"] is None

    def test_record_uses_ratio_for_large_outputs(self) -> None:
        record = _record(diff=3.06e-4, output_scale=122.5)
        assert record["output_max_abs"] == 122.5
        assert record["max_abs_diff_ratio"] == pytest.approx(3.06e-4 / 122.5)
        assert record["max_abs_diff_limit"] == pytest.approx(1e-4 * 122.5)

    def test_non_finite_and_uncompared_are_written_as_null(self, tmp_path: Path) -> None:
        record = _record(mask_mismatch=None, diff=math.nan, output_scale=math.nan)
        path = write_metrics_json(tmp_path / "metrics.json", {"export": record})
        written = json.loads(path.read_text(encoding="utf-8"))["export"]
        assert written["mask_mismatch_pixels"] is None
        assert written["max_abs_diff_ratio"] is None
        assert written["max_abs_diff_limit"] is None
        assert written["output_max_abs"] is None


# ---------------------------------------------------------------------------
# 比・マスクの補助関数
# ---------------------------------------------------------------------------


class TestOutputMaxAbs:
    def test_known_value(self) -> None:
        assert output_max_abs(np.array([[1.0, -3.5], [2.0, 0.0]], dtype=np.float32)) == 3.5

    def test_nan_propagates(self) -> None:
        assert math.isnan(output_max_abs(np.array([1.0, np.nan], dtype=np.float32)))

    def test_inf(self) -> None:
        assert output_max_abs(np.array([1.0, -np.inf], dtype=np.float32)) == math.inf

    def test_empty_is_zero(self) -> None:
        assert output_max_abs(np.zeros((0, 2), dtype=np.float32)) == 0.0


class TestAllowedMaxAbsDiff:
    def test_ratio_times_scale(self) -> None:
        assert allowed_max_abs_diff(200.0) == pytest.approx(0.02)

    def test_floor(self) -> None:
        assert allowed_max_abs_diff(0.0) == 1e-4
        assert allowed_max_abs_diff(0.3) == 1e-4

    @pytest.mark.parametrize("scale", [math.nan, math.inf, -math.inf])
    def test_non_finite_scale_is_nan(self, scale: float) -> None:
        assert math.isnan(allowed_max_abs_diff(scale))


class TestMaxAbsDiffRatio:
    def test_divides_by_scale(self) -> None:
        assert max_abs_diff_ratio(0.02, 200.0) == pytest.approx(1e-4)

    def test_floor(self) -> None:
        assert max_abs_diff_ratio(5e-5, 0.0) == 5e-5

    @pytest.mark.parametrize(("diff", "scale"), [(math.nan, 1.0), (1.0, math.nan), (math.inf, 1.0)])
    def test_non_finite_is_nan(self, diff: float, scale: float) -> None:
        assert math.isnan(max_abs_diff_ratio(diff, scale))


class TestMaskMismatch:
    def test_count(self) -> None:
        a = np.array([[0, 255], [255, 0]], dtype=np.uint8)
        b = np.array([[0, 0], [255, 255]], dtype=np.uint8)
        assert count_mask_mismatch(a, b) == 2
        assert count_mask_mismatch(a, a.copy()) == 0

    def test_returns_python_int(self) -> None:
        a = np.zeros((2, 2), dtype=np.uint8)
        assert type(count_mask_mismatch(a, a)) is int

    def test_shape_mismatch_raises(self) -> None:
        with pytest.raises(RuntimeError):
            count_mask_mismatch(np.zeros((4, 4)), np.zeros((4, 5)))

    def test_limit_is_floor_of_ratio(self) -> None:
        assert max_mask_mismatch(256 * 256) == 65
        assert max_mask_mismatch(64 * 64) == 4
        assert max_mask_mismatch(1000) == 1
        assert max_mask_mismatch(999) == 0