diff --git a/.claude/rules/testing.md b/.claude/rules/testing.md index 6d3c33d..d087202 100644 --- a/.claude/rules/testing.md +++ b/.claude/rules/testing.md @@ -30,7 +30,7 @@ 5. **学習後の評価**: 既知の予測と正解に対して IoU が期待値と一致すること(シグモイド → 255 倍 → 大津の 2 値化の手順を含む) 6. **分割**: 同じ seed で分割が再現すること.患者単位の分割では同じ患者が学習と検証にまたがらないこと 7. **バンドルの検証**: 画像と正解マスクの組が欠けている・大きさが合わない場合に止まること(黙って除かないこと) -8. **設定スキーマ**: 不正な YAML・未知のキーが `ValidationError` になること.既定値が SPEC_02 の表(原本と同じ学習条件)と一致すること +8. **設定スキーマ**: 未知のキー・必須項目の欠落・範囲外の値が `ValidationError` になること.YAML として読めないファイル・トップレベルが辞書でないファイルが `ValueError` になること.既定値が SPEC_02 の表(原本と同じ学習条件)と一致すること 9. **ONNX の書き出し**: 書き出した ONNX の入出力の形が `(1, 3, 256, 256)` → `(1, 2, 256, 256)` であること.onnxruntime の出力が PyTorch の出力とほぼ一致すること ## テストを必須としない対象 (Optional) diff --git a/CLAUDE.md b/CLAUDE.md index 9782fbd..1023653 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -8,7 +8,7 @@ ## 開発進捗 -最新: プロジェクト立ち上げ完了(GUIDE_01 の全フェーズ).次は PLAN_02 のステップ 1-1(設定と実験の出力) +最新: PLAN_02 ステップ 1-1(設定スキーマと実験の出力の土台)完了.次はステップ 1-2(モデル) ※ 本欄は**最新ステップ 1 行のみ上書き更新**.詳細な進捗履歴(動機・設計判断・失敗パターン)は [docs/PROGRESS.md](docs/PROGRESS.md) に追記する.運用ルールは `.claude/rules/progress-log.md` を参照(該当ファイル編集時に自動ロードされる). ## 必須ルール(コード実装時) diff --git a/configs/resunet.yaml b/configs/resunet.yaml new file mode 100644 index 0000000..2d03062 --- /dev/null +++ b/configs/resunet.yaml @@ -0,0 +1,14 @@ +# サーバの実データで ResUNet を学習する設定(原本 legacy/source/main.py と同じ学習条件). +# 学習条件は src/tongue_seg_model/schema.py の既定値のまま.書いていない項目も既定値になる +# (実際に使った値は runs/<実験ID>/config.yaml に全項目が残る). + +data: + bundle: + # 未確定: TIASDataHub がセグメンテーション用データの取り込みに対応していないため, + # バンドルの名前と版は仮の値である(SPEC_01「データ契約」.確定したら書き換える) + name: tongue_segmentation + version: 1 + +train: + # GPU の番号は共用サーバの空きに合わせて指定する(auto は GPU があれば cuda) + device: auto diff --git a/configs/synthetic.yaml b/configs/synthetic.yaml new file mode 100644 index 0000000..706533a --- /dev/null +++ b/configs/synthetic.yaml @@ -0,0 +1,19 @@ +# 手元の合成データ(scripts/ で作るバンドルの形のデータ)で学習のコードを流すための設定. +# 目的は「落ちずに数エポック回り,指標と ONNX が書き出される」ことの確認で,精度は意味を持たない. +# 書いていない項目は src/tongue_seg_model/schema.py の既定値(原本と同じ学習条件)になる. + +data: + bundle: + # 合成データのバンドルの名前と版(合成データの生成スクリプトに合わせる.PLAN_02 のステップ 1-4 で確定) + name: synthetic + version: 1 + +model: + # 手元でダウンロードを待たないよう,事前学習の重みは使わない + pretrained: false + +train: + batch_size: 4 + max_epochs: 3 + early_stopping_patience: 2 + device: cpu diff --git "a/docs/03_PLAN/PLAN_02_\351\226\213\347\231\272\343\202\271\343\203\206\343\203\203\343\203\227.md" "b/docs/03_PLAN/PLAN_02_\351\226\213\347\231\272\343\202\271\343\203\206\343\203\203\343\203\227.md" index 1668cbf..d610169 100644 --- "a/docs/03_PLAN/PLAN_02_\351\226\213\347\231\272\343\202\271\343\203\206\343\203\203\343\203\227.md" +++ "b/docs/03_PLAN/PLAN_02_\351\226\213\347\231\272\343\202\271\343\203\206\343\203\203\343\203\227.md" @@ -14,7 +14,7 @@ | ステップ | 内容 | 完了の条件 | | --- | --- | --- | -| 1-1 設定と実験の出力 | 設定スキーマ(`schema.py`.既定値は SPEC_02 の原本と同じ学習条件),`configs/synthetic.yaml`・`configs/resunet.yaml`,実験 ID と `runs/<実験ID>/` の作成,`config.yaml`・`log.txt` の書き出し | 不正な設定で止まる.既定値が SPEC_02 の表と一致する(テスト) | +| 1-1 設定と実験の出力(**完了**) | 設定スキーマ(`schema.py`.既定値は SPEC_02 の原本と同じ学習条件),`configs/synthetic.yaml`・`configs/resunet.yaml`,実験 ID と `runs/<実験ID>/` の作成,`config.yaml`・`log.txt` の書き出し | 不正な設定で止まる.既定値が SPEC_02 の表と一致する(テスト) | | 1-2 モデル | ResUNet(原本の `ResNetUNet`)を `models/` に移す | 出力の形が `(N, 2, H, W)`.`state_dict` のキーが原本と同じ(テスト) | | 1-3 前処理・損失・IoU | 画像とマスクの前処理,Dice+BCE 損失(`bce_input` の切り替え),学習後の評価の IoU を純関数で作る | 手計算した期待値と一致する(テスト) | | 1-4 合成データとデータの読み込み | バンドルの形の合成データを作るスクリプト,バンドルの読み込み(`data/bundle.py`),Dataset,データ拡張,分割 | 合成のバンドルを読める.組の欠け・大きさの違いで止まる.分割が seed で再現する(テスト).※ manifest の列名は仮(ステップ 2-2 で確定) | @@ -62,4 +62,4 @@ ## 最初の実装ステップ (First Step) -**ステップ 1-1(設定と実験の出力)**から始める.`/implement ステップ 1-1 設定スキーマと実験の出力の土台を作る` で開始できる. +ステップ 1-1(設定と実験の出力)から始めた(2026-11-18 に完了).次は**ステップ 1-2(モデル)**.`/implement ステップ 1-2 ResUNet を models に移す` で開始できる. diff --git "a/docs/04_SPEC/SPEC_01_\343\202\242\343\203\274\343\202\255\343\203\206\343\202\257\343\203\201\343\203\243\350\250\255\350\250\210.md" "b/docs/04_SPEC/SPEC_01_\343\202\242\343\203\274\343\202\255\343\203\206\343\202\257\343\203\201\343\203\243\350\250\255\350\250\210.md" index 7eb20e5..3929501 100644 --- "a/docs/04_SPEC/SPEC_01_\343\202\242\343\203\274\343\202\255\343\203\206\343\202\257\343\203\201\343\203\243\350\250\255\350\250\210.md" +++ "b/docs/04_SPEC/SPEC_01_\343\202\242\343\203\274\343\202\255\343\203\206\343\202\257\343\203\201\343\203\243\350\250\255\350\250\210.md" @@ -100,9 +100,12 @@ └── ResUNet.onnx # ONNX の書き出しを実行したとき ``` -実験 ID の書式: `YYYYmmdd-HHMMSS_<設定ファイル名>_` +実験 ID の書式: `YYYYmmdd-HHMMSS_<設定ファイル名>_`(設定ファイル名は拡張子を除いたもの) - サーバには `.git` を送らないため,git のハッシュは手元で求めてリモート実行ツールが環境変数で渡す([SPEC_03](SPEC_03_リモート実行仕様.md)).未コミットの変更があるときは末尾に `-dirty` が付く.環境変数が無い場合(手元での直接実行等)は `nogit` とする +- 環境変数の名前は `TSM_GIT_COMMIT`.値は英数字で始まり英数字・`_`・`-` の 64 文字以内でなければ拒否する.設定ファイル名も実験 ID(フォルダ名)に入るため,英数字で始まり英数字・`.`・`_`・`-` の 64 文字以内に限る +- 同じ実験 ID のフォルダが既にあるときは上書きせずに止める +- `config.yaml` は 2 つの部分からなる: `run`(`id`・`git_commit`・`seed`・`data_bundle`=バンドルの指紋.バンドルを読まない実行では null)と `config`(既定値を埋めた設定の全項目.そのまま設定として読み戻せる) - 原本は最良を更新するたびに `epoch.pth` を残していたが,新しいコードは `best.pth` を上書きする(サーバのディスクを使い過ぎないため) - **`figures/` には図だけを置き,舌画像・マスク・予測結果の画像を書き込まない**.回収ホワイトリストが `figures/*.png` を回収対象にしているため - 画像ごとの結果(`predictions.csv`)・分割結果(`split.json`)は回収対象外の名前で保存する diff --git "a/docs/04_SPEC/SPEC_02_\345\255\246\347\277\222\343\203\273ONNX\346\233\270\343\201\215\345\207\272\343\201\227\344\273\225\346\247\230.md" "b/docs/04_SPEC/SPEC_02_\345\255\246\347\277\222\343\203\273ONNX\346\233\270\343\201\215\345\207\272\343\201\227\344\273\225\346\247\230.md" index 0c8a407..25c7c04 100644 --- "a/docs/04_SPEC/SPEC_02_\345\255\246\347\277\222\343\203\273ONNX\346\233\270\343\201\215\345\207\272\343\201\227\344\273\225\346\247\230.md" +++ "b/docs/04_SPEC/SPEC_02_\345\255\246\347\277\222\343\203\273ONNX\346\233\270\343\201\215\345\207\272\343\201\227\344\273\225\346\247\230.md" @@ -117,17 +117,34 @@ ## 設定項目 (Configuration Keys) -`configs/*.yaml` の項目(名前は実装時に確定する).既定値は上の各節のとおり. +`configs/*.yaml` の項目.スキーマと既定値は `src/tongue_seg_model/schema.py` の 1 か所にある.必須は `data.bundle` だけで,書かなかった項目は既定値(原本と同じ学習条件)になる.未知のキーは拒否する. -| 区分 | 項目 | -| --- | --- | -| `data` | バンドルの名前と版,画像の大きさ,分割の方法(`random` / `subject`)と学習用の割合 | -| `augment` | 色のゆらぎの強さ,左右反転の確率 | -| `model` | 事前学習の重みを使うか,重みファイルの場所(任意) | -| `loss` | `bce_weight`,`bce_input`(`sigmoid` / `logits`) | -| `train` | バッチサイズ,学習率,最大エポック数,早期終了の待ち数,乱数の種,データを読む並列数 | -| `export` | opset | -| `run` | 出力先(既定 `runs/`) | +| 項目 | 既定 | 内容・制約 | +| --- | --- | --- | +| `data.bundle.name` | (必須) | バンドルの名前.英数字で始まり英数字・`.`・`_`・`-` の 64 文字以内 | +| `data.bundle.version` | (必須) | バンドルの版.1 以上の整数 | +| `data.image_size` | `[256, 256]` | 画像の大きさ(高さ,幅).正の整数 | +| `data.split` | `random` | 分割の方法.`random`(画像単位)/ `subject`(患者単位) | +| `data.train_ratio` | `2/3` | 学習用の割合.0 より大きく 1 未満 | +| `augment.color_jitter.brightness`・`contrast`・`saturation` | 各 `0.5` | 色のゆらぎの強さ.0 以上 | +| `augment.color_jitter.hue` | `0.5` | 色相のゆらぎ.0〜0.5(torchvision の制約) | +| `augment.hflip_prob` | `0.5` | 左右反転の確率.0〜1 | +| `model.pretrained` | `true` | 事前学習の重みを使うか | +| `model.pretrained_weights` | 無し | 重みファイルの場所(任意.`pretrained: true` のときだけ指定できる) | +| `loss.bce_weight` | `0.5` | BCE の重み.0〜1 | +| `loss.bce_input` | `sigmoid` | `sigmoid`(原本どおり)/ `logits` | +| `train.batch_size` | `16` | 正の整数 | +| `train.learning_rate` | `1e-4` | 正の数 | +| `train.max_epochs` | `300` | 正の整数 | +| `train.early_stopping_patience` | `30` | 早期終了の待ち数.正の整数 | +| `train.seed` | `2021` | 乱数の種.0〜2^32−1 | +| `train.num_workers` | `0` | データを読む並列数(原本と同じ 0) | +| `train.device` | `auto` | `auto`(GPU があれば使い,無ければ CPU)/ `cpu` / `cuda` / `cuda:<番号>`.共用サーバでは空いている GPU の番号を指定する | +| `export.opset` | `11` | 7 以上の整数 | +| `run.out_dir` | `runs` | 出力先 | + +- 整数の項目に小数や文字列で書いた数値(`1.5`・`"16"`)を書くと止まる(書き間違いを黙って丸めない) +- 設定ファイルが無い・YAML として読めない・トップレベルが辞書でない場合は `ValueError`,項目の内容の誤りは pydantic の `ValidationError`(`ValueError` の一種)になる ## 原本の挙動のうち注意が要るもの (Notable Behaviours) diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index d44a067..92c2dd8 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -27,3 +27,6 @@ - [x] **立ち上げフェーズ 7(実装開始)**: CLAUDE.md を立ち上げ完了の状態に更新(概要に技術スタック・構成・実行環境の要約を追加).Dependabot のセキュリティ設定が有効なことを再確認 - 次: PLAN_02 のステップ 1-1(設定と実験の出力).ステップ 1-4 が済んだら TIASDataHub 側の作業(2-1)の着手を提案する - `legacy/` の重み・結果のバックアップは研究室の共有フォルダにある(ユーザーが確認).`legacy/result/` は当面 Git に入れない(ユーザー判断).人間の確認待ち: 原本のコードの作者とライセンス(ENV_03「人間が確認すべき事項」) +- [x] **ステップ 1-1 設定スキーマと実験の出力の土台**: 設定スキーマ(既定値は原本と同じ学習条件)・設定ファイル 2 つ・実験 ID と `runs/<実験ID>/`・`config.yaml`・ログの設定を作成 + - 設計判断: 整数の項目は文字列や小数を拒否する(書き間違いを黙って丸めないため)が,浮動小数点は文字列も受ける(PyYAML が `1e-4` を文字列として読むため) + - 未実装・後段: `train.device: auto` の実際の切り替えは学習ループ(1-5).バンドルの名前は仮(合成データは 1-4,実データは 2-2 で確定) diff --git a/src/tongue_seg_model/schema.py b/src/tongue_seg_model/schema.py new file mode 100644 index 0000000..b19bdfe --- /dev/null +++ b/src/tongue_seg_model/schema.py @@ -0,0 +1,223 @@ +"""pydantic による設定スキーマと設定 YAML の読み込み. + +学習条件の既定値は**このファイルの 1 か所だけ**に置く(`.claude/rules/coding-style.md`). +既定値は原本(`legacy/source/main.py`・`legacy/source/pytorchToOnnx.py`)と同じ学習条件で, +[SPEC_02](../../docs/04_SPEC/SPEC_02_学習・ONNX書き出し仕様.md) の各節の表に対応する. +`data.bundle` だけは既定を持たない(暗黙に最新の版を使うと再現性が崩れるため). +""" + +from __future__ import annotations + +from pathlib import Path +from typing import Annotated, Any, Literal + +import yaml +from pydantic import BaseModel, ConfigDict, Field, FiniteFloat, field_validator, model_validator + +# 実験 ID・ファイル名に埋め込んでも安全な名前(英数字で始まり,英数字・`_`・`-`・`.`). +_NAME_PATTERN = r"^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$" +# 学習に使う計算装置の指定.`auto` は「GPU があれば `cuda`,無ければ `cpu`」を表す. +# 共用サーバでは GPU の番号を指定するため,`cuda:N` を許す(`cuda:0` を直書きしない). +_DEVICE_PATTERN = r"^(auto|cpu|cuda(:[0-9]+)?)$" + +# 画像の高さ・幅(YAML のリストを受けるため,tuple 自体ではなく要素を strict にする). +_ImageSide = Annotated[int, Field(ge=1, strict=True)] + +SplitMethod = Literal["random", "subject"] +BceInput = Literal["sigmoid", "logits"] + + +class _StrictModel(BaseModel): + """未知のキー(綴り間違い)を拒否し,生成後の変更を禁止する基底モデル.""" + + model_config = ConfigDict(extra="forbid", frozen=True) + + +class BundleConfig(_StrictModel): + """読み込む TIASDataHub のバンドル(データセットの 1 つの版). + + Attributes: + name: データセット名. + version: 版(1 以上.省略できない). + """ + + name: str = Field(pattern=_NAME_PATTERN) + version: int = Field(ge=1, strict=True) + + +class DataConfig(_StrictModel): + """データに関する設定(SPEC_02「入力の前処理」「分割」). + + Attributes: + bundle: 読み込むバンドル(必須). + image_size: 画像と正解マスクの大きさ `(高さ, 幅)`.違うものがあれば学習を始めずに止める. + split: 学習用と検証用の分け方.`random` は原本と同じ画像単位,`subject` は患者単位. + train_ratio: `subset` が `train` の組のうち学習用に回す割合(0〜1 の開区間.端数は + 検証側.原本は 2/3). + """ + + bundle: BundleConfig + image_size: tuple[_ImageSide, _ImageSide] = (256, 256) + split: SplitMethod = "random" + train_ratio: FiniteFloat = Field(default=2 / 3, gt=0.0, lt=1.0) + + +class ColorJitterConfig(_StrictModel): + """色のゆらぎ(`torchvision.transforms.ColorJitter`)の強さ(原本: `main.py`.各 0.5). + + Attributes: + brightness: 明るさ(0 以上). + contrast: コントラスト(0 以上). + saturation: 彩度(0 以上). + hue: 色相(0〜0.5.`ColorJitter` の受け付ける範囲). + """ + + brightness: FiniteFloat = Field(default=0.5, ge=0.0) + contrast: FiniteFloat = Field(default=0.5, ge=0.0) + saturation: FiniteFloat = Field(default=0.5, ge=0.0) + hue: FiniteFloat = Field(default=0.5, ge=0.0, le=0.5) + + +class AugmentConfig(_StrictModel): + """データ拡張の設定(SPEC_02「データ拡張」). + + Attributes: + color_jitter: 画像だけに掛ける色のゆらぎ. + hflip_prob: 画像とマスクの両方を左右反転する確率(0〜1). + """ + + color_jitter: ColorJitterConfig = Field(default_factory=ColorJitterConfig) + hflip_prob: FiniteFloat = Field(default=0.5, ge=0.0, le=1.0) + + +class ModelConfig(_StrictModel): + """モデルの設定(SPEC_02「モデル」). + + Attributes: + pretrained: エンコーダ(resnet18)に ImageNet の事前学習の重みを使うか. + pretrained_weights: 事前学習の重みファイルの場所(任意).ダウンロードできない環境で + 使う.None なら torchvision の既定の取得方法に任せる.`~` は展開される. + """ + + pretrained: bool = Field(default=True, strict=True) + pretrained_weights: Path | None = None + + @field_validator("pretrained_weights", mode="after") + @classmethod + def _expand_user(cls, value: Path | None) -> Path | None: + return None if value is None else value.expanduser() + + @model_validator(mode="after") + def _check_weights(self) -> ModelConfig: + if self.pretrained_weights is not None and not self.pretrained: + raise ValueError( + "model.pretrained_weights は model.pretrained が true のときだけ指定できる" + ) + return self + + +class LossConfig(_StrictModel): + """損失の設定(SPEC_02「損失」.原本: `losses.py` の `DiceCE`). + + Attributes: + bce_weight: BCE の重み(0〜1.Dice の重みは `1 − bce_weight`). + bce_input: BCE に渡す値.`sigmoid` は原本どおり(シグモイドが 2 重に掛かる), + `logits` は直した版. + """ + + bce_weight: FiniteFloat = Field(default=0.5, ge=0.0, le=1.0) + bce_input: BceInput = "sigmoid" + + +class TrainConfig(_StrictModel): + """学習の設定(SPEC_02「学習」). + + Attributes: + batch_size: バッチサイズ(学習・検証とも). + learning_rate: Adam の学習率. + max_epochs: 最大エポック数. + early_stopping_patience: 検証損失が最良を更新しないまま待つエポック数. + seed: 乱数の種(NumPy の種が受け付ける 0〜2**32−1). + num_workers: データを読む並列数(`DataLoader` の `num_workers`.原本は 0). + device: 計算装置(`auto`・`cpu`・`cuda`・`cuda:N`).`auto` は GPU があれば `cuda`. + """ + + batch_size: int = Field(default=16, ge=1, strict=True) + learning_rate: FiniteFloat = Field(default=1e-4, gt=0.0) + max_epochs: int = Field(default=300, ge=1, strict=True) + early_stopping_patience: int = Field(default=30, ge=1, strict=True) + seed: int = Field(default=2021, ge=0, le=2**32 - 1, strict=True) + num_workers: int = Field(default=0, ge=0, strict=True) + device: str = Field(default="auto", pattern=_DEVICE_PATTERN) + + +class ExportConfig(_StrictModel): + """ONNX の書き出しの設定(SPEC_02「ONNX の書き出し」). + + Attributes: + opset: ONNX の opset の版(原本と同じ 11). + """ + + opset: int = Field(default=11, ge=7, strict=True) + + +class RunConfig(_StrictModel): + """実験の出力の設定(SPEC_01「実験の出力」). + + Attributes: + out_dir: 実験ディレクトリ `/<実験ID>/` の親.相対パスはカレントディレクトリ + 基準.`~` は展開される. + """ + + out_dir: Path = Path("runs") + + @field_validator("out_dir", mode="after") + @classmethod + def _expand_user(cls, value: Path) -> Path: + return value.expanduser() + + +class ExperimentConfig(_StrictModel): + """設定 YAML 全体(SPEC_02「設定項目」). + + `data` 以外の区分は省略でき,省略時は各区分の既定値(原本と同じ学習条件)で補う. + """ + + data: DataConfig + augment: AugmentConfig = Field(default_factory=AugmentConfig) + model: ModelConfig = Field(default_factory=ModelConfig) + loss: LossConfig = Field(default_factory=LossConfig) + train: TrainConfig = Field(default_factory=TrainConfig) + export: ExportConfig = Field(default_factory=ExportConfig) + run: RunConfig = Field(default_factory=RunConfig) + + +def load_config(path: Path) -> ExperimentConfig: + """設定 YAML を読み込み,検証済みの設定を返す. + + Args: + path: 設定 YAML のパス. + + Returns: + 検証済みの設定(省略した項目は既定値で埋まる). + + Raises: + ValueError: ファイルが無い・読めない,YAML として解釈できない,またはトップレベルが + マッピングでない場合. + pydantic.ValidationError: 設定値が不正な場合(未知のキー・範囲外の値等). + """ + try: + text = path.read_text(encoding="utf-8") + except FileNotFoundError as exc: + raise ValueError(f"設定ファイルが見つからない: {path}") from exc + except (OSError, UnicodeDecodeError) as exc: + raise ValueError(f"設定ファイルを読めない: {path}({exc})") from exc + try: + raw: Any = yaml.safe_load(text) + except yaml.YAMLError as exc: + raise ValueError(f"設定ファイルを YAML として解釈できない: {path}({exc})") from exc + if raw is None: + raw = {} + if not isinstance(raw, dict): + raise ValueError(f"設定 YAML のトップレベルはマッピングでなければならない: {path}") + return ExperimentConfig.model_validate(raw) diff --git a/src/tongue_seg_model/training/__init__.py b/src/tongue_seg_model/training/__init__.py new file mode 100644 index 0000000..c7200a0 --- /dev/null +++ b/src/tongue_seg_model/training/__init__.py @@ -0,0 +1 @@ +"""学習ループ・損失・学習中の評価と,実験の出力(`runs/<実験ID>/`)の作成.""" diff --git a/src/tongue_seg_model/training/run_artifacts.py b/src/tongue_seg_model/training/run_artifacts.py new file mode 100644 index 0000000..8993dda --- /dev/null +++ b/src/tongue_seg_model/training/run_artifacts.py @@ -0,0 +1,233 @@ +"""実験の出力 `runs/<実験ID>/` の土台(SPEC_01「実験の出力」). + +実験 ID の生成・実験ディレクトリの作成・`config.yaml` の書き出し・`log.txt` へのログ設定を担う. +torch に依存しない.実験 ID と `config.yaml` の内容を作る部分は純関数にしてある +(`resolve_git_commit`・`make_run_id`・`build_config_document`). +""" + +from __future__ import annotations + +import logging +import os +import re +import sys +from collections.abc import Mapping +from dataclasses import dataclass +from datetime import datetime +from pathlib import Path +from typing import Any + +import yaml + +from tongue_seg_model.schema import ExperimentConfig + +# 実験 ID に入れる git の短縮ハッシュ.サーバには .git を送らないため,リモート実行ツールが +# 手元で求めてこの環境変数で渡す(SPEC_01「実験の出力」・SPEC_03). +GIT_COMMIT_ENV_VAR = "TSM_GIT_COMMIT" +# 環境変数が無い(手元での直接実行等)ときに実験 ID へ入れる値. +NO_GIT = "nogit" + +CONFIG_FILENAME = "config.yaml" +LOG_FILENAME = "log.txt" +FIGURES_DIRNAME = "figures" +CHECKPOINTS_DIRNAME = "checkpoints" + +# 実験 ID はディレクトリ名・環境変数の値として使うため,安全な文字だけを許す +# (git の短縮ハッシュと `-dirty` を想定). +_GIT_COMMIT_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$") +_CONFIG_NAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$") +_SHA256_RE = re.compile(r"^[0-9a-f]{64}$") + +_LOG_FORMAT = "%(asctime)s %(levelname)s %(name)s: %(message)s" +# 本モジュールが root logger に付けるハンドラの名前.2 回目の呼び出しで付け直すために使う. +_CONSOLE_HANDLER_NAME = "tongue_seg_model.console" +_FILE_HANDLER_NAME = "tongue_seg_model.run_log" + + +@dataclass(frozen=True) +class BundleFingerprint: + """学習に使ったバンドルの指紋(SPEC_01「データ契約」.患者 ID・ファイル名を含まない). + + Attributes: + name: データセット名. + version: 版(1 以上). + manifest_sha256: manifest の SHA-256(16 進の小文字 64 文字). + + Raises: + ValueError: 値の形式が不正な場合. + """ + + name: str + version: int + manifest_sha256: str + + def __post_init__(self) -> None: + if not self.name: + raise ValueError("バンドルの指紋の name が空である") + if isinstance(self.version, bool) or not isinstance(self.version, int) or self.version < 1: + raise ValueError("バンドルの指紋の version は 1 以上の整数でなければならない") + if not _SHA256_RE.match(self.manifest_sha256): + raise ValueError("バンドルの指紋の manifest_sha256 は 16 進の小文字 64 文字である") + + def to_dict(self) -> dict[str, str | int]: + """`config.yaml`・`metrics.json` に書く形の dict を返す. + + Returns: + `name`・`version`・`manifest_sha256` をキーとする dict. + """ + return { + "name": self.name, + "version": self.version, + "manifest_sha256": self.manifest_sha256, + } + + +def resolve_git_commit(environ: Mapping[str, str] | None = None) -> str: + """実験 ID に入れる git の短縮ハッシュを環境変数から決める. + + Args: + environ: 参照する環境変数.None なら `os.environ` を使う. + + Returns: + `TSM_GIT_COMMIT` の値(前後の空白は除く).未設定・空なら `nogit`. + + Raises: + ValueError: 値が英数字で始まり英数字・`_`・`-` だけからなる 64 文字以内でない場合. + """ + env = os.environ if environ is None else environ + value = env.get(GIT_COMMIT_ENV_VAR, "").strip() + if not value: + return NO_GIT + if not _GIT_COMMIT_RE.match(value): + raise ValueError( + f"環境変数 {GIT_COMMIT_ENV_VAR} の値が不正である: {value!r}" + "(英数字で始まり,英数字・_・- のみ,64 文字以内)" + ) + return value + + +def make_run_id(now: datetime, config_name: str, git_commit: str) -> str: + """実験 ID `YYYYmmdd-HHMMSS_<設定ファイル名>_` を作る. + + Args: + now: 実行日時. + config_name: 設定ファイル名(拡張子なし.例: `Path("configs/resunet.yaml").stem`). + git_commit: git の短縮ハッシュ(`resolve_git_commit` の戻り値.`nogit` を含む). + + Returns: + 実験 ID. + + Raises: + ValueError: `config_name` または `git_commit` がディレクトリ名に使えない文字を含む場合. + """ + if not _CONFIG_NAME_RE.match(config_name): + raise ValueError( + f"設定ファイル名が実験 ID に使えない: {config_name!r}" + "(英数字で始まり,英数字・.・_・- のみ,64 文字以内)" + ) + if not _GIT_COMMIT_RE.match(git_commit): + raise ValueError(f"git のハッシュが実験 ID に使えない: {git_commit!r}") + return f"{now:%Y%m%d-%H%M%S}_{config_name}_{git_commit}" + + +def create_run_dir(out_dir: Path, run_id: str) -> Path: + """実験ディレクトリ `//` と,その下の `figures/`・`checkpoints/` を作る. + + Args: + out_dir: 実験ディレクトリの親(無ければ作る). + run_id: 実験 ID. + + Returns: + 作った実験ディレクトリ. + + Raises: + ValueError: 実験ディレクトリが既にある場合(上書きしない). + """ + run_dir = out_dir / run_id + out_dir.mkdir(parents=True, exist_ok=True) + try: + run_dir.mkdir() + except FileExistsError as exc: + raise ValueError( + f"実験ディレクトリが既にある: {run_dir}(上書きしない.時間をおいて再実行する)" + ) from exc + (run_dir / FIGURES_DIRNAME).mkdir() + (run_dir / CHECKPOINTS_DIRNAME).mkdir() + return run_dir + + +def build_config_document( + config: ExperimentConfig, + *, + run_id: str, + git_commit: str, + data_bundle: BundleFingerprint | None = None, +) -> dict[str, Any]: + """`config.yaml` に書く内容を作る. + + Args: + config: 検証済みの設定(既定値で埋まった全項目が書かれる). + run_id: 実験 ID. + git_commit: git の短縮ハッシュ(または `nogit`). + data_bundle: 学習に使ったバンドルの指紋.まだ読んでいなければ None(`null` で書く). + + Returns: + YAML に書き出せる dict(`run` に実験の記録,`config` に解決済みの設定). + """ + return { + "run": { + "id": run_id, + "git_commit": git_commit, + "seed": config.train.seed, + "data_bundle": None if data_bundle is None else data_bundle.to_dict(), + }, + "config": config.model_dump(mode="json"), + } + + +def write_config_yaml(run_dir: Path, document: Mapping[str, Any]) -> Path: + """`build_config_document` の内容を `/config.yaml` に書き出す. + + Args: + run_dir: 実験ディレクトリ. + document: 書き出す内容. + + Returns: + 書き出したファイルのパス. + """ + path = run_dir / CONFIG_FILENAME + with path.open("w", encoding="utf-8", newline="\n") as f: + yaml.safe_dump(dict(document), f, allow_unicode=True, sort_keys=False) + return path + + +def configure_logging(run_dir: Path | None = None, level: int = logging.INFO) -> None: + """ログを標準エラーと(`run_dir` があれば)`/log.txt` の両方へ出すよう設定する. + + root logger に設定する.同じプロセスで何度呼んでもハンドラは重複しない(前回本関数が付けた + ハンドラを外してから付け直す.`log.txt` のハンドラは閉じてから外す).標準出力は実験 ID の + 受け渡しに使うため汚さない. + + Args: + run_dir: 実験ディレクトリ.None ならコンソールにだけ出す. + level: root logger のログレベル. + """ + root = logging.getLogger() + for handler in list(root.handlers): + if handler.get_name() in (_CONSOLE_HANDLER_NAME, _FILE_HANDLER_NAME): + root.removeHandler(handler) + handler.close() + + formatter = logging.Formatter(_LOG_FORMAT) + console = logging.StreamHandler(sys.stderr) + console.set_name(_CONSOLE_HANDLER_NAME) + console.setFormatter(formatter) + root.addHandler(console) + + if run_dir is not None: + file_handler = logging.FileHandler(run_dir / LOG_FILENAME, encoding="utf-8") + file_handler.set_name(_FILE_HANDLER_NAME) + file_handler.setFormatter(formatter) + root.addHandler(file_handler) + + root.setLevel(level) diff --git a/tests/test_schema.py b/tests/test_schema.py new file mode 100644 index 0000000..5963315 --- /dev/null +++ b/tests/test_schema.py @@ -0,0 +1,325 @@ +"""設定スキーマ(`schema.py`)のテスト. + +期待値は SPEC_02(原本と同じ学習条件)と SPEC_01「設定ファイル」を基準にする. +""" + +from __future__ import annotations + +from pathlib import Path +from typing import Any + +import pytest +from pydantic import ValidationError + +from tongue_seg_model.schema import ExperimentConfig, load_config + +REPO_ROOT = Path(__file__).resolve().parents[1] +CONFIGS_DIR = REPO_ROOT / "configs" + + +def _minimal() -> dict[str, Any]: + """必須項目(`data.bundle`)だけを持つ設定.""" + return {"data": {"bundle": {"name": "synthetic", "version": 1}}} + + +def _with(section: str, values: dict[str, Any]) -> dict[str, Any]: + raw = _minimal() + if section == "data": + raw["data"].update(values) + else: + raw[section] = values + return raw + + +def _write(tmp_path: Path, text: str, name: str = "config.yaml") -> Path: + path = tmp_path / name + path.write_text(text, encoding="utf-8") + return path + + +# --------------------------------------------------------------------------- +# 既定値(SPEC_02 の表 = 原本と同じ学習条件) +# --------------------------------------------------------------------------- + + +class TestDefaultsMatchSpec02: + @pytest.fixture + def config(self) -> ExperimentConfig: + return ExperimentConfig.model_validate(_minimal()) + + def test_preprocessing_image_size_is_256x256(self, config: ExperimentConfig) -> None: + assert tuple(config.data.image_size) == (256, 256) + + def test_split_defaults_to_random_with_two_thirds_for_training( + self, config: ExperimentConfig + ) -> None: + assert config.data.split == "random" + assert config.data.train_ratio == pytest.approx(2 / 3) + + def test_color_jitter_defaults_are_each_0_5(self, config: ExperimentConfig) -> None: + cj = config.augment.color_jitter + assert (cj.brightness, cj.contrast, cj.saturation, cj.hue) == (0.5, 0.5, 0.5, 0.5) + + def test_hflip_probability_defaults_to_0_5(self, config: ExperimentConfig) -> None: + assert config.augment.hflip_prob == 0.5 + + def test_model_uses_pretrained_weights_by_default(self, config: ExperimentConfig) -> None: + assert config.model.pretrained is True + assert config.model.pretrained_weights is None + + def test_loss_defaults_to_original_dice_ce(self, config: ExperimentConfig) -> None: + assert config.loss.bce_weight == 0.5 + assert config.loss.bce_input == "sigmoid" + + def test_training_defaults_match_original(self, config: ExperimentConfig) -> None: + train = config.train + assert train.batch_size == 16 + assert train.learning_rate == pytest.approx(1e-4) + assert train.max_epochs == 300 + assert train.early_stopping_patience == 30 + assert train.seed == 2021 + + def test_export_opset_defaults_to_11(self, config: ExperimentConfig) -> None: + assert config.export.opset == 11 + + def test_run_out_dir_defaults_to_runs(self, config: ExperimentConfig) -> None: + assert config.run.out_dir == Path("runs") + + def test_all_sections_are_filled_when_omitted(self, config: ExperimentConfig) -> None: + dumped = config.model_dump(mode="json") + assert set(dumped) == {"data", "augment", "model", "loss", "train", "export", "run"} + + +def test_explicit_values_override_defaults() -> None: + raw = _minimal() + raw["train"] = {"batch_size": 4, "max_epochs": 3, "seed": 7} + raw["loss"] = {"bce_input": "logits", "bce_weight": 0.3} + raw["data"]["split"] = "subject" + config = ExperimentConfig.model_validate(raw) + assert config.train.batch_size == 4 + assert config.train.max_epochs == 3 + assert config.train.seed == 7 + # 書いていない項目は既定のまま + assert config.train.learning_rate == pytest.approx(1e-4) + assert config.train.early_stopping_patience == 30 + assert config.loss.bce_input == "logits" + assert config.loss.bce_weight == 0.3 + assert config.data.split == "subject" + + +def test_config_is_immutable() -> None: + config = ExperimentConfig.model_validate(_minimal()) + with pytest.raises(ValidationError): + config.train.batch_size = 1 # type: ignore[misc] + + +# --------------------------------------------------------------------------- +# 不正な設定は ValidationError で止まる +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + "raw", + [ + pytest.param({**_minimal(), "unknown": 1}, id="top-level"), + pytest.param(_with("data", {"imagesize": [256, 256]}), id="data"), + pytest.param( + {"data": {"bundle": {"name": "a", "version": 1, "extra": 1}}}, id="data.bundle" + ), + pytest.param(_with("augment", {"hflip": 0.5}), id="augment"), + pytest.param(_with("augment", {"color_jitter": {"gamma": 0.1}}), id="color_jitter"), + pytest.param(_with("model", {"pretrain": False}), id="model"), + pytest.param(_with("loss", {"dice_weight": 0.5}), id="loss"), + pytest.param(_with("train", {"epochs": 3}), id="train"), + pytest.param(_with("export", {"opset_version": 11}), id="export"), + pytest.param(_with("run", {"output": "runs"}), id="run"), + ], +) +def test_unknown_key_is_rejected(raw: dict[str, Any]) -> None: + with pytest.raises(ValidationError): + ExperimentConfig.model_validate(raw) + + +@pytest.mark.parametrize( + "raw", + [ + pytest.param({}, id="no-data"), + pytest.param({"data": {}}, id="no-bundle"), + pytest.param({"data": {"bundle": {"version": 1}}}, id="no-bundle-name"), + pytest.param({"data": {"bundle": {"name": "synthetic"}}}, id="no-bundle-version"), + ], +) +def test_missing_required_field_is_rejected(raw: dict[str, Any]) -> None: + with pytest.raises(ValidationError): + ExperimentConfig.model_validate(raw) + + +@pytest.mark.parametrize( + "raw", + [ + # data + pytest.param({"data": {"bundle": {"name": "a", "version": 0}}}, id="bundle-version-0"), + pytest.param({"data": {"bundle": {"name": "a", "version": "1"}}}, id="bundle-version-str"), + pytest.param({"data": {"bundle": {"name": "", "version": 1}}}, id="bundle-name-empty"), + pytest.param({"data": {"bundle": {"name": "../x", "version": 1}}}, id="bundle-name-path"), + pytest.param(_with("data", {"image_size": [0, 256]}), id="image-size-0"), + pytest.param(_with("data", {"image_size": [256]}), id="image-size-1d"), + pytest.param(_with("data", {"image_size": [256, 256, 3]}), id="image-size-3d"), + pytest.param(_with("data", {"image_size": [256.5, 256]}), id="image-size-float"), + pytest.param(_with("data", {"split": "patient"}), id="split-unknown"), + pytest.param(_with("data", {"train_ratio": 0.0}), id="train-ratio-0"), + pytest.param(_with("data", {"train_ratio": 1.0}), id="train-ratio-1"), + pytest.param(_with("data", {"train_ratio": 1.5}), id="train-ratio-gt1"), + pytest.param(_with("data", {"train_ratio": float("nan")}), id="train-ratio-nan"), + # augment + pytest.param(_with("augment", {"hflip_prob": -0.1}), id="hflip-negative"), + pytest.param(_with("augment", {"hflip_prob": 1.1}), id="hflip-gt1"), + pytest.param( + _with("augment", {"color_jitter": {"brightness": -0.1}}), id="brightness-negative" + ), + pytest.param(_with("augment", {"color_jitter": {"hue": 0.6}}), id="hue-gt-0.5"), + pytest.param(_with("augment", {"color_jitter": {"hue": -0.1}}), id="hue-negative"), + # model + pytest.param(_with("model", {"pretrained": "yes"}), id="pretrained-str"), + pytest.param( + _with("model", {"pretrained": False, "pretrained_weights": "w.pth"}), + id="weights-without-pretrained", + ), + # loss + pytest.param(_with("loss", {"bce_weight": 1.5}), id="bce-weight-gt1"), + pytest.param(_with("loss", {"bce_weight": -0.1}), id="bce-weight-negative"), + pytest.param(_with("loss", {"bce_input": "probs"}), id="bce-input-unknown"), + # train + pytest.param(_with("train", {"batch_size": 0}), id="batch-size-0"), + pytest.param(_with("train", {"batch_size": 1.5}), id="batch-size-float"), + pytest.param(_with("train", {"batch_size": "16"}), id="batch-size-str"), + pytest.param(_with("train", {"learning_rate": 0.0}), id="lr-0"), + pytest.param(_with("train", {"learning_rate": -1e-4}), id="lr-negative"), + pytest.param(_with("train", {"max_epochs": 0}), id="max-epochs-0"), + pytest.param(_with("train", {"early_stopping_patience": 0}), id="patience-0"), + pytest.param(_with("train", {"seed": -1}), id="seed-negative"), + pytest.param(_with("train", {"seed": 2**32}), id="seed-too-large"), + pytest.param(_with("train", {"num_workers": -1}), id="num-workers-negative"), + pytest.param(_with("train", {"device": "gpu"}), id="device-unknown"), + pytest.param(_with("train", {"device": "cuda:"}), id="device-cuda-colon"), + # export + pytest.param(_with("export", {"opset": 6}), id="opset-too-old"), + pytest.param(_with("export", {"opset": "11"}), id="opset-str"), + ], +) +def test_out_of_range_or_wrong_type_is_rejected(raw: dict[str, Any]) -> None: + with pytest.raises(ValidationError): + ExperimentConfig.model_validate(raw) + + +@pytest.mark.parametrize("device", ["auto", "cpu", "cuda", "cuda:0", "cuda:3"]) +def test_valid_device_is_accepted(device: str) -> None: + config = ExperimentConfig.model_validate(_with("train", {"device": device})) + assert config.train.device == device + + +def test_pretrained_weights_path_is_accepted_when_pretrained(tmp_path: Path) -> None: + weights = tmp_path / "resnet18.pth" + config = ExperimentConfig.model_validate( + _with("model", {"pretrained": True, "pretrained_weights": str(weights)}) + ) + assert config.model.pretrained_weights == weights + + +def test_image_size_accepts_yaml_list() -> None: + config = ExperimentConfig.model_validate(_with("data", {"image_size": [128, 64]})) + assert tuple(config.data.image_size) == (128, 64) + + +# --------------------------------------------------------------------------- +# load_config +# --------------------------------------------------------------------------- + + +def test_load_config_fills_defaults(tmp_path: Path) -> None: + path = _write(tmp_path, "data:\n bundle:\n name: synthetic\n version: 2\n") + config = load_config(path) + assert config.data.bundle.name == "synthetic" + assert config.data.bundle.version == 2 + assert config.train.batch_size == 16 + assert config.export.opset == 11 + + +def test_load_config_rejects_unknown_key_in_yaml(tmp_path: Path) -> None: + path = _write( + tmp_path, + "data:\n bundle:\n name: synthetic\n version: 1\ntrain:\n batchsize: 4\n", + ) + with pytest.raises(ValidationError): + load_config(path) + + +def test_load_config_rejects_malformed_yaml(tmp_path: Path) -> None: + path = _write(tmp_path, "data: [unclosed\n bundle: {name: a\n") + with pytest.raises((ValueError, ValidationError)): + load_config(path) + + +@pytest.mark.parametrize( + "text", + [ + pytest.param("- a\n- b\n", id="list"), + pytest.param("just a string\n", id="scalar"), + ], +) +def test_load_config_rejects_non_mapping_top_level(tmp_path: Path, text: str) -> None: + path = _write(tmp_path, text) + with pytest.raises((ValueError, ValidationError)): + load_config(path) + + +def test_load_config_empty_file_fails_for_missing_bundle(tmp_path: Path) -> None: + path = _write(tmp_path, "") + with pytest.raises(ValidationError): + load_config(path) + + +def test_load_config_missing_file_raises(tmp_path: Path) -> None: + with pytest.raises(ValueError): + load_config(tmp_path / "does_not_exist.yaml") + + +# --------------------------------------------------------------------------- +# リポジトリの configs/*.yaml +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize("name", ["synthetic.yaml", "resunet.yaml"]) +def test_repository_configs_are_valid(name: str) -> None: + load_config(CONFIGS_DIR / name) + + +def test_resunet_config_keeps_original_training_conditions() -> None: + """`configs/resunet.yaml` は原本と同じ学習条件(SPEC_01「設定ファイル」).""" + config = load_config(CONFIGS_DIR / "resunet.yaml") + defaults = ExperimentConfig.model_validate( + {"data": config.data.model_dump(mode="json", include={"bundle"})} + ) + assert config.data.image_size == defaults.data.image_size + assert config.data.split == defaults.data.split + assert config.data.train_ratio == defaults.data.train_ratio + assert config.augment == defaults.augment + assert config.model.pretrained is True + assert config.loss == defaults.loss + assert config.export == defaults.export + t = config.train + assert (t.batch_size, t.learning_rate, t.max_epochs, t.early_stopping_patience, t.seed) == ( + 16, + pytest.approx(1e-4), + 300, + 30, + 2021, + ) + + +def test_synthetic_config_runs_locally_without_download() -> None: + """`configs/synthetic.yaml` は手元で流す設定(エポック数を小さく,事前学習の重みを使わない).""" + config = load_config(CONFIGS_DIR / "synthetic.yaml") + assert config.model.pretrained is False + assert config.train.max_epochs < 300 + assert config.train.device == "cpu" diff --git a/tests/training/test_run_artifacts.py b/tests/training/test_run_artifacts.py new file mode 100644 index 0000000..4ed6e06 --- /dev/null +++ b/tests/training/test_run_artifacts.py @@ -0,0 +1,360 @@ +"""実験の出力 `runs/<実験ID>/` の土台(`training/run_artifacts.py`)のテスト. + +期待値は SPEC_01「実験の出力」を基準にする.ファイル I/O はすべて `tmp_path` で行う. +""" + +from __future__ import annotations + +import logging +import re +from collections.abc import Iterator +from datetime import datetime +from pathlib import Path +from typing import Any + +import pytest +import yaml + +from tongue_seg_model.schema import ExperimentConfig +from tongue_seg_model.training.run_artifacts import ( + CHECKPOINTS_DIRNAME, + CONFIG_FILENAME, + FIGURES_DIRNAME, + GIT_COMMIT_ENV_VAR, + LOG_FILENAME, + NO_GIT, + BundleFingerprint, + build_config_document, + configure_logging, + create_run_dir, + make_run_id, + resolve_git_commit, + write_config_yaml, +) + +SHA = "0123456789abcdef" * 4 +RUN_ID_RE = re.compile(r"^\d{8}-\d{6}_[A-Za-z0-9][A-Za-z0-9._-]*_[A-Za-z0-9][A-Za-z0-9_-]*$") + + +def _config(**sections: Any) -> ExperimentConfig: + raw: dict[str, Any] = {"data": {"bundle": {"name": "synthetic", "version": 1}}} + raw.update(sections) + return ExperimentConfig.model_validate(raw) + + +@pytest.fixture +def restore_logging() -> Iterator[None]: + """root logger の状態を戻し,`log.txt` のハンドラを閉じる(Windows での削除失敗を防ぐ).""" + root = logging.getLogger() + level = root.level + yield + configure_logging(None) + for handler in list(root.handlers): + if handler.get_name() and handler.get_name().startswith("tongue_seg_model."): + root.removeHandler(handler) + handler.close() + root.setLevel(level) + + +# --------------------------------------------------------------------------- +# 定数(SPEC_01 のファイル名) +# --------------------------------------------------------------------------- + + +def test_artifact_names_match_spec01() -> None: + assert CONFIG_FILENAME == "config.yaml" + assert LOG_FILENAME == "log.txt" + assert FIGURES_DIRNAME == "figures" + assert CHECKPOINTS_DIRNAME == "checkpoints" + assert NO_GIT == "nogit" + + +# --------------------------------------------------------------------------- +# resolve_git_commit +# --------------------------------------------------------------------------- + + +class TestResolveGitCommit: + def test_returns_nogit_without_env_var(self) -> None: + assert resolve_git_commit({}) == "nogit" + + def test_returns_nogit_for_empty_value(self) -> None: + assert resolve_git_commit({GIT_COMMIT_ENV_VAR: ""}) == "nogit" + assert resolve_git_commit({GIT_COMMIT_ENV_VAR: " "}) == "nogit" + + def test_returns_short_hash(self) -> None: + assert resolve_git_commit({GIT_COMMIT_ENV_VAR: "a1b2c3d"}) == "a1b2c3d" + + def test_accepts_dirty_suffix(self) -> None: + assert resolve_git_commit({GIT_COMMIT_ENV_VAR: "a1b2c3d-dirty"}) == "a1b2c3d-dirty" + + def test_strips_surrounding_whitespace(self) -> None: + assert resolve_git_commit({GIT_COMMIT_ENV_VAR: " a1b2c3d\n"}) == "a1b2c3d" + + @pytest.mark.parametrize( + "value", + [ + "../evil", + "a1b2c3d/x", + "a1b2 c3d", + "-dirty", + "a1b2c3d;rm", + "a" * 65, + ], + ) + def test_rejects_invalid_hash(self, value: str) -> None: + with pytest.raises(ValueError): + resolve_git_commit({GIT_COMMIT_ENV_VAR: value}) + + def test_reads_os_environ_by_default(self, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv(GIT_COMMIT_ENV_VAR, "deadbee") + assert resolve_git_commit() == "deadbee" + monkeypatch.delenv(GIT_COMMIT_ENV_VAR) + assert resolve_git_commit() == "nogit" + + +# --------------------------------------------------------------------------- +# make_run_id +# --------------------------------------------------------------------------- + + +class TestMakeRunId: + def test_format_is_timestamp_config_name_and_hash(self) -> None: + run_id = make_run_id(datetime(2026, 11, 18, 9, 5, 7), "resunet", "a1b2c3d") + assert run_id == "20261118-090507_resunet_a1b2c3d" + + def test_includes_dirty_suffix(self) -> None: + run_id = make_run_id(datetime(2026, 1, 2, 3, 4, 5), "synthetic", "a1b2c3d-dirty") + assert run_id == "20260102-030405_synthetic_a1b2c3d-dirty" + assert RUN_ID_RE.match(run_id) + + def test_includes_nogit(self) -> None: + run_id = make_run_id(datetime(2026, 1, 2, 3, 4, 5), "synthetic", NO_GIT) + assert run_id.endswith("_synthetic_nogit") + + def test_config_name_from_path_stem(self) -> None: + stem = Path("configs/resunet.yaml").stem + assert make_run_id(datetime(2026, 1, 1), stem, "abc1234") == ( + "20260101-000000_resunet_abc1234" + ) + + @pytest.mark.parametrize("name", ["", "../x", "a/b", "a b", "a\\b"]) + def test_rejects_unsafe_config_name(self, name: str) -> None: + with pytest.raises(ValueError): + make_run_id(datetime(2026, 1, 1), name, "abc1234") + + @pytest.mark.parametrize("commit", ["", "../x", "a/b"]) + def test_rejects_unsafe_git_commit(self, commit: str) -> None: + with pytest.raises(ValueError): + make_run_id(datetime(2026, 1, 1), "resunet", commit) + + +# --------------------------------------------------------------------------- +# create_run_dir +# --------------------------------------------------------------------------- + + +class TestCreateRunDir: + def test_creates_run_dir_with_figures_and_checkpoints(self, tmp_path: Path) -> None: + out_dir = tmp_path / "runs" + run_dir = create_run_dir(out_dir, "20260101-000000_synthetic_nogit") + assert run_dir == out_dir / "20260101-000000_synthetic_nogit" + assert run_dir.is_dir() + assert (run_dir / "figures").is_dir() + assert (run_dir / "checkpoints").is_dir() + + def test_creates_missing_parent_out_dir(self, tmp_path: Path) -> None: + out_dir = tmp_path / "nested" / "runs" + run_dir = create_run_dir(out_dir, "rid") + assert run_dir.is_dir() + + def test_does_not_overwrite_existing_run_dir(self, tmp_path: Path) -> None: + run_dir = create_run_dir(tmp_path, "rid") + marker = run_dir / CONFIG_FILENAME + marker.write_text("original", encoding="utf-8") + with pytest.raises(ValueError): + create_run_dir(tmp_path, "rid") + assert marker.read_text(encoding="utf-8") == "original" + + def test_existing_dir_without_subdirs_is_also_refused(self, tmp_path: Path) -> None: + (tmp_path / "rid").mkdir() + with pytest.raises(ValueError): + create_run_dir(tmp_path, "rid") + + +# --------------------------------------------------------------------------- +# BundleFingerprint +# --------------------------------------------------------------------------- + + +class TestBundleFingerprint: + def test_to_dict(self) -> None: + fp = BundleFingerprint("synthetic", 1, SHA) + assert fp.to_dict() == {"name": "synthetic", "version": 1, "manifest_sha256": SHA} + + @pytest.mark.parametrize( + ("name", "version", "sha"), + [ + ("", 1, SHA), + ("a", 0, SHA), + ("a", True, SHA), + ("a", "1", SHA), + ("a", 1, SHA[:-1]), + ("a", 1, SHA.upper()), + ("a", 1, "g" * 64), + ], + ) + def test_rejects_invalid_values(self, name: str, version: Any, sha: str) -> None: + with pytest.raises(ValueError): + BundleFingerprint(name, version, sha) + + +# --------------------------------------------------------------------------- +# build_config_document / write_config_yaml +# --------------------------------------------------------------------------- + + +class TestConfigDocument: + def test_contains_run_record(self) -> None: + config = _config(train={"seed": 7}) + fp = BundleFingerprint("synthetic", 1, SHA) + doc = build_config_document( + config, run_id="rid", git_commit="a1b2c3d-dirty", data_bundle=fp + ) + assert doc["run"] == { + "id": "rid", + "git_commit": "a1b2c3d-dirty", + "seed": 7, + "data_bundle": {"name": "synthetic", "version": 1, "manifest_sha256": SHA}, + } + + def test_bundle_fingerprint_defaults_to_null(self) -> None: + doc = build_config_document(_config(), run_id="rid", git_commit=NO_GIT) + assert doc["run"]["data_bundle"] is None + assert doc["run"]["git_commit"] == "nogit" + assert doc["run"]["seed"] == 2021 + + def test_config_contains_all_resolved_items(self) -> None: + doc = build_config_document(_config(), run_id="rid", git_commit=NO_GIT) + cfg = doc["config"] + assert set(cfg) == {"data", "augment", "model", "loss", "train", "export", "run"} + # 書いていない項目も既定値で埋まっている + assert cfg["train"]["batch_size"] == 16 + assert cfg["train"]["learning_rate"] == pytest.approx(1e-4) + assert cfg["train"]["max_epochs"] == 300 + assert cfg["train"]["early_stopping_patience"] == 30 + assert cfg["loss"] == {"bce_weight": 0.5, "bce_input": "sigmoid"} + assert cfg["augment"]["hflip_prob"] == 0.5 + assert cfg["export"]["opset"] == 11 + assert list(cfg["data"]["image_size"]) == [256, 256] + + def test_written_yaml_round_trips(self, tmp_path: Path) -> None: + config = _config( + model={"pretrained": False}, + train={"batch_size": 4, "max_epochs": 3, "device": "cpu"}, + run={"out_dir": str(tmp_path / "runs")}, + ) + fp = BundleFingerprint("synthetic", 1, SHA) + doc = build_config_document(config, run_id="rid", git_commit="abc1234", data_bundle=fp) + path = write_config_yaml(tmp_path, doc) + + assert path == tmp_path / "config.yaml" + loaded = yaml.safe_load(path.read_text(encoding="utf-8")) + assert loaded["run"] == { + "id": "rid", + "git_commit": "abc1234", + "seed": 2021, + "data_bundle": {"name": "synthetic", "version": 1, "manifest_sha256": SHA}, + } + # 書き出した設定をスキーマで読み戻すと元と同じ設定になる + assert ExperimentConfig.model_validate(loaded["config"]) == config + + def test_written_yaml_has_null_bundle_when_absent(self, tmp_path: Path) -> None: + doc = build_config_document(_config(), run_id="rid", git_commit=NO_GIT) + path = write_config_yaml(tmp_path, doc) + text = path.read_text(encoding="utf-8") + loaded = yaml.safe_load(text) + assert "data_bundle" in loaded["run"] + assert loaded["run"]["data_bundle"] is None + + +# --------------------------------------------------------------------------- +# configure_logging +# --------------------------------------------------------------------------- + + +def _own_handlers() -> list[logging.Handler]: + return [ + h + for h in logging.getLogger().handlers + if h.get_name() and h.get_name().startswith("tongue_seg_model.") + ] + + +@pytest.mark.usefixtures("restore_logging") +class TestConfigureLogging: + def test_writes_to_log_txt(self, tmp_path: Path) -> None: + configure_logging(tmp_path) + logging.getLogger("tongue_seg_model.test").info("hello-log-file") + for h in _own_handlers(): + h.flush() + text = (tmp_path / "log.txt").read_text(encoding="utf-8") + assert "hello-log-file" in text + + def test_writes_to_stderr_not_stdout( + self, tmp_path: Path, capsys: pytest.CaptureFixture[str] + ) -> None: + configure_logging(tmp_path) + logging.getLogger("tongue_seg_model.test").info("hello-console") + captured = capsys.readouterr() + assert "hello-console" in captured.err + assert "hello-console" not in captured.out + + def test_calling_twice_does_not_duplicate_handlers(self, tmp_path: Path) -> None: + configure_logging(tmp_path) + configure_logging(tmp_path) + assert len(_own_handlers()) == 2 + logging.getLogger("tongue_seg_model.test").info("only-once") + for h in _own_handlers(): + h.flush() + text = (tmp_path / "log.txt").read_text(encoding="utf-8") + assert text.count("only-once") == 1 + + def test_switching_run_dir_moves_file_output(self, tmp_path: Path) -> None: + first = tmp_path / "first" + second = tmp_path / "second" + first.mkdir() + second.mkdir() + configure_logging(first) + configure_logging(second) + logging.getLogger("tongue_seg_model.test").info("to-second") + for h in _own_handlers(): + h.flush() + assert "to-second" in (second / "log.txt").read_text(encoding="utf-8") + assert "to-second" not in (first / "log.txt").read_text(encoding="utf-8") + + def test_without_run_dir_only_console(self, tmp_path: Path) -> None: + configure_logging(tmp_path) + configure_logging(None) + handlers = _own_handlers() + assert len(handlers) == 1 + assert not isinstance(handlers[0], logging.FileHandler) + + def test_does_not_remove_foreign_handlers(self, tmp_path: Path) -> None: + root = logging.getLogger() + foreign = logging.NullHandler() + root.addHandler(foreign) + try: + configure_logging(tmp_path) + configure_logging(tmp_path) + assert foreign in root.handlers + finally: + root.removeHandler(foreign) + + def test_sets_level(self, tmp_path: Path) -> None: + configure_logging(tmp_path, level=logging.WARNING) + assert logging.getLogger().level == logging.WARNING + logging.getLogger("tongue_seg_model.test").info("suppressed-info") + for h in _own_handlers(): + h.flush() + assert "suppressed-info" not in (tmp_path / "log.txt").read_text(encoding="utf-8")