Newer
Older
TongueSegModel / tests / models / test_resunet.py
@rintoHasegawa rintoHasegawa 11 days ago 14 KB [add] ResUNet のモデルを追加
"""ResUNet(`models/resunet.py`)のテスト.

期待値は SPEC_02「モデル」と原本(`legacy/source/models.py` の `ResNetUNet`)を基準にする.
原本は import できないため,同じフォルダの `original_resnetunet.py` に書き写した参照実装と比べる.
事前学習の重みはダウンロードしない(`pretrained=False` か,`tmp_path` に置いた重みを使う.
`pretrained=True` で場所の指定が無い経路は torchvision の関数を差し替えて確かめる).
"""

from __future__ import annotations

from collections.abc import Callable
from pathlib import Path

import pytest
import torch
from original_resnetunet import ResNetUNet
from torchvision.models import ResNet18_Weights, resnet18

from tongue_seg_model.models import (
    NUM_CLASSES,
    TONGUE_CHANNEL,
    ResUNet,
    build_model,
)
from tongue_seg_model.models import resunet as resunet_module
from tongue_seg_model.schema import ModelConfig

SEED = 0


def _seeded_original() -> ResNetUNet:
    torch.manual_seed(SEED)
    return ResNetUNet(n_class=2)


def _seeded_model() -> ResUNet:
    torch.manual_seed(SEED)
    return ResUNet(pretrained=False)


def _rand(*shape: int) -> torch.Tensor:
    return torch.rand(*shape, generator=torch.Generator().manual_seed(SEED))


def _decoder_keys() -> list[str]:
    """原本の `ResNetUNet.__init__` で最後に足している層のキー(登録順).

    `legacy/source/models.py` を読んで書いた期待値.
    """
    keys: list[str] = []
    for name in [
        "conv_up3",
        "conv_up2",
        "conv_up1",
        "conv_up0",
        "conv_original_size0",
        "conv_original_size1",
        "conv_original_size2",
    ]:
        keys += [f"{name}.0.weight", f"{name}.0.bias"]
    keys += ["conv_last.weight", "conv_last.bias"]
    return keys


def _expected_keys() -> list[str]:
    """原本の `ResNetUNet(n_class=2)` の `state_dict` のキー(順序つき).

    原本の `__init__` の登録順: `base_model`(resnet18 全体)→ `layer0`(conv1・bn1・relu)
    → `layer0_1x1` → `layer1`(maxpool・layer1)→ `layer1_1x1` → `layer2` → `layer2_1x1`
    → `layer3` → `layer3_1x1` → `layer4` → `layer4_1x1` → デコーダ(`_decoder_keys`).
    """
    base = list(resnet18(weights=None).state_dict().keys())

    def sub(prefix: str) -> list[str]:
        return [k[len(prefix) :] for k in base if k.startswith(prefix)]

    keys = [f"base_model.{k}" for k in base]
    keys += [f"layer0.0.{k}" for k in sub("conv1.")]
    keys += [f"layer0.1.{k}" for k in sub("bn1.")]
    keys += ["layer0_1x1.0.weight", "layer0_1x1.0.bias"]
    keys += [f"layer1.1.{k}" for k in sub("layer1.")]
    keys += ["layer1_1x1.0.weight", "layer1_1x1.0.bias"]
    for i in (2, 3, 4):
        keys += [k for k in base if k.startswith(f"layer{i}.")]
        keys += [f"layer{i}_1x1.0.weight", f"layer{i}_1x1.0.bias"]
    keys += _decoder_keys()
    return keys


@pytest.fixture
def resnet18_calls(monkeypatch: pytest.MonkeyPatch) -> list[object]:
    """`resunet` の `resnet18` を差し替え,渡された `weights` を記録する(ダウンロードしない)."""
    calls: list[object] = []
    real: Callable[..., torch.nn.Module] = resnet18

    def fake(*, weights: object = None, **kwargs: object) -> torch.nn.Module:
        calls.append(weights)
        return real(weights=None, **kwargs)

    monkeypatch.setattr(resunet_module, "resnet18", fake)
    return calls


# ---------------------------------------------------------------------------
# 定数
# ---------------------------------------------------------------------------


def test_num_classes_is_two() -> None:
    assert NUM_CLASSES == 2


def test_tongue_is_channel_zero() -> None:
    assert TONGUE_CHANNEL == 0


# ---------------------------------------------------------------------------
# state_dict のキー(原本と同じであること)
# ---------------------------------------------------------------------------


class TestStateDictKeys:
    def test_keys_match_original_in_order(self) -> None:
        model_keys = list(ResUNet(pretrained=False).state_dict().keys())
        original_keys = list(ResNetUNet(n_class=2).state_dict().keys())
        assert model_keys == original_keys

    def test_keys_match_list_written_from_original(self) -> None:
        assert list(ResUNet(pretrained=False).state_dict().keys()) == _expected_keys()

    def test_key_count_is_268(self) -> None:
        assert len(ResUNet(pretrained=False).state_dict()) == 268

    def test_keeps_unused_resnet_head(self) -> None:
        # 原本は resnet18 全体を base_model に持つため,使わない fc の重みもキーにある.
        keys = ResUNet(pretrained=False).state_dict().keys()
        assert "base_model.fc.weight" in keys
        assert "base_model.fc.bias" in keys

    def test_last_keys_are_conv_last(self) -> None:
        keys = list(ResUNet(pretrained=False).state_dict().keys())
        assert keys[-2:] == ["conv_last.weight", "conv_last.bias"]

    def test_shapes_match_original(self) -> None:
        model_sd = ResUNet(pretrained=False).state_dict()
        original_sd = ResNetUNet(n_class=2).state_dict()
        for key, value in original_sd.items():
            assert model_sd[key].shape == value.shape, key

    def test_encoder_and_layers_share_tensors(self) -> None:
        model = ResUNet(pretrained=False)
        assert model.layer0[0].weight is model.base_model.conv1.weight
        assert model.layer4 is model.base_model.layer4

    def test_loads_original_state_dict_strictly(self) -> None:
        original = _seeded_original()
        model = ResUNet(pretrained=False)
        model.load_state_dict(original.state_dict(), strict=True)
        model_sd = model.state_dict()
        for key, value in original.state_dict().items():
            assert torch.equal(model_sd[key], value), key


# ---------------------------------------------------------------------------
# forward(出力の形・原本との一致)
# ---------------------------------------------------------------------------


class TestForward:
    @pytest.mark.parametrize("batch", [1, 2, 3])
    @pytest.mark.parametrize("size", [(64, 64), (32, 96)])
    def test_output_shape(self, batch: int, size: tuple[int, int]) -> None:
        model = _seeded_model().eval()
        with torch.no_grad():
            out = model(_rand(batch, 3, *size))
        assert out.shape == (batch, 2, *size)
        assert out.dtype == torch.float32

    @pytest.mark.slow
    @pytest.mark.parametrize("batch", [1, 2])
    def test_output_shape_256(self, batch: int) -> None:
        model = _seeded_model().eval()
        with torch.no_grad():
            out = model(_rand(batch, 3, 256, 256))
        assert out.shape == (batch, 2, 256, 256)

    def test_output_is_before_activation(self) -> None:
        # 活性化関数を掛ける前の値なので,[0, 1] に収まらない値も出る.
        model = _seeded_model().eval()
        with torch.no_grad():
            model.conv_last.bias.fill_(5.0)
            out = model(torch.zeros(1, 3, 64, 64))
        assert out.max().item() > 1.0

    @pytest.mark.parametrize("size", [(64, 64), (96, 128)])
    def test_matches_original_with_same_weights(self, size: tuple[int, int]) -> None:
        original = _seeded_original().eval()
        model = ResUNet(pretrained=False).eval()
        model.load_state_dict(original.state_dict(), strict=True)
        x = _rand(2, 3, *size)
        with torch.no_grad():
            expected = original(x)
            actual = model(x)
        assert torch.allclose(actual, expected, atol=1e-6)

    def test_matches_original_in_train_mode(self) -> None:
        # BatchNorm がバッチの統計を使う学習モードでも同じ計算になること.
        original = _seeded_original().train()
        model = ResUNet(pretrained=False).train()
        model.load_state_dict(original.state_dict(), strict=True)
        x = _rand(2, 3, 64, 64)
        assert torch.allclose(model(x), original(x), atol=1e-6)

    def test_same_seed_gives_same_initial_weights_as_original(self) -> None:
        original_sd = _seeded_original().state_dict()
        model_sd = _seeded_model().state_dict()
        for key, value in original_sd.items():
            assert torch.equal(model_sd[key], value), key

    def test_new_model_is_on_cpu_and_in_train_mode(self) -> None:
        model = ResUNet(pretrained=False)
        assert model.training
        assert all(p.device.type == "cpu" for p in model.parameters())


# ---------------------------------------------------------------------------
# 事前学習の重み
# ---------------------------------------------------------------------------


class _NotAllowedInWeightsOnly:
    """`weights_only=True` では読めない(任意の pickle オブジェクト)ことを確かめるための型."""


def _save_resnet18_weights(path: Path) -> dict[str, torch.Tensor]:
    torch.manual_seed(123)
    state_dict = resnet18(weights=None).state_dict()
    torch.save(state_dict, path)
    return state_dict


class TestPretrainedWeights:
    def test_loads_weights_from_file(self, tmp_path: Path) -> None:
        path = tmp_path / "resnet18.pth"
        saved = _save_resnet18_weights(path)
        model = ResUNet(pretrained=True, pretrained_weights=path)
        encoder_sd = model.base_model.state_dict()
        for key, value in saved.items():
            assert torch.equal(encoder_sd[key], value), key
        # layer0 等も同じ重みを使う.
        assert torch.equal(model.layer0[0].weight, saved["conv1.weight"])

    def test_file_weights_do_not_download(
        self, tmp_path: Path, resnet18_calls: list[object]
    ) -> None:
        path = tmp_path / "resnet18.pth"
        _save_resnet18_weights(path)
        ResUNet(pretrained=True, pretrained_weights=path)
        assert resnet18_calls == [None]

    def test_pretrained_without_path_requests_imagenet_weights(
        self, resnet18_calls: list[object]
    ) -> None:
        ResUNet(pretrained=True)
        assert resnet18_calls == [ResNet18_Weights.IMAGENET1K_V1]

    def test_not_pretrained_requests_no_weights(self, resnet18_calls: list[object]) -> None:
        ResUNet(pretrained=False)
        assert resnet18_calls == [None]

    def test_missing_file_is_value_error(self, tmp_path: Path) -> None:
        with pytest.raises(ValueError):
            ResUNet(pretrained=True, pretrained_weights=tmp_path / "missing.pth")

    def test_directory_is_value_error(self, tmp_path: Path) -> None:
        with pytest.raises(ValueError):
            ResUNet(pretrained=True, pretrained_weights=tmp_path)

    def test_weights_with_pretrained_false_is_value_error(self, tmp_path: Path) -> None:
        path = tmp_path / "resnet18.pth"
        _save_resnet18_weights(path)
        with pytest.raises(ValueError):
            ResUNet(pretrained=False, pretrained_weights=path)

    def test_corrupt_file_is_value_error(self, tmp_path: Path) -> None:
        path = tmp_path / "broken.pth"
        path.write_bytes(b"this is not a torch file")
        with pytest.raises(ValueError):
            ResUNet(pretrained=True, pretrained_weights=path)

    def test_arbitrary_pickle_is_value_error(self, tmp_path: Path) -> None:
        path = tmp_path / "pickle.pth"
        torch.save({"obj": _NotAllowedInWeightsOnly()}, path)
        with pytest.raises(ValueError):
            ResUNet(pretrained=True, pretrained_weights=path)

    def test_mismatched_keys_is_value_error(self, tmp_path: Path) -> None:
        path = tmp_path / "other.pth"
        torch.save(torch.nn.Conv2d(3, 8, 3).state_dict(), path)
        with pytest.raises(ValueError):
            ResUNet(pretrained=True, pretrained_weights=path)

    def test_partial_resnet_weights_is_value_error(self, tmp_path: Path) -> None:
        path = tmp_path / "partial.pth"
        state_dict = resnet18(weights=None).state_dict()
        del state_dict["fc.weight"]
        torch.save(state_dict, path)
        with pytest.raises(ValueError):
            ResUNet(pretrained=True, pretrained_weights=path)

    def test_mismatched_shapes_is_value_error(self, tmp_path: Path) -> None:
        path = tmp_path / "resnet18_10cls.pth"
        torch.save(resnet18(weights=None, num_classes=10).state_dict(), path)
        with pytest.raises(ValueError):
            ResUNet(pretrained=True, pretrained_weights=path)

    def test_non_dict_content_is_value_error(self, tmp_path: Path) -> None:
        path = tmp_path / "tensor.pth"
        torch.save(torch.zeros(3), path)
        with pytest.raises(ValueError):
            ResUNet(pretrained=True, pretrained_weights=path)


# ---------------------------------------------------------------------------
# build_model
# ---------------------------------------------------------------------------


class TestBuildModel:
    def test_builds_resunet_without_pretrained(self, resnet18_calls: list[object]) -> None:
        model = build_model(ModelConfig(pretrained=False))
        assert isinstance(model, ResUNet)
        assert resnet18_calls == [None]
        assert list(model.state_dict().keys()) == _expected_keys()

    def test_default_config_requests_imagenet_weights(self, resnet18_calls: list[object]) -> None:
        build_model(ModelConfig())
        assert resnet18_calls == [ResNet18_Weights.IMAGENET1K_V1]

    def test_uses_pretrained_weights_from_config(self, tmp_path: Path) -> None:
        path = tmp_path / "resnet18.pth"
        saved = _save_resnet18_weights(path)
        model = build_model(ModelConfig(pretrained=True, pretrained_weights=path))
        assert torch.equal(model.base_model.conv1.weight, saved["conv1.weight"])
        assert torch.equal(model.base_model.fc.weight, saved["fc.weight"])

    def test_missing_weights_from_config_is_value_error(self, tmp_path: Path) -> None:
        config = ModelConfig(pretrained=True, pretrained_weights=tmp_path / "missing.pth")
        with pytest.raises(ValueError):
            build_model(config)

    def test_built_model_outputs_two_channels(self) -> None:
        torch.manual_seed(SEED)
        model = build_model(ModelConfig(pretrained=False)).eval()
        with torch.no_grad():
            out = model(_rand(1, 3, 64, 64))
        assert out.shape == (1, NUM_CLASSES, 64, 64)