Newer
Older
TongueSegModel / tests / scripts / test_compare_original_weights.py
"""原本の重みでの新旧比較のスクリプト(`scripts/compare_original_weights.py`)の純粋な部分のテスト.

期待値は SPEC_02「ONNX の書き出し」(PyTorch と onnxruntime の差は出力の大きさとの比 1e-4・
基準の下限 1.0・2 値のマスクは画素の 0.1% 以下.許容値は `export/check.py` と同じ値を使う)と,
TEST_01 の手順(`weights_only=True` で読み,モデル全体の pickle は読まずに止める・`strict=True` で
読み込む・BatchNorm を畳み込んだ値 `W × γ / √(var + eps)`・`β − mean × γ / √(var + eps)` で
初期値と照合する・終了コード 0 / 1 / 2 / 3)を基準にする.

**原本の重み・配布中の ONNX(`legacy/`)は読まない**.スクリプトを既定のパスで実行しない.
重みは `ResUNet(pretrained=False)` の state_dict(BatchNorm の統計を乱数で変えたもの),ONNX は
`onnx.helper` の小さなグラフか,その state_dict から書き出したものを `tmp_path` に作って使う.
書き出しを回すテストは `slow`.
"""

from __future__ import annotations

import importlib.util
import math
import sys
import tempfile
from collections.abc import Iterator
from dataclasses import dataclass
from pathlib import Path
from types import ModuleType

import cv2
import numpy as np
import onnx
import pytest
import torch
from onnx import TensorProto, helper, numpy_helper
from torch import nn
from torch.nn import functional

from tongue_seg_model.data.synthetic import write_synthetic_bundle
from tongue_seg_model.export.check import MAX_DIFF_RATIO_TOLERANCE
from tongue_seg_model.export.onnx_export import export_to_onnx
from tongue_seg_model.models.resunet import ResUNet

SCRIPT = Path(__file__).resolve().parents[2] / "scripts" / "compare_original_weights.py"
_MODULE_NAME = "compare_original_weights_under_test"


def _load_script() -> ModuleType:
    spec = importlib.util.spec_from_file_location(_MODULE_NAME, SCRIPT)
    assert spec is not None and spec.loader is not None
    module = importlib.util.module_from_spec(spec)
    sys.modules[_MODULE_NAME] = module  # dataclass が自分のモジュールを引くため
    spec.loader.exec_module(module)
    return module


cow = _load_script()


def _model(seed: int = 0) -> ResUNet:
    """BatchNorm の統計・係数を乱数で変えた ResUNet(畳み込みの影響が出るようにする)."""
    torch.manual_seed(seed)
    model = ResUNet(pretrained=False)
    generator = torch.Generator().manual_seed(seed + 100)
    with torch.no_grad():
        for module in model.modules():
            if isinstance(module, nn.BatchNorm2d):
                n = module.num_features
                module.running_mean.copy_(torch.rand(n, generator=generator) - 0.5)
                module.running_var.copy_(torch.rand(n, generator=generator) * 1.5 + 0.5)
                module.weight.copy_(torch.rand(n, generator=generator) + 0.5)
                module.bias.copy_(torch.rand(n, generator=generator) - 0.5)
    model.eval()
    return model


def _base_bn_names(model: ResUNet) -> list[str]:
    return [
        f"base_model.{name}"
        for name, module in model.base_model.named_modules()
        if isinstance(module, nn.BatchNorm2d)
    ]


def _random_input(seed: int, shape: tuple[int, ...]) -> torch.Tensor:
    return torch.from_numpy(np.random.default_rng(seed).random(shape).astype(np.float32))


# ---------------------------------------------------------------------------
# 定数(tsm-export と同じ基準を使う)
# ---------------------------------------------------------------------------


def test_constants() -> None:
    assert cow.EXIT_OK == 0
    assert cow.EXIT_INPUT_ERROR == 1
    assert cow.EXIT_DIFF_EXCEEDED == 3
    assert cow.IMAGE_SIZE == (256, 256)
    assert cow.OPSET == 11
    assert cow.MAX_DIFF_RATIO_TOLERANCE is MAX_DIFF_RATIO_TOLERANCE


def test_bn_eps_is_same_as_resnet() -> None:
    model = ResUNet(pretrained=False)
    assert {m.eps for m in model.modules() if isinstance(m, nn.BatchNorm2d)} == {cow.BN_EPS}


# ---------------------------------------------------------------------------
# _layer_key_to_base_key
# ---------------------------------------------------------------------------


class TestLayerKeyToBaseKey:
    @pytest.mark.parametrize(
        ("key", "expected"),
        [
            ("layer0.0.weight", "base_model.conv1.weight"),
            ("layer0.1.running_var", "base_model.bn1.running_var"),
            ("layer1.1.0.conv1.weight", "base_model.layer1.0.conv1.weight"),
            ("layer1.1.1.bn2.bias", "base_model.layer1.1.bn2.bias"),
            ("layer2.0.downsample.1.weight", "base_model.layer2.0.downsample.1.weight"),
            ("layer4.1.conv2.weight", "base_model.layer4.1.conv2.weight"),
        ],
    )
    def test_known_keys(self, key: str, expected: str) -> None:
        assert cow._layer_key_to_base_key(key) == expected

    def test_every_layer_key_points_to_same_tensor(self) -> None:
        # ResUNet の layer0〜layer4 は base_model の部品を共有する.対応先は同じテンソルであること
        state = ResUNet(pretrained=False).state_dict(keep_vars=True)
        layer_keys = [k for k in state if k.startswith("layer") and "_1x1" not in k]
        assert len(layer_keys) > 0
        for key in layer_keys:
            base_key = cow._layer_key_to_base_key(key)
            assert base_key in state, key
            assert state[base_key] is state[key], key

    def test_every_base_layer_key_is_covered(self) -> None:
        # base_model の conv1〜layer4 のキーは,どれかの layer*.* から対応が付く(漏れが無い)
        state = ResUNet(pretrained=False).state_dict()
        mapped = {
            cow._layer_key_to_base_key(k)
            for k in state
            if k.startswith("layer") and "_1x1" not in k
        }
        base_keys = {
            k
            for k in state
            if k.startswith(("base_model.conv1", "base_model.bn1", "base_model.layer"))
        }
        assert base_keys <= mapped


# ---------------------------------------------------------------------------
# _reference_tensors(BatchNorm を畳み込んだ値)
# ---------------------------------------------------------------------------


class TestReferenceTensors:
    @pytest.fixture(scope="class")
    def model(self) -> ResUNet:
        return _model(0)

    @pytest.fixture(scope="class")
    def refs(self, model: ResUNet) -> dict[str, np.ndarray]:
        return cow._reference_tensors(model.state_dict())

    def test_float_tensors_are_kept_and_ints_dropped(
        self, model: ResUNet, refs: dict[str, np.ndarray]
    ) -> None:
        for key, value in model.state_dict().items():
            if value.dtype.is_floating_point:
                assert refs[key].dtype == np.float64
                np.testing.assert_array_equal(refs[key], value.numpy().astype(np.float64))
            else:
                assert key not in refs  # num_batches_tracked

    def test_every_base_batchnorm_is_fused(
        self, model: ResUNet, refs: dict[str, np.ndarray]
    ) -> None:
        bns = _base_bn_names(model)
        assert len(bns) == 20  # resnet18 の BatchNorm
        fused = {k.rsplit(".", 1)[0] for k in refs if k.endswith((".fused_weight", ".fused_bias"))}
        assert fused == set(bns)

    def test_fused_values_follow_formula(self, model: ResUNet, refs: dict[str, np.ndarray]) -> None:
        modules = dict(model.named_modules())
        for bn_name in _base_bn_names(model):
            conv_name = bn_name.replace(".bn", ".conv").replace("downsample.1", "downsample.0")
            bn = modules[bn_name]
            conv = modules[conv_name]
            gamma = bn.weight.detach().double().numpy()
            beta = bn.bias.detach().double().numpy()
            mean = bn.running_mean.double().numpy()
            var = bn.running_var.double().numpy()
            scale = gamma / np.sqrt(var + 1e-5)
            weight = conv.weight.detach().double().numpy() * scale.reshape(-1, 1, 1, 1)
            np.testing.assert_allclose(
                refs[f"{bn_name}.fused_weight"], weight, rtol=1e-5, atol=1e-7
            )
            np.testing.assert_allclose(
                refs[f"{bn_name}.fused_bias"], beta - mean * scale, rtol=1e-5, atol=1e-6
            )

    @pytest.mark.parametrize(
        ("conv_name", "bn_name"),
        [
            ("conv1", "bn1"),
            ("layer1.0.conv2", "layer1.0.bn2"),
            ("layer3.0.downsample.0", "layer3.0.downsample.1"),
        ],
    )
    def test_fused_conv_equals_conv_then_bn(
        self, model: ResUNet, refs: dict[str, np.ndarray], conv_name: str, bn_name: str
    ) -> None:
        modules = dict(model.base_model.named_modules())
        conv = modules[conv_name]
        bn = modules[bn_name]
        x = _random_input(0, (1, conv.in_channels, 16, 16))
        with torch.no_grad():
            expected = bn(conv(x))
            actual = functional.conv2d(
                x,
                torch.from_numpy(refs[f"base_model.{bn_name}.fused_weight"]).float(),
                torch.from_numpy(refs[f"base_model.{bn_name}.fused_bias"]).float(),
                stride=conv.stride,
                padding=conv.padding,
            )
        torch.testing.assert_close(actual, expected, rtol=1e-4, atol=1e-5)


# ---------------------------------------------------------------------------
# _fuse_batchnorm
# ---------------------------------------------------------------------------


class TestFuseBatchnorm:
    def test_output_is_unchanged(self) -> None:
        model = _model(1)
        fused = cow._fuse_batchnorm(model)
        x = _random_input(1, (1, 3, 64, 64))
        with torch.no_grad():
            expected = model(x)
            actual = fused(x)
        scale = float(expected.abs().max())
        assert float((actual - expected).abs().max()) <= 1e-4 * max(scale, 1.0)

    def test_original_model_is_not_modified(self) -> None:
        model = _model(2)
        before = {k: v.clone() for k, v in model.state_dict().items()}
        cow._fuse_batchnorm(model)
        after = model.state_dict()
        for key, value in before.items():
            assert torch.equal(after[key], value), key

    def test_fused_batchnorms_are_identity_plus_bias(self) -> None:
        fused = cow._fuse_batchnorm(_model(3))
        assert not fused.training
        for module in fused.base_model.modules():
            if isinstance(module, nn.BatchNorm2d):
                assert module.eps == 0.0
                assert torch.all(module.weight == 1.0)
                assert torch.all(module.running_mean == 0.0)
                assert torch.all(module.running_var == 1.0)

    def test_layer_modules_share_fused_parts(self) -> None:
        # layer0〜layer4 も base_model を共有するので,畳み込んだ値が効いている
        fused = cow._fuse_batchnorm(_model(4))
        assert fused.layer0[0] is fused.base_model.conv1
        assert fused.layer0[1].eps == 0.0


# ---------------------------------------------------------------------------
# _load_original_state_dict(保存形式の判定)
# ---------------------------------------------------------------------------


def _small_state() -> dict[str, torch.Tensor]:
    torch.manual_seed(0)
    return nn.Linear(3, 2).state_dict()


class TestLoadOriginalStateDict:
    def test_missing_file_is_value_error(self, tmp_path: Path) -> None:
        with pytest.raises(ValueError, match="見つからない"):
            cow._load_original_state_dict(tmp_path / "none.pth")

    def test_directory_is_value_error(self, tmp_path: Path) -> None:
        with pytest.raises(ValueError):
            cow._load_original_state_dict(tmp_path)

    def test_plain_state_dict(self, tmp_path: Path) -> None:
        state = _small_state()
        torch.save(state, tmp_path / "w.pth")
        loaded = cow._load_original_state_dict(tmp_path / "w.pth")
        assert list(loaded) == list(state)
        for key, value in state.items():
            assert torch.equal(loaded[key], value)

    @pytest.mark.parametrize("wrapper", ["state_dict", "model_state_dict", "model"])
    def test_wrapped_state_dict(self, tmp_path: Path, wrapper: str) -> None:
        state = _small_state()
        torch.save({wrapper: state, "epoch": 3}, tmp_path / "w.pth")
        assert set(cow._load_original_state_dict(tmp_path / "w.pth")) == set(state)

    def test_module_prefix_is_removed(self, tmp_path: Path) -> None:
        state = _small_state()
        torch.save({f"module.{k}": v for k, v in state.items()}, tmp_path / "w.pth")
        assert set(cow._load_original_state_dict(tmp_path / "w.pth")) == set(state)

    def test_partial_module_prefix_is_kept(self, tmp_path: Path) -> None:
        torch.save({"module.a": torch.zeros(1), "b": torch.zeros(1)}, tmp_path / "w.pth")
        assert set(cow._load_original_state_dict(tmp_path / "w.pth")) == {"module.a", "b"}

    def test_whole_model_pickle_is_rejected(self, tmp_path: Path) -> None:
        # モデル全体の pickle は weights_only=True で読めない.読まずに ValueError で止める
        torch.save(nn.Linear(3, 2), tmp_path / "w.pth")
        with pytest.raises(ValueError, match="weights_only"):
            cow._load_original_state_dict(tmp_path / "w.pth")

    def test_broken_file_is_value_error(self, tmp_path: Path) -> None:
        (tmp_path / "w.pth").write_bytes(b"not a checkpoint")
        with pytest.raises(ValueError):
            cow._load_original_state_dict(tmp_path / "w.pth")

    def test_non_dict_is_value_error(self, tmp_path: Path) -> None:
        torch.save([torch.zeros(1)], tmp_path / "w.pth")
        with pytest.raises(ValueError, match="dict"):
            cow._load_original_state_dict(tmp_path / "w.pth")

    def test_dict_with_non_tensors_without_wrapper_is_value_error(self, tmp_path: Path) -> None:
        torch.save({"a": torch.zeros(1), "epoch": 3}, tmp_path / "w.pth")
        with pytest.raises(ValueError, match="テンソル以外"):
            cow._load_original_state_dict(tmp_path / "w.pth")


class TestStage1Load:
    def test_new_model_state_dict_loads_strictly(self, tmp_path: Path) -> None:
        model = _model(0)
        torch.save(model.state_dict(), tmp_path / "w.pth")
        loaded, state = cow._stage1_load(tmp_path / "w.pth")
        assert not loaded.training
        x = _random_input(0, (1, 3, 64, 64))
        with torch.no_grad():
            torch.testing.assert_close(loaded(x), model(x), rtol=0, atol=0)
        assert set(state) == set(model.state_dict())

    def test_missing_key_is_value_error(self, tmp_path: Path) -> None:
        state = ResUNet(pretrained=False).state_dict()
        state.pop("conv_last.weight")
        torch.save(state, tmp_path / "w.pth")
        with pytest.raises(ValueError, match="strict=True"):
            cow._stage1_load(tmp_path / "w.pth")

    def test_wrong_shape_is_value_error(self, tmp_path: Path) -> None:
        state = ResUNet(pretrained=False).state_dict()
        state["conv_last.bias"] = torch.zeros(3)
        torch.save(state, tmp_path / "w.pth")
        with pytest.raises(ValueError):
            cow._stage1_load(tmp_path / "w.pth")


# ---------------------------------------------------------------------------
# 初期値の照合(onnx.helper の小さなグラフ)
# ---------------------------------------------------------------------------


def _graph(initializers: dict[str, np.ndarray]) -> onnx.ModelProto:
    """Conv(初期値を入力にする)と,Conv でない演算(Add)の初期値を 1 つ持つグラフ."""
    nodes = [
        helper.make_node("Conv", ["x", *initializers], ["y"]),
        helper.make_node("Add", ["y", "c"], ["z"]),
    ]
    inits = [numpy_helper.from_array(v.astype(np.float32), name=k) for k, v in initializers.items()]
    inits.append(numpy_helper.from_array(np.zeros(1, dtype=np.float32), name="c"))
    graph = helper.make_graph(
        nodes,
        "g",
        [helper.make_tensor_value_info("x", TensorProto.FLOAT, None)],
        [helper.make_tensor_value_info("z", TensorProto.FLOAT, None)],
        initializer=inits,
    )
    return helper.make_model(graph, opset_imports=[helper.make_opsetid("", 11)])


class TestConvInitializers:
    def test_only_conv_inputs(self) -> None:
        proto = _graph({"w": np.zeros((2, 3, 3, 3)), "b": np.zeros(2)})
        assert cow._conv_initializer_names(proto) == {"w", "b"}

    def test_count_ops(self) -> None:
        assert cow._count_ops(_graph({"w": np.zeros((2, 3, 3, 3))})) == {"Add": 1, "Conv": 1}


class TestStage3Initializers:
    @pytest.fixture(scope="class")
    def state(self) -> dict[str, torch.Tensor]:
        return _model(0).state_dict()

    def test_fused_values_match_by_value(self, state: dict[str, torch.Tensor]) -> None:
        refs = cow._reference_tensors(state)
        proto = _graph(
            {
                "onnx::Conv_1": refs["base_model.layer2.0.bn1.fused_weight"],
                "onnx::Conv_2": refs["base_model.layer2.0.bn1.fused_bias"],
            }
        )
        assert cow._stage3_initializers(proto, state) is True

    def test_same_name_matches(self, state: dict[str, torch.Tensor]) -> None:
        proto = _graph(
            {
                "conv_last.weight": state["conv_last.weight"].numpy(),
                "conv_last.bias": state["conv_last.bias"].numpy(),
            }
        )
        assert cow._stage3_initializers(proto, state) is True

    def test_perturbed_values_do_not_match(self, state: dict[str, torch.Tensor]) -> None:
        refs = cow._reference_tensors(state)
        weight = refs["base_model.layer2.0.bn1.fused_weight"] + 1e-3
        assert cow._stage3_initializers(_graph({"onnx::Conv_1": weight}), state) is False

    def test_shape_without_candidate_does_not_match(self, state: dict[str, torch.Tensor]) -> None:
        assert cow._stage3_initializers(_graph({"w": np.ones((7, 5, 3, 3))}), state) is False


# ---------------------------------------------------------------------------
# _check_pair(判定)・_diff_stats・_binary_mask・_inputs
# ---------------------------------------------------------------------------


class TestCheckPair:
    def test_rel_at_limit_is_ok_and_above_is_not(self) -> None:
        limit = MAX_DIFF_RATIO_TOLERANCE * 200.0
        above = float(np.nextafter(limit, 1.0))
        assert cow._check_pair("x", "a-b", "rel", cow.DiffStats(limit, 0.0), 200.0) is True
        assert cow._check_pair("x", "a-b", "rel", cow.DiffStats(above, 0.0), 200.0) is False

    def test_rel_uses_floor_for_small_outputs(self) -> None:
        above = float(np.nextafter(1e-4, 1.0))
        assert cow._check_pair("x", "a-b", "rel", cow.DiffStats(1e-4, 0.0), 0.01) is True
        assert cow._check_pair("x", "a-b", "rel", cow.DiffStats(above, 0.0), 0.01) is False

    @pytest.mark.parametrize("value", [math.nan, math.inf])
    def test_rel_rejects_non_finite(self, value: float) -> None:
        assert cow._check_pair("x", "a-b", "rel", cow.DiffStats(value, 0.0), 1.0) is False
        assert cow._check_pair("x", "a-b", "rel", cow.DiffStats(0.0, 0.0), value) is False

    def test_abs_ignores_output_scale(self) -> None:
        tol = cow.ONNX_ABS_TOLERANCE
        above = float(np.nextafter(tol, 1.0))
        assert cow._check_pair("x", "b-c", "abs", cow.DiffStats(tol, 0.0), 1000.0) is True
        assert cow._check_pair("x", "b-c", "abs", cow.DiffStats(above, 0.0), 1000.0) is False
        assert cow._check_pair("x", "b-c", "abs", cow.DiffStats(math.nan, 0.0), 1.0) is False

    def test_record_only_pairs_never_fail(self) -> None:
        assert cow._check_pair("x", "a'-b", None, cow.DiffStats(1e9, 1e9), 1.0) is True

    def test_pairs_cover_required_comparisons(self) -> None:
        kinds = {name: kind for name, _, _, kind in cow._PAIRS}
        assert kinds["a-b"] == "rel"
        assert kinds["a-c"] == "rel"
        assert kinds["b-c"] == "abs"


def test_diff_stats() -> None:
    a = np.array([[0.0, 1.0], [2.0, 3.0]], dtype=np.float32)
    b = np.array([[0.0, 1.5], [2.0, 2.0]], dtype=np.float32)
    stats = cow._diff_stats(a, b)
    assert stats.max_abs == 1.0
    assert stats.mean_abs == pytest.approx(0.375)


def test_binary_mask_is_evaluation_postprocess() -> None:
    # SPEC_02: チャンネル 0 → シグモイド → 255 倍の切り捨て → 大津の 2 値化
    output = np.random.default_rng(0).normal(0, 3, size=(1, 2, 16, 16)).astype(np.float32)
    prob = 1.0 / (1.0 + np.exp(-output[0, 0].astype(np.float64)))
    image = np.floor(prob * 255).astype(np.uint8)
    _, expected = cv2.threshold(image, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
    np.testing.assert_array_equal(cow._binary_mask(output), expected)


class TestInputs:
    def test_without_synthetic_data(self, tmp_path: Path) -> None:
        inputs = cow._inputs(tmp_path / "none")
        labels = [label for label, _ in inputs]
        assert len(inputs) == len(cow.RANDOM_SEEDS) + 2
        assert len(set(labels)) == len(labels)
        values = [x for _, x in inputs]
        for x in values:
            assert x.shape == (1, 3, 256, 256)
            assert x.dtype == np.float32
        assert np.all(values[-2] == 0.0) and np.all(values[-1] == 1.0)
        for x in values[: len(cow.RANDOM_SEEDS)]:
            assert 0.0 <= x.min() and x.max() < 1.0

    def test_with_synthetic_data_uses_test_images(self, tmp_path: Path) -> None:
        write_synthetic_bundle(tmp_path, train_pairs=2, test_pairs=5, seed=0)
        inputs = cow._inputs(tmp_path)
        assert len(inputs) == len(cow.RANDOM_SEEDS) + 2 + cow.MAX_SYNTHETIC_IMAGES
        for label, x in inputs[-cow.MAX_SYNTHETIC_IMAGES :]:
            assert label.startswith("合成 test")
            assert x.shape == (1, 3, 256, 256) and x.dtype == np.float32
            assert x.flags["C_CONTIGUOUS"]


# ---------------------------------------------------------------------------
# main(引数・終了コード)
# ---------------------------------------------------------------------------


def _argv(weights: Path, onnx_path: Path, synthetic: Path) -> list[str]:
    return ["--weights", str(weights), "--onnx", str(onnx_path), "--synthetic-dir", str(synthetic)]


class TestMainArguments:
    def test_unknown_option_exits_with_2(self) -> None:
        with pytest.raises(SystemExit) as info:
            cow.main(["--unknown"])
        assert info.value.code == 2

    def test_option_without_value_exits_with_2(self) -> None:
        with pytest.raises(SystemExit) as info:
            cow.main(["--weights"])
        assert info.value.code == 2

    def test_defaults_point_to_legacy(self) -> None:
        # 既定のパスで実行はしない(値だけ確かめる)
        args = cow._parse_args([])
        assert args.weights == cow.DEFAULT_WEIGHTS
        assert args.onnx == cow.DEFAULT_ONNX


class TestMainInputErrors:
    def test_missing_weights_exits_with_1(self, tmp_path: Path) -> None:
        argv = _argv(tmp_path / "none.pth", tmp_path / "none.onnx", tmp_path / "syn")
        assert cow.main(argv) == 1

    def test_whole_model_pickle_exits_with_1(self, tmp_path: Path) -> None:
        torch.save(nn.Linear(3, 2), tmp_path / "w.pth")
        assert cow.main(_argv(tmp_path / "w.pth", tmp_path / "none.onnx", tmp_path / "syn")) == 1

    def test_mismatched_weights_exit_with_1(self, tmp_path: Path) -> None:
        torch.save(_small_state(), tmp_path / "w.pth")
        assert cow.main(_argv(tmp_path / "w.pth", tmp_path / "none.onnx", tmp_path / "syn")) == 1

    def test_missing_onnx_exits_with_1(self, tmp_path: Path) -> None:
        torch.save(_model(0).state_dict(), tmp_path / "w.pth")
        assert cow.main(_argv(tmp_path / "w.pth", tmp_path / "none.onnx", tmp_path / "syn")) == 1


# ---------------------------------------------------------------------------
# main(書き出しを回す.slow)
# ---------------------------------------------------------------------------


@dataclass(frozen=True)
class Files:
    weights: Path
    same_onnx: Path
    other_onnx: Path
    root: Path


@pytest.fixture(scope="module")
def files(tmp_path_factory: pytest.TempPathFactory) -> Iterator[Files]:
    """BatchNorm の統計を変えた重みと,それを書き出した ONNX・別の重みの ONNX を作る."""
    root = tmp_path_factory.mktemp("compare")
    model = _model(0)
    weights = root / "weights.pth"
    torch.save(model.state_dict(), weights)
    same = root / "same.onnx"
    other = root / "other.onnx"
    export_to_onnx(model, same, input_shape=(1, 3, 256, 256), opset=11)
    export_to_onnx(_model(7), other, input_shape=(1, 3, 256, 256), opset=11)
    yield Files(weights=weights, same_onnx=same, other_onnx=other, root=root)
    for path in (weights, same, other):
        path.unlink(missing_ok=True)


@pytest.mark.slow
def test_main_passes_with_onnx_from_same_weights(
    files: Files, caplog: pytest.LogCaptureFixture
) -> None:
    caplog.set_level("INFO")
    before = set(Path(tempfile.gettempdir()).glob("tsm-compare-*"))
    assert cow.main(_argv(files.weights, files.same_onnx, files.root / "syn")) == 0
    # BatchNorm を畳み込んだ初期値も含め,すべて重みと対応が付く
    assert "対応する: True" in caplog.text
    assert "対応無し 0" in caplog.text
    # 書き出した ONNX の一時フォルダは消える
    assert set(Path(tempfile.gettempdir()).glob("tsm-compare-*")) == before


@pytest.mark.slow
def test_main_exits_with_3_for_onnx_from_other_weights(
    files: Files, caplog: pytest.LogCaptureFixture
) -> None:
    caplog.set_level("INFO")
    assert cow.main(_argv(files.weights, files.other_onnx, files.root / "syn")) == 3
    assert "対応する: False" in caplog.text