diff --git a/CLAUDE.md b/CLAUDE.md index 09855ba..f1b3e17 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -8,7 +8,7 @@ ## 開発進捗 -最新: PLAN_02 ステップ 1-4(合成データとデータの読み込み)完了.次はステップ 1-5(学習).TIASDataHub 側の作業(2-1)にも着手できる +最新: PLAN_02 ステップ 1-5(学習と `tsm-train`)完了.実データのバンドルは両サーバに配置済み(2-1・2-2 完了).次はステップ 1-6(ONNX の書き出し) ※ 本欄は**最新ステップ 1 行のみ上書き更新**.詳細な進捗履歴(動機・設計判断・失敗パターン)は [docs/PROGRESS.md](docs/PROGRESS.md) に追記する.運用ルールは `.claude/rules/progress-log.md` を参照(該当ファイル編集時に自動ロードされる). ## 必須ルール(コード実装時) diff --git a/configs/resunet.yaml b/configs/resunet.yaml index 2d03062..e3ec44c 100644 --- a/configs/resunet.yaml +++ b/configs/resunet.yaml @@ -4,8 +4,8 @@ data: bundle: - # 未確定: TIASDataHub がセグメンテーション用データの取り込みに対応していないため, - # バンドルの名前と版は仮の値である(SPEC_01「データ契約」.確定したら書き換える) + # TIASDataHub のデータセット tongue_segmentation の版 1(組 562.train 382・test 180). + # 両サーバの ~/data/tiasdata/ に配置済み(SPEC_01「データ契約」) name: tongue_segmentation version: 1 diff --git "a/docs/02_ENV/ENV_01_\346\212\200\350\241\223\343\202\271\343\202\277\343\203\203\343\202\257.md" "b/docs/02_ENV/ENV_01_\346\212\200\350\241\223\343\202\271\343\202\277\343\203\203\343\202\257.md" index c553d22..015090a 100644 --- "a/docs/02_ENV/ENV_01_\346\212\200\350\241\223\343\202\271\343\202\277\343\203\203\343\202\257.md" +++ "b/docs/02_ENV/ENV_01_\346\212\200\350\241\223\343\202\271\343\202\277\343\203\203\343\202\257.md" @@ -89,6 +89,5 @@ ## 未確定事項 (Open Items) -- TIASDataHub がセグメンテーション用のデータ(画像と正解マスクの組・学習用とテスト用の分け方)をバンドルでどう渡すか.学習データの入口はバンドルだけとし,フォルダを直接読む経路は作らない(2026-11-18 のユーザー判断).本リポジトリが必要とする内容は [SPEC_01](../04_SPEC/SPEC_01_アーキテクチャ設計.md)「データ契約」に書き,TIASDataHub 側の設計で確定する - 今の `torch.onnx` で opset 11・同じ入出力名の ONNX を書き出せるか(実装時に確認) - resnet18 の事前学習の重みの入手方法(サーバからダウンロードできるか.できなければ事前に配置する) diff --git "a/docs/02_ENV/ENV_04_\351\226\213\347\231\272\343\202\263\343\203\236\343\203\263\343\203\211.md" "b/docs/02_ENV/ENV_04_\351\226\213\347\231\272\343\202\263\343\203\236\343\203\263\343\203\211.md" index ac7ba86..076ec20 100644 --- "a/docs/02_ENV/ENV_04_\351\226\213\347\231\272\343\202\263\343\203\236\343\203\263\343\203\211.md" +++ "b/docs/02_ENV/ENV_04_\351\226\213\347\231\272\343\202\263\343\203\236\343\203\263\343\203\211.md" @@ -35,7 +35,20 @@ - `data/` は `.gitignore` 済み(合成データは Git に入らない) - 合成データを学習で読むときは,環境変数 `TIASDATA_BUNDLES` を出力先(`data/synthetic`)に向ける(未設定だと `~/data/tiasdata` を探す) -## 学習・ONNX の書き出し・リモート実行 (Training, Export & Remote) +## 学習 (Training) + +| 目的 | コマンド | 備考 | +| --- | --- | --- | +| 合成データで学習(手元) | `TIASDATA_BUNDLES=data/synthetic uv run tsm-train --config configs/synthetic.yaml` | 3 エポック・CPU で約 40 秒.先に合成データを生成しておく.PowerShell では `$env:TIASDATA_BUNDLES = 'data/synthetic'; uv run tsm-train --config configs/synthetic.yaml` | +| 実データで学習(サーバ) | `uv run tsm-train --config configs/resunet.yaml` | サーバでだけ実行する(リモート実行ツールから呼ぶ.ツールはまだ無い).※ 未検証(GPU での実行はステップ 1-8 で確かめる) | +| 時間のかかるテストを除く | `uv run pytest -m "not slow"` | 学習を実際に回すテスト(約 20 秒分)を除く | + +- 出力は `runs/<実験ID>/`(`.gitignore` 済み).実験 ID は標準出力に 1 行出る.ログは標準エラーと `log.txt` +- 終了コード: 0 成功/1 設定・バンドル・データの問題(ログに理由が 1 行出る)/2 引数の誤り +- バンドルの読み込み・事前検証で止まった実験のフォルダは `runs/` に残る(`log.txt` に理由がある.不要なら手で消す) +- 設定の `run.out_dir` 等にパスを書くときは,Git Bash 形式(`/c/Users/...`)を使わない(Windows の Python が `C:\c\Users\...` と解釈し,別の場所にフォルダができる) + +## ONNX の書き出し・リモート実行 (Export & Remote) 未定(実装フェーズでコマンドが確定した時点で追記する). 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 fd77d22..5642e72 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" @@ -18,7 +18,7 @@ | 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 で確定) | -| 1-5 学習 | 学習ループ・早期終了・最良の重みの保存・学習後の評価・`history.csv`・`metrics.json`・学習曲線(コマンド `tsm-train`) | 手元の合成データで数エポック回り,`runs/<実験ID>/` に SPEC_01 の出力がそろう | +| 1-5 学習(**完了**) | 学習ループ・早期終了・最良の重みの保存・学習後の評価・`history.csv`・`metrics.json`・学習曲線(コマンド `tsm-train`) | 手元の合成データで数エポック回り,`runs/<実験ID>/` に SPEC_01 の出力がそろう | | 1-6 ONNX の書き出し | `best.pth` から ONNX を書き出し,onnxruntime で形と PyTorch との一致を確かめる(コマンド `tsm-export`) | 合成データで学習した重みから書き出せ,入出力の形が `(1, 3, 256, 256)` → `(1, 2, 256, 256)` | | 1-7 原本の重みでの確認 | 原本の ResUNet の重み(`legacy/result/` にある `bestModel.pth`)を新しいモデルに読み込み,ONNX を書き出して,配布している `ResUNet.onnx`(`legacy/output/`)と同じ入力に対する出力を比べる | 出力の差が十分小さい(差の大きさを記録する).Claude が単独で実行してよい(2026-11-18 のユーザー判断).重みの場所は原本のコードに書かれたパスと,`legacy/output/` の `*.onnx` に絞った検索で求める(`.claude/rules/legacy.md`.csv・txt は読まない・一覧しない) | | 1-8 リモート実行 | TIASJudgeModel の `tias-remote` を移植する(コマンド `tsm-remote`.`legacy/` を送らない・回収ホワイトリスト).サーバ側の初期設定(ENV_03) | 単体テストが通る.Newton・Archimedes で合成データの学習が GPU で回り,結果を回収できる(実サーバの確認まで行う) | @@ -30,12 +30,13 @@ | ステップ | 内容 | 完了の条件 | | --- | --- | --- | -| 2-1 TIASDataHub の対応(**別リポジトリ**) | TIASDataHub でセグメンテーション用データ(研究室 PC の `E:\clinical-data\TongueSegmentation\`)の取り込みとデータセットの定義を作り,バンドルを両サーバに配置する | 両サーバの `~/data/tiasdata/` にバンドルがある.本リポジトリが要る情報(SPEC_01「データ契約」)が manifest にある | -| 2-2 データ契約の確定 | 2-1 で決まった列名・種類名に合わせて SPEC_01「データ契約」と `data/bundle.py`・合成データを直す.サブモジュールを更新する | 実データのバンドルを読め,組の数・大きさの確認を通る(サーバ上.集計値だけを見る) | +| 2-1 TIASDataHub の対応(**別リポジトリ.完了**) | TIASDataHub でセグメンテーション用データ(研究室 PC の `E:\clinical-data\TongueSegmentation\`)の取り込みとデータセットの定義を作り,バンドルを両サーバに配置する | 両サーバの `~/data/tiasdata/` にバンドルがある.本リポジトリが要る情報(SPEC_01「データ契約」)が manifest にある | +| 2-2 データ契約の確定(**完了**) | 2-1 で決まった列名・種類名に合わせて SPEC_01「データ契約」と `data/bundle.py`・合成データを直す(名前は変わらなかったので,直したのは文書とコメントだけ.サブモジュールは今の版のままで読めるので更新していない) | 実データのバンドルを読め,組の数・大きさの確認を通る(サーバ上.集計値だけを見る) | | 2-3 学習の再現 | `configs/resunet.yaml`(原本と同じ条件)でサーバで学習する | 学習が最後まで回り,テスト用データの IoU の集計値が得られる | | 2-4 配布中のモデルとの比較 | 学習したモデルの ONNX を TIASJudgeModel の `tias-seg eval` で評価し,配布している `ResUNet.onnx` の結果と比べる | 同程度の精度であることを確かめ,結果を `docs/06_TEST/` に記録する | -- 2-1 は TIASDataHub の開発計画(マイルストーン 2 以降)に入っている作業で,本リポジトリのステップではない.ステップ 1-4 が済んだ時点で Claude が着手を提案し,TIASDataHub のリポジトリで作業する +- 2-1 は TIASDataHub の開発計画(マイルストーン 2 以降)に入っている作業で,本リポジトリのステップではない.ステップ 1-4 が済んだ時点で Claude が着手を提案し,TIASDataHub のリポジトリで作業した(TIASDataHub の Issue #28.2026-11-19 に完了) +- 2-1・2-2 の完了の確認(2026-11-19): 両サーバの `~/data/tiasdata/tongue_segmentation/v1/` を,本リポジトリの読み込み(全ファイルの SHA-256 の照合つき)と全件の事前検証に通した.組 562(`train` 382・`test` 180) - 2-3 の結果が配布中のモデルと大きく違う場合は,仮定した学習条件(SPEC_02「再現の前提」)を見直す ## マイルストーン 3: 整理と引き継ぎ (M3: Cleanup & Handover) @@ -62,4 +63,4 @@ ## 最初の実装ステップ (First Step) -ステップ 1-1(設定と実験の出力)から始めた(2026-11-18 に完了).ステップ 1-2(モデル)・1-3(前処理・損失・IoU)・1-4(合成データとデータの読み込み)も完了.次は**ステップ 1-5(学習)**.`/implement ステップ 1-5 学習ループと tsm-train を作る` で開始できる.ステップ 1-4 が済んだので,TIASDataHub 側の作業(ステップ 2-1)にも着手できる(求める内容は SPEC_01「仮の契約」). +ステップ 1-1(設定と実験の出力)から始めた(2026-11-18 に完了).ステップ 1-2(モデル)・1-3(前処理・損失・IoU)・1-4(合成データとデータの読み込み)も完了.ステップ 1-5(学習)も完了(2026-11-19).次は**ステップ 1-6(ONNX の書き出し)**.`/implement ステップ 1-6 ONNX の書き出しと tsm-export を作る` で開始できる.実データのバンドルは両サーバに配置済み(ステップ 2-1・2-2 完了)なので,ステップ 1-8(リモート実行)が済めば実データでの学習(2-3)に入れる. 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 84ae976..5a844c9 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" @@ -69,17 +69,19 @@ - **実験の記録**: バンドルの指紋(`name`・`version`・`manifest_sha256`)を実験の出力に残す.患者 ID・ファイル名を含まないので回収してよい - バンドルのファイル名は内容のハッシュなので,元の画像のファイル名(患者 ID の可能性)は学習側に現れない.それでも画像ごとの結果は回収しない(「回収ホワイトリスト」) -### 仮の契約 (Provisional Contract) +### manifest の契約 (Manifest Contract) -TIASDataHub 側の設計が決まるまで,**既存のバンドルの形式(1 行 1 ファイル.列は `path`・`sha256`・`kind`・`subject_id`・`capture_id`・`<所見>.<項目>`)の中で**次の契約を置く.tiasdata の今の読み込みはこの形をそのまま受け付ける(tiasdata 側の変更は要らない).名前はすべて仮で,`src/tongue_seg_model/data/bundle.py` の定数 1 か所にまとめてある.ステップ 2-1・2-2 で確定したら本節と定数を直す. +**既存のバンドルの形式(1 行 1 ファイル.列は `path`・`sha256`・`kind`・`subject_id`・`capture_id`・`<所見>.<項目>`)の中で**次の契約を置く.名前は `src/tongue_seg_model/data/bundle.py` の定数 1 か所にまとめてある. -| 必要な情報 | manifest での表し方(仮) | +この契約は 2026-11-19 に確定した.TIASDataHub のデータセット `tongue_segmentation`(TIASDataHub の Issue #28)がこの名前のままバンドルを作り,版 1(組 562.`train` 382・`test` 180.すべて 256×256)が両サーバで本リポジトリの読み込みと全件の事前検証を通った.確定の前は「仮の契約」と呼んでいた. + +| 必要な情報 | manifest での表し方 | | --- | --- | | 画像の行 | `kind` が `tongue_seg_image` | | 正解マスクの行 | `kind` が `tongue_mask`(TIASDataHub に既にある種類名) | | 画像と正解マスクの組 | 同じ `capture_id` を持つ画像の行 1 つとマスクの行 1 つ | | 用途の区分 | 所見の列 `tongue_seg.subset`.値は `train` か `test`.組の 2 行で同じ値 | -| 患者の ID | `subject_id`.組の 2 行で同じ値(空でもよいが,空があると患者単位の分割は使えない) | +| 患者の ID | `subject_id`.組の 2 行で同じ値(空でもよいが,空があると患者単位の分割は使えない.`tongue_segmentation` の版 1 は取り込み元に患者の情報が無いため全組が空) | - データセット名は tiasdata の制約(小文字で始まり,小文字・数字・`_` だけ)に従う.本リポジトリの設定スキーマはこれより広い文字を受け付けるが,tiasdata が開くときに止まる - `SegRecord` は上の 4 項目に加えて,画像の行とマスクの行の manifest の行番号を持つ(エラーの位置を示すためと,`split.json` で組を識別するため).レコードの順序は画像の行の manifest の順 @@ -96,7 +98,7 @@ ### 合成データ (Synthetic Data) -手元で学習のコードを流すため,`scripts/make_synthetic_bundle.py` で**バンドルと同じ形**の合成データを `data/synthetic/` に作る(単色の背景に楕円を描いた画像と,その楕円のマスク.上の仮の契約どおりの manifest).目的は「落ちずに数エポック回り,指標と ONNX が書き出される」ことの確認で,精度は意味を持たない. +手元で学習のコードを流すため,`scripts/make_synthetic_bundle.py` で**バンドルと同じ形**の合成データを `data/synthetic/` に作る(単色の背景に楕円を描いた画像と,その楕円のマスク.上の契約どおりの manifest).目的は「落ちずに数エポック回り,指標と ONNX が書き出される」ことの確認で,精度は意味を持たない. - 置き場所は `data/synthetic/synthetic/v1/`(名前 `synthetic`・版 1.`configs/synthetic.yaml` と対応).既定は学習用 12 組・テスト用 4 組・256×256.患者の ID は合成の連番で 2 組ごとに 1 人(1 人は学習用かテスト用の一方だけ) - 同じ seed なら同じバイト列になる(`manifest.csv` の SHA-256 が同じ).作ったバンドルは tiasdata で開けて全ファイルの照合を通る @@ -118,7 +120,7 @@ runs/<実験ID>/ ├── config.yaml # 解決済みの設定 + git コミットハッシュ + seed + バンドルの指紋 ├── history.csv # エポックごとの学習損失・検証損失 -├── metrics.json # 最良エポック・最良の検証損失・テスト用データでの IoU の集計値(平均・中央値・最小等)+ バンドルの指紋 +├── metrics.json # 最良エポック・最良の検証損失・テスト用データでの IoU の集計値(平均・中央値・最小等)+ 件数・所要時間・バンドルの指紋(下の表) ├── log.txt ├── figures/ # 図専用(学習曲線).舌画像・マスク・予測の画像は書き込まない │ └── loss.png @@ -129,6 +131,23 @@ └── ResUNet.onnx # ONNX の書き出しを実行したとき ``` +`metrics.json` の項目(集計値だけ.画像ごとの値・ファイル名は入れない): + +| キー | 内容 | +| --- | --- | +| `best_epoch` | 検証損失が最良だったエポック(1 から数える) | +| `best_val_loss` | 最良の検証損失 | +| `epochs_run` | 実際に回したエポック数 | +| `stopped_early` | 最大エポック数に達する前に早期終了で止まったか(最後のエポックでちょうど条件を満たした場合は `false`) | +| `test_iou` | テスト用データでの IoU の集計値(`count`・`mean`・`median`・`min`・`max`・`std`) | +| `counts` | 組の数(`train`・`val`・`test`) | +| `data_bundle` | バンドルの指紋 | +| `elapsed_seconds` | 学習と評価にかかった時間(秒) | + +- `history.csv` の列は `epoch,train_loss,val_loss`(エポックは 1 から数える.原本は 0 から),`predictions.csv` の列は `image_line,iou`(`image_line` は画像の行の manifest の行番号.原本の `Log_detail.csv` は画像のファイル名を書いていた) +- `metrics.json` は厳密な JSON で書く.損失が発散して値が NaN・無限大になった項目は `null` にする +- **失敗した実験のフォルダは残す**(2026-11-19 のユーザー判断).設定の誤り(`image_size`・計算装置・実験 ID)はフォルダを作る前に止めるが,バンドルの読み込み・事前検証で止まった場合は `log.txt`(事前検証まで進んでいれば `config.yaml` も)が残る.サーバで止まった原因を回収できるようにするため + 実験 ID の書式: `YYYYmmdd-HHMMSS_<設定ファイル名>_`(設定ファイル名は拡張子を除いたもの) - サーバには `.git` を送らないため,git のハッシュは手元で求めてリモート実行ツールが環境変数で渡す([SPEC_03](SPEC_03_リモート実行仕様.md)).未コミットの変更があるときは末尾に `-dirty` が付く.環境変数が無い場合(手元での直接実行等)は `nogit` とする @@ -157,7 +176,7 @@ | コマンド(仮) | 役割 | 実行場所 | | --- | --- | --- | -| `tsm-train --config PATH` | 設定に従って学習し,学習後にテスト用データで IoU を集計して `runs/<実験ID>/` に書き出す.最後に実験 ID を出力する | サーバ(GPU).合成データなら手元 | +| `tsm-train --config PATH` | 設定に従って学習し,学習後にテスト用データで IoU を集計して `runs/<実験ID>/` に書き出す.最後に実験 ID を標準出力に 1 行出す(ログは標準エラーと `log.txt`).終了コードは成功 0・設定やデータの問題 1・引数の誤り 2 | サーバ(GPU).合成データなら手元 | | `tsm-export --run <実験ID>` | その実験の `best.pth` から ONNX を書き出し,onnxruntime で入出力の形と PyTorch の出力との一致を確かめる | サーバ.合成データなら手元 | | `tsm-remote ` | コード送信・ジョブ実行・結果回収・GPU の空き確認([SPEC_03](SPEC_03_リモート実行仕様.md)) | 手元 | | `uv run python scripts/make_synthetic_bundle.py` | 合成データ(バンドルの形)を `data/synthetic/` に作る | 手元 | 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 dad4efc..91939ee 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" @@ -96,6 +96,11 @@ | 乱数の固定の範囲 | Python・NumPy・PyTorch(CPU・GPU)の種と,cuDNN の決定的な動作の指定.`torch.use_deterministic_algorithms` は有効にしない(原本と同じ) | - エポックごとに学習損失・検証損失を `history.csv` に書き,学習後に学習曲線を `figures/loss.png` に出す +- エポックの損失は,バッチごとの損失の単純な平均(最後の小さいバッチも同じ重み.原本と同じ) +- 最良の更新は,検証損失が前の最良より厳密に小さいときだけ(同じ値では更新しない.原本と同じ).最良の初期値は原本と同じ `1e5`.検証損失が一度も最良にならなかった場合(すべて NaN 等)は重みを保存せずに止める(原本は初期の重みを保存していた) +- 学習後の評価は,メモリ上の重みではなく保存した `best.pth` を読み直して行う(値は同じ.保存したファイルが使えることを同時に確かめるため) +- 学習曲線の図には凡例を入れる(原本は保存した後に凡例を付けていたため,保存した図に凡例が無かった) +- 実装は `src/tongue_seg_model/training/` の `experiment.py`(全体の流れ)・`loop.py`(学習ループ・評価)・`early_stopping.py`・`history.py`・`metrics.py`・`reproducibility.py`・`device.py` - 原本は検証のときもデータ拡張が掛かり,並べ替えも行う.検証損失はエポックごとに少し揺れる ## 学習後の評価 (Post-training Evaluation) @@ -110,7 +115,7 @@ - これは学習の成否を見るための簡易な評価である.DeepTIAS 2.7 の手順(枠の切り出し・小領域除去を含む)での評価は TIASJudgeModel の `tias-seg eval` で行う - 255 倍して 8 ビットにするときは切り捨てる(原本と同じ.四捨五入ではない).出力 0 は 127 になる.出力が大きく float32 のシグモイドが 1.0 に丸まるとき(およそ 17 以上)だけ 255 になる - **IoU を定義できない場合**: 予測も正解も空(和集合が 0)なら止める(原本もこの場合は落ちる).正解マスクが空でないことはデータの読み込みの入口で確かめる.予測も正解も全画素が舌なら 1.0 を返す(原本は落ちる) -- モデルの出力が一様な画像では,大津の 2 値化の結果は全画素 0 になる(正解に舌があれば IoU は 0) +- モデルの出力が一様な画像では,大津の 2 値化のしきい値は 0 になる.8 ビットにした値が 0 の一様な出力(およそ −6 以下)は全画素 0(正解に舌があれば IoU は 0),0 でない一様な出力は全画素 255 になる(例: 出力 0 は全画素 127 → 全画素が舌の予測).OpenCV の動作で,原本も同じ - 実装は `src/tongue_seg_model/training/iou.py`(IoU と集計値),`src/tongue_seg_model/training/losses.py`(損失) ## ONNX の書き出し (ONNX Export) diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index 0709a42..0fedff0 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -41,3 +41,12 @@ - 設計判断: TIASDataHub が未対応のため,既存のバンドルの形式(1 行 1 ファイル)の中で仮の契約を置いた(画像とマスクを別の行にし `capture_id` で組にする.`tongue_seg.subset` で学習用とテスト用を分ける).tiasdata の今の読み込みがそのまま受け付けるので,TIASDataHub 側は取り込みとデータセットの定義を足すだけで済む見込み - 設計判断: テスト用の正解マスクが空の組は学習前に止める(学習後の IoU を定義できなくなるのを入口で防ぐ) - 未実装・後段: DataLoader と学習ループ(1-5).契約の名前の確定(2-2).設定スキーマのバンドル名の制約は tiasdata より広いまま +- [x] **ステップ 2-1・2-2 実データのバンドルとデータ契約の確定(2026-11-19)**: TIASDataHub がデータセット `tongue_segmentation` を作り(TIASDataHub の Issue #28),版 1 を Newton・Archimedes に配置した.契約の名前は仮のものから変わらず,本リポジトリのコードとサブモジュールは変更なしで読めた + - 確認: 両サーバで読み込み(全ファイルの SHA-256 の照合つき)と全件の事前検証を通した.組 562(`train` 382・`test` 180).リモート実行ツールがまだ無いので,`src/` を `/tmp` の一時フォルダに送り,サーバに既にある TIASJudgeModel の仮想環境の Python で動かした(実行後に削除.出力は件数だけ) + - 判明: `subject_id` は全組が空(取り込み元のファイル名に患者の情報が無い).患者単位の分割は使えない.既定(原本と同じ画像単位の分割)には影響しない +- [x] **ステップ 1-5 学習と `tsm-train`**: 学習ループ・早期終了・最良の重みの保存・学習後の評価と,`history.csv`・`metrics.json`・学習曲線・`predictions.csv` の書き出しを作成.手元の合成データで最後まで回り,SPEC_01 の出力がそろう.同じ設定を 2 回回すと結果が一致する + - 原本と変えた点(学習の手順は同じ): エポックは 1 から数える.評価は保存した `best.pth` を読み直して行う.図に凡例を入れる.画像ごとの結果はファイル名ではなく manifest の行番号で書く.検証損失が一度も最良にならなければ重みを保存せずに止める + - 設計判断(ユーザー判断): バンドルの読み込み・事前検証で失敗した実験のフォルダは残す(サーバで原因を回収するため).全ファイルの SHA-256 の照合は `tsm-train` のオプションにしない(受け渡しのときに TIASDataHub が照合している).`metrics.json` の NaN・無限大は `null` にする(厳密な JSON にするため) + - 失敗パターン: 動作確認で設定の `out_dir` に Git Bash 形式のパス(`/c/Users/...`)を書き,Windows の Python が `C:\c\Users\...` と解釈してリポジトリの外にフォルダができた → 設定のパスは Windows 形式か相対パスで書く(ENV_04) + - 判明: SPEC_02 の「一様な出力では大津の 2 値化が全画素 0 になる」は誤りだった(0 でない一様な値は全画素 255).実装は原本と同じ呼び出しなので,仕様書の文を直した + - 未実装・後段: GPU での学習・事前学習の重みのダウンロード・`num_workers` が 1 以上のときの動作は未確認(1-8 のサーバでの確認).`fingerprint_from_bundle` の置き場所(`run_artifacts.py` のほうが自然) diff --git a/pyproject.toml b/pyproject.toml index b112325..910edd6 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -17,6 +17,9 @@ "tiasdata", ] +[project.scripts] +tsm-train = "tongue_seg_model.cli.train:main" + [dependency-groups] dev = [ "pytest>=8.0", diff --git a/src/tongue_seg_model/cli/__init__.py b/src/tongue_seg_model/cli/__init__.py new file mode 100644 index 0000000..9de8a7f --- /dev/null +++ b/src/tongue_seg_model/cli/__init__.py @@ -0,0 +1 @@ +"""CLI のエントリポイント(`tsm-train` 等.SPEC_01「CLI」).""" diff --git a/src/tongue_seg_model/cli/train.py b/src/tongue_seg_model/cli/train.py new file mode 100644 index 0000000..0b9f92a --- /dev/null +++ b/src/tongue_seg_model/cli/train.py @@ -0,0 +1,74 @@ +"""`tsm-train --config PATH`: 設定に従って学習し,結果を `runs/<実験ID>/` に書く(SPEC_01「CLI」). + +最後に実験 ID だけを標準出力に 1 行で出す(リモート実行ツールが受け取るため.ログは標準エラーと +`log.txt` に出す). + +終了コード: + +- 0: 成功 +- 1: 設定・環境・バンドル・データの問題(`ValueError`).メッセージをログ(標準エラー. + 実験ディレクトリを作った後なら `log.txt` にも)に出し,スタックトレースは出さない +- 2: 引数の誤り(`argparse` の既定) +- それ以外の例外はスタックトレースを出して異常終了する(バグとして扱う) +""" + +from __future__ import annotations + +import argparse +import logging +import sys +from collections.abc import Sequence +from pathlib import Path + +from tongue_seg_model.schema import load_config +from tongue_seg_model.training.experiment import run_training +from tongue_seg_model.training.run_artifacts import configure_logging + +logger = logging.getLogger(__name__) + +EXIT_OK = 0 +EXIT_INPUT_ERROR = 1 + + +def _build_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser( + prog="tsm-train", + description=( + "設定に従って ResUNet を学習し,学習後にテスト用データで IoU を集計して " + "runs/<実験ID>/ に書き出す.最後に実験 ID を標準出力に出す." + ), + ) + parser.add_argument( + "--config", + type=Path, + required=True, + help="設定 YAML のパス(例: configs/resunet.yaml).拡張子を除いた名前が実験 ID に入る", + ) + return parser + + +def main(argv: Sequence[str] | None = None) -> int: + """`tsm-train` を実行する. + + Args: + argv: コマンドライン引数(プログラム名を除く).None なら `sys.argv[1:]`. + + Returns: + 終了コード(0: 成功,1: 入力の問題). + """ + args = _build_parser().parse_args(argv) + configure_logging() + config_path: Path = args.config + try: + config = load_config(config_path) + outcome = run_training(config, config_name=config_path.stem) + except ValueError as exc: + logger.error("学習を中止した: %s", exc) + return EXIT_INPUT_ERROR + sys.stdout.write(f"{outcome.run_id}\n") + sys.stdout.flush() + return EXIT_OK + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/src/tongue_seg_model/data/bundle.py b/src/tongue_seg_model/data/bundle.py index 3b73e44..257bb07 100644 --- a/src/tongue_seg_model/data/bundle.py +++ b/src/tongue_seg_model/data/bundle.py @@ -35,20 +35,20 @@ logger = logging.getLogger(__name__) # --------------------------------------------------------------------------- -# 仮のデータ契約.TIASDataHub 側の設計(PLAN_02 のステップ 2-1・2-2)で確定する. +# データ契約(SPEC_01「manifest の契約」.TIASDataHub の tongue_segmentation と同じ名前). # 名前を変えるときはここだけを直す(合成データ `data/synthetic.py` もこの定数を使う). # --------------------------------------------------------------------------- IMAGE_KIND = "tongue_seg_image" -"""画像の行の `kind`(仮).""" +"""画像の行の `kind`.""" MASK_KIND = "tongue_mask" """正解マスクの行の `kind`(TIASDataHub の SPEC_02 にある既存の種類名).""" SUBSET_ANNOTATION_KIND = "tongue_seg" -"""用途の区分を持つ所見の種類(manifest の列 `tongue_seg.subset` の前半.仮).""" +"""用途の区分を持つ所見の種類(manifest の列 `tongue_seg.subset` の前半).""" SUBSET_ANNOTATION_FIELD = "subset" -"""用途の区分を持つ所見の項目(manifest の列 `tongue_seg.subset` の後半.仮).""" +"""用途の区分を持つ所見の項目(manifest の列 `tongue_seg.subset` の後半).""" SUBSET_TRAIN = "train" """学習・検証に使う組の `subset`.""" diff --git a/src/tongue_seg_model/data/synthetic.py b/src/tongue_seg_model/data/synthetic.py index 650733b..bf13255 100644 --- a/src/tongue_seg_model/data/synthetic.py +++ b/src/tongue_seg_model/data/synthetic.py @@ -5,7 +5,7 @@ `files/.png`)で書き出す.形のずれを防ぐため,`dataset.json`・`manifest.csv`・ `SHA256SUMS` は tiasdata の関数(`build_dataset_json`・`build_manifest`・`build_sha256sums`) で作る. -manifest の `kind`・所見の列は `data/bundle.py` の仮のデータ契約の定数を使う. +manifest の `kind`・所見の列は `data/bundle.py` のデータ契約の定数を使う. 画像は単色の背景に楕円を描いた BGR の PNG,正解マスクはその楕円を白(255)・他を黒(0)にした PNG.精度は意味を持たない(「落ちずに回る」ことの確認用).同じ seed・同じ引数なら同じバイト列に diff --git a/src/tongue_seg_model/training/device.py b/src/tongue_seg_model/training/device.py new file mode 100644 index 0000000..8cc5b98 --- /dev/null +++ b/src/tongue_seg_model/training/device.py @@ -0,0 +1,60 @@ +"""計算装置の決定(設定の `train.device`.SPEC_02「設定項目」). + +`resolve_device` は GPU の有無を引数で受け取る純関数,`select_device` はそれに今の環境の +GPU の状態を渡す縁の関数である. +""" + +from __future__ import annotations + +import torch + + +def resolve_device(spec: str, *, cuda_available: bool, cuda_device_count: int) -> str: + """設定の計算装置の指定を,実際に使う装置の名前にする. + + 原本は `cuda if torch.cuda.is_available() else cpu`(設定の `auto` と同じ). + + Args: + spec: 設定の `train.device`(`auto`・`cpu`・`cuda`・`cuda:N`.形はスキーマで検証済み). + cuda_available: GPU を使えるか(`torch.cuda.is_available()`). + cuda_device_count: 使える GPU の数(`torch.cuda.device_count()`). + + Returns: + `cpu`・`cuda`・`cuda:N` のいずれか. + + Raises: + ValueError: GPU を指定したのに使えない,または番号が GPU の数以上の場合. + """ + if spec == "auto": + return "cuda" if cuda_available else "cpu" + if spec == "cpu": + return "cpu" + if not cuda_available: + raise ValueError( + f"設定 train.device が {spec} だが GPU を使えない(CPU で回すなら cpu か auto にする)" + ) + if spec.startswith("cuda:"): + index = int(spec.removeprefix("cuda:")) + if index >= cuda_device_count: + raise ValueError( + f"設定 train.device の GPU の番号 {index} が使える GPU の数 " + f"{cuda_device_count} 以上である" + ) + return spec + + +def select_device(spec: str) -> torch.device: + """今の環境で,設定の指定に合う計算装置を返す. + + Args: + spec: 設定の `train.device`. + + Returns: + 使う計算装置. + + Raises: + ValueError: 指定の GPU を使えない場合(`resolve_device`). + """ + available = torch.cuda.is_available() + count = torch.cuda.device_count() if available else 0 + return torch.device(resolve_device(spec, cuda_available=available, cuda_device_count=count)) diff --git a/src/tongue_seg_model/training/early_stopping.py b/src/tongue_seg_model/training/early_stopping.py new file mode 100644 index 0000000..0fed243 --- /dev/null +++ b/src/tongue_seg_model/training/early_stopping.py @@ -0,0 +1,67 @@ +"""最良の検証損失の追跡と早期終了の判定(SPEC_02「学習」.純関数). + +原本: `legacy/source/main.py` の学習ループ. + +- 最良の更新: `epoch_loss < best_loss`(厳密に小さいときだけ.初期値は原本の `1e5`) +- 早期終了: `(epoch - best_model_epochs) >= num_epochsEarlyStop` で止める(各エポックの検証の + 後に判定する).`best_model_epochs` の初期値は 0(最初のエポック) + +エポックの番号は本モジュールでは **1 から数える**(`history.csv`・`metrics.json` と同じ). +原本の 0 から数える番号とは 1 ずれるが,判定の結果(何エポック目で止まるか)は同じである. +""" + +from __future__ import annotations + +from dataclasses import dataclass + +# 原本の `best_loss = 1e5`.損失(BCE+Dice)はこれより十分小さいので,有限の損失なら +# 最初のエポックで必ず最良になる.NaN は最良にならない(原本と同じ). +INITIAL_BEST_LOSS = 1e5 + +# 最良が一度も更新されていないときに早期終了の基準にするエポック(原本の +# `best_model_epochs = 0` を 1 から数えた番号). +_INITIAL_REFERENCE_EPOCH = 1 + + +@dataclass(frozen=True) +class BestState: + """それまでの最良の検証損失. + + Attributes: + epoch: 最良を記録したエポック(1 から数える).まだ無ければ None. + loss: 最良の検証損失(まだ無ければ `INITIAL_BEST_LOSS`). + """ + + epoch: int | None = None + loss: float = INITIAL_BEST_LOSS + + +def update_best(state: BestState, epoch: int, val_loss: float) -> tuple[BestState, bool]: + """そのエポックの検証損失で最良を更新する. + + Args: + state: それまでの最良. + epoch: エポック(1 から数える). + val_loss: そのエポックの検証損失. + + Returns: + `(更新後の最良, 更新したか)`.更新しなければ `state` をそのまま返す. + """ + if val_loss < state.loss: + return BestState(epoch=epoch, loss=val_loss), True + return state, False + + +def should_stop(state: BestState, epoch: int, patience: int) -> bool: + """そのエポックの後で学習を止めるか(早期終了)を判定する. + + Args: + state: そのエポックの検証損失で更新した後の最良. + epoch: エポック(1 から数える). + patience: 待つエポック数(`train.early_stopping_patience`). + + Returns: + 最良のエポックから `patience` エポック以上進んでいれば True. + """ + reference = _INITIAL_REFERENCE_EPOCH if state.epoch is None else state.epoch + return epoch - reference >= patience diff --git a/src/tongue_seg_model/training/experiment.py b/src/tongue_seg_model/training/experiment.py new file mode 100644 index 0000000..ac1ed25 --- /dev/null +++ b/src/tongue_seg_model/training/experiment.py @@ -0,0 +1,345 @@ +"""1 回の実験(学習 → 学習後の評価 → 結果の書き出し)を通して実行する(`tsm-train` の本体). + +原本: `legacy/source/main.py` 全体の流れ.順序と乱数の固定の位置を原本と同じにしてある. + +1. 乱数を固定し,学習・検証用に分割する(原本: `fix_rand(2021)` → `random_split`) +2. 乱数をもう一度固定してからモデルを作る(原本: `fix_rand(2021)` → モデルの生成) +3. 学習ループ(早期終了・最良の重みの保存) +4. 最良の重みでテスト用データの IoU を計算する + +出力(`runs/<実験ID>/`)は SPEC_01「実験の出力」のとおり.実験ディレクトリを作った後の失敗は +`log.txt` に残る(呼び出し側がログに書く).ログ・例外にはファイル名・パス(データの)・ +患者 ID を出さず,件数と manifest の行番号だけを出す. +""" + +from __future__ import annotations + +import logging +import time +from collections.abc import Mapping, Sequence +from dataclasses import dataclass +from datetime import datetime +from pathlib import Path +from typing import Any + +import torch +from torch import nn +from torch.utils.data import DataLoader + +from tongue_seg_model.data.augment import SegAugment +from tongue_seg_model.data.bundle import ( + SUBSET_TEST, + SegRecord, + load_seg_bundle, + validate_image_size, + validate_records, +) +from tongue_seg_model.data.dataset import SegDataset +from tongue_seg_model.data.split import ( + SPLIT_FILENAME, + SplitResult, + build_split_document, + split_records, + write_split_json, +) +from tongue_seg_model.models.resunet import build_model +from tongue_seg_model.schema import ExperimentConfig +from tongue_seg_model.training.device import select_device +from tongue_seg_model.training.history import ( + HISTORY_FILENAME, + LOSS_FIGURE_FILENAME, + HistoryRow, + plot_loss_curve, + write_history_csv, +) +from tongue_seg_model.training.iou import summarize_ious +from tongue_seg_model.training.loop import Batch, fit, predict_ious +from tongue_seg_model.training.losses import build_loss +from tongue_seg_model.training.metrics import ( + METRICS_FILENAME, + PREDICTIONS_FILENAME, + build_metrics_document, + write_metrics_json, + write_predictions_csv, +) +from tongue_seg_model.training.reproducibility import fix_random_seed +from tongue_seg_model.training.run_artifacts import ( + CHECKPOINTS_DIRNAME, + FIGURES_DIRNAME, + BundleFingerprint, + build_config_document, + configure_logging, + create_run_dir, + make_run_id, + resolve_git_commit, + write_config_yaml, +) + +logger = logging.getLogger(__name__) + +BEST_CHECKPOINT_FILENAME = "best.pth" +"""最良の重みのファイル名(`checkpoints/` の下).""" + +# 学習後の評価は原本と同じく 1 枚ずつ回す(`DataLoader(dataset_test, batch_size=1)`). +_TEST_BATCH_SIZE = 1 + + +@dataclass(frozen=True) +class TrainingOutcome: + """1 回の実験の結果. + + Attributes: + run_id: 実験 ID. + run_dir: 実験ディレクトリ. + metrics: `metrics.json` に書いた内容. + """ + + run_id: str + run_dir: Path + metrics: dict[str, Any] + + +def fingerprint_from_bundle(fingerprint: Mapping[str, str | int]) -> BundleFingerprint: + """`SegBundle.fingerprint`(dict)を `BundleFingerprint` にする. + + Args: + fingerprint: `name`・`version`・`manifest_sha256` をキーとする dict. + + Returns: + 検証済みの指紋. + + Raises: + ValueError: キーが欠けている・値の形が不正な場合. + """ + try: + return BundleFingerprint( + name=str(fingerprint["name"]), + version=int(fingerprint["version"]), + manifest_sha256=str(fingerprint["manifest_sha256"]), + ) + except KeyError as exc: + raise ValueError(f"バンドルの指紋に {exc.args[0]} が無い") from None + + +def _loader( + records: Sequence[SegRecord], + *, + augment: SegAugment | None, + batch_size: int, + shuffle: bool, + num_workers: int, +) -> DataLoader[Batch]: + # 並べ替えの乱数はグローバルな生成器を使う(原本の DataLoader と同じ.乱数は入口で固定済み). + return DataLoader( + SegDataset(records, transform=augment), + batch_size=batch_size, + shuffle=shuffle, + num_workers=num_workers, + ) + + +def _split_and_record( + config: ExperimentConfig, + records: Sequence[SegRecord], + run_dir: Path, + fingerprint: BundleFingerprint, +) -> tuple[SplitResult, list[SegRecord], dict[str, int]]: + """学習用・検証用に分け,`split.json` を書き,件数をログに出す(乱数は呼び出し側で固定済み). + + Returns: + `(分割の結果, テスト用の組(manifest の順), 件数 {"train", "val", "test"})`. + """ + seed = config.train.seed + split = split_records(records, config.data.split, config.data.train_ratio, seed) + test_records = [record for record in records if record.subset == SUBSET_TEST] + document = build_split_document( + split, + records, + method=config.data.split, + seed=seed, + train_ratio=config.data.train_ratio, + bundle=fingerprint.to_dict(), + ) + write_split_json(run_dir / SPLIT_FILENAME, document) + counts = dict(document["counts"]) + logger.info( + "分割(%s): 学習用 %d 件・検証用 %d 件・テスト用 %d 件", + config.data.split, + counts["train"], + counts["val"], + counts["test"], + ) + return split, test_records, counts + + +def _build_loaders( + config: ExperimentConfig, split: SplitResult, test_records: Sequence[SegRecord] +) -> tuple[DataLoader[Batch], DataLoader[Batch], DataLoader[Batch]]: + """学習用・検証用・テスト用の DataLoader を作る. + + Returns: + `(学習用, 検証用, テスト用)`. + """ + # 原本と同じく,検証用にもデータ拡張を掛け,学習・検証とも毎エポック並べ替える. + augment = SegAugment(config.augment) + batch_size = config.train.batch_size + num_workers = config.train.num_workers + train_loader = _loader( + split.train, augment=augment, batch_size=batch_size, shuffle=True, num_workers=num_workers + ) + val_loader = _loader( + split.val, augment=augment, batch_size=batch_size, shuffle=True, num_workers=num_workers + ) + test_loader = _loader( + test_records, + augment=None, + batch_size=_TEST_BATCH_SIZE, + shuffle=False, + num_workers=num_workers, + ) + return train_loader, val_loader, test_loader + + +def _evaluate_on_test( + model: nn.Module, + *, + checkpoint_path: Path, + test_loader: DataLoader[Batch], + test_records: Sequence[SegRecord], + run_dir: Path, + device: torch.device, +) -> dict[str, int | float]: + """最良の重みを読み直してテスト用データの IoU を計算し,`predictions.csv` を書く. + + Returns: + IoU の集計値(`summarize_ious` の戻り値). + """ + # 原本: model.load_state_dict(best_model_wts).保存したファイルから読み直す + # (書き出した best.pth が評価に使った重みであることを保証するため). + model.load_state_dict(torch.load(checkpoint_path, map_location=device, weights_only=True)) + ious = predict_ious(model, test_loader, device) + write_predictions_csv( + run_dir / PREDICTIONS_FILENAME, [record.image_line for record in test_records], ious + ) + test_iou = summarize_ious(ious) + logger.info( + "テスト用データの IoU(%d 枚): 平均 %.4f・中央値 %.4f・最小 %.4f・最大 %.4f", + test_iou["count"], + test_iou["mean"], + test_iou["median"], + test_iou["min"], + test_iou["max"], + ) + return test_iou + + +def run_training( + config: ExperimentConfig, + *, + config_name: str, + environ: Mapping[str, str] | None = None, + now: datetime | None = None, + bundles_dir: Path | None = None, +) -> TrainingOutcome: + """設定に従って学習し,学習後にテスト用データで IoU を集計して `runs/<実験ID>/` に書く. + + 実験ディレクトリを作る前に,設定の大きさ・計算装置・実験 ID を確かめる(ここで止まれば + 何も作らない).作った後はログを `log.txt` にも出す. + + Args: + config: 検証済みの設定. + config_name: 設定ファイル名(拡張子なし.実験 ID に入る). + environ: git のハッシュ(`TSM_GIT_COMMIT`)を探す環境変数.None なら `os.environ`. + now: 実験 ID に入れる日時.None なら今の時刻. + bundles_dir: バンドルの置き場所.None なら環境変数 `TIASDATA_BUNDLES`(既定 + `~/data/tiasdata`).テスト用で,環境変数は書き換えない. + + Returns: + 実験 ID・実験ディレクトリ・`metrics.json` の内容. + + Raises: + ValueError: 設定・環境(GPU)・バンドル・データに問題がある場合,実験ディレクトリが + 既にある場合,または検証損失が一度も最良にならなかった場合. + """ + started = time.monotonic() + seed = config.train.seed + validate_image_size(config.data.image_size) + device = select_device(config.train.device) + git_commit = resolve_git_commit(environ) + run_id = make_run_id(now if now is not None else datetime.now(), config_name, git_commit) + + run_dir = create_run_dir(config.run.out_dir, run_id) + configure_logging(run_dir) + logger.info("実験 %s を始める(計算装置: %s)", run_id, device) + + bundle = load_seg_bundle(config.data.bundle, bundles_dir=bundles_dir) + fingerprint = fingerprint_from_bundle(bundle.fingerprint) + write_config_yaml( + run_dir, + build_config_document( + config, run_id=run_id, git_commit=git_commit, data_bundle=fingerprint + ), + ) + validate_records(bundle.records, config.data.image_size) + + # 原本: fix_rand(2021) → random_split(分割自体は seed の専用の生成器で行う). + fix_random_seed(seed) + split, test_records, counts = _split_and_record(config, bundle.records, run_dir, fingerprint) + train_loader, val_loader, test_loader = _build_loaders(config, split, test_records) + + # 原本: モデルを作る前に fix_rand(2021) をもう一度呼ぶ. + fix_random_seed(seed) + model = build_model(config.model).to(device) + params = sum(p.numel() for p in model.parameters() if p.requires_grad) + logger.info("モデルの学習するパラメータ数: %d", params) + criterion = build_loss(config.loss) + optimizer = torch.optim.Adam(model.parameters(), lr=config.train.learning_rate) + + history_path = run_dir / HISTORY_FILENAME + checkpoint_path = run_dir / CHECKPOINTS_DIRNAME / BEST_CHECKPOINT_FILENAME + + def _write_history(rows: Sequence[HistoryRow]) -> None: + write_history_csv(history_path, rows) + + result = fit( + model, + train_loader=train_loader, + val_loader=val_loader, + criterion=criterion, + optimizer=optimizer, + device=device, + max_epochs=config.train.max_epochs, + patience=config.train.early_stopping_patience, + checkpoint_path=checkpoint_path, + on_epoch=_write_history, + ) + plot_loss_curve(run_dir / FIGURES_DIRNAME / LOSS_FIGURE_FILENAME, result.history) + logger.info( + "学習を終えた(%d エポック.最良はエポック %d の検証損失 %.4f)", + len(result.history), + result.best_epoch, + result.best_val_loss, + ) + + test_iou = _evaluate_on_test( + model, + checkpoint_path=checkpoint_path, + test_loader=test_loader, + test_records=test_records, + run_dir=run_dir, + device=device, + ) + + metrics = build_metrics_document( + best_epoch=result.best_epoch, + best_val_loss=result.best_val_loss, + epochs_run=len(result.history), + stopped_early=result.stopped_early, + test_iou=test_iou, + counts=counts, + data_bundle=fingerprint.to_dict(), + elapsed_seconds=time.monotonic() - started, + ) + write_metrics_json(run_dir / METRICS_FILENAME, metrics) + logger.info("実験 %s を終えた(%.1f 秒)", run_id, metrics["elapsed_seconds"]) + return TrainingOutcome(run_id=run_id, run_dir=run_dir, metrics=metrics) diff --git a/src/tongue_seg_model/training/history.py b/src/tongue_seg_model/training/history.py new file mode 100644 index 0000000..de6b4ae --- /dev/null +++ b/src/tongue_seg_model/training/history.py @@ -0,0 +1,105 @@ +"""学習の履歴 `history.csv` と学習曲線 `figures/loss.png`(SPEC_01「実験の出力」). + +原本: `legacy/source/main.py` の `losses_train`・`losses_val` と「lossの可視化」. +行の組み立て(`HistoryRow`・`history_csv_text`)は純関数,書き出しと図は縁の関数である. +図は pyplot を使わず `matplotlib.figure.Figure` に直接描く(画面の無いサーバで動き, +pyplot のグローバルな状態を使わない.PNG は Agg で書き出される). +""" + +from __future__ import annotations + +import csv +import io +from collections.abc import Sequence +from dataclasses import dataclass +from pathlib import Path + +from matplotlib.backends.backend_agg import FigureCanvasAgg +from matplotlib.figure import Figure +from matplotlib.ticker import MaxNLocator + +HISTORY_FILENAME = "history.csv" +"""エポックごとの損失のファイル名(回収する).""" +LOSS_FIGURE_FILENAME = "loss.png" +"""学習曲線のファイル名(`figures/` の下.回収する).""" + +HISTORY_COLUMNS: tuple[str, ...] = ("epoch", "train_loss", "val_loss") +"""`history.csv` の列.""" + + +@dataclass(frozen=True) +class HistoryRow: + """1 エポック分の履歴. + + Attributes: + epoch: エポック(1 から数える). + train_loss: 学習損失(バッチごとの損失の平均.原本と同じ). + val_loss: 検証損失(同上). + """ + + epoch: int + train_loss: float + val_loss: float + + +def history_csv_text(rows: Sequence[HistoryRow]) -> str: + """`history.csv` の中身を作る(純関数). + + 損失は `repr` の精度(float を往復できる桁数)で書く. + + Args: + rows: エポックの順の履歴. + + Returns: + 見出し行付きの CSV の文字列(改行は LF). + """ + buffer = io.StringIO() + writer = csv.writer(buffer, lineterminator="\n") + writer.writerow(HISTORY_COLUMNS) + for row in rows: + writer.writerow([row.epoch, repr(row.train_loss), repr(row.val_loss)]) + return buffer.getvalue() + + +def write_history_csv(path: Path, rows: Sequence[HistoryRow]) -> Path: + """`history.csv` を(全エポック分を)書き出す. + + エポックごとに呼び,そのたびにファイル全体を書き直す(長い学習が途中で止まっても, + そこまでの履歴が残るように). + + Args: + path: 書き出す先(`runs/<実験ID>/history.csv`). + rows: エポックの順の履歴. + + Returns: + 書き出したパス. + """ + path.write_text(history_csv_text(rows), encoding="utf-8", newline="") + return path + + +def plot_loss_curve(path: Path, rows: Sequence[HistoryRow]) -> Path: + """学習曲線(学習損失・検証損失)を PNG に書き出す. + + 原本は `plt.savefig` の後に `plt.legend` を呼んでいたため保存した図に凡例が無かった. + 図は学習の手順に影響しないので,凡例を入れて保存する. + + Args: + path: 書き出す先(`runs/<実験ID>/figures/loss.png`). + rows: エポックの順の履歴. + + Returns: + 書き出したパス. + """ + figure = Figure(figsize=(6.4, 4.8)) + FigureCanvasAgg(figure) + axes = figure.add_subplot() + epochs = [row.epoch for row in rows] + axes.plot(epochs, [row.train_loss for row in rows], label="training loss") + axes.plot(epochs, [row.val_loss for row in rows], label="validation loss") + axes.xaxis.set_major_locator(MaxNLocator(integer=True)) + axes.set_xlabel("epoch") + axes.set_ylabel("loss") + axes.legend() + figure.savefig(path, format="png") + return path diff --git a/src/tongue_seg_model/training/loop.py b/src/tongue_seg_model/training/loop.py new file mode 100644 index 0000000..ab542f5 --- /dev/null +++ b/src/tongue_seg_model/training/loop.py @@ -0,0 +1,189 @@ +"""学習ループと学習後の評価(SPEC_02「学習」「学習後の評価」). + +原本: `legacy/source/main.py` の学習ループ(`for epoch in range(num_epochs)` 以降)と +後半の評価(`model.eval()` 以降).手順は原本と同じにしてある. + +- 各エポックで学習 → 検証の順に回す.損失はバッチごとの損失の平均(`running_loss / len(loader)`) +- 検証は `model.eval()` で勾配を計算しない(原本は `torch.set_grad_enabled(False)`) +- 検証損失が最良を更新したら重みを保存する(原本は `epoch.pth` を残したが,ここでは + `checkpoints/best.pth` を上書きする.SPEC_01「実験の出力」) +- 早期終了の判定は `training/early_stopping.py`(純関数) +- 学習後の評価は,テスト用データを 1 枚ずつ推論して `training/iou.py` の `evaluate_iou` を使う + +ファイル(`history.csv` 等)は書かない.エポックごとの記録は呼び出し側に `on_epoch` で渡す. +""" + +from __future__ import annotations + +import logging +from collections.abc import Callable, Sequence +from dataclasses import dataclass +from pathlib import Path + +import torch +from torch import nn +from torch.utils.data import DataLoader + +from tongue_seg_model.training.early_stopping import BestState, should_stop, update_best +from tongue_seg_model.training.history import HistoryRow +from tongue_seg_model.training.iou import evaluate_iou + +logger = logging.getLogger(__name__) + +Batch = tuple[torch.Tensor, torch.Tensor] +"""`(画像 (B, 3, H, W), 正解 (B, 2, H, W))` の組(`SegDataset` を束ねたもの).""" + + +@dataclass(frozen=True) +class FitResult: + """学習の結果. + + Attributes: + history: エポックの順の履歴. + best_epoch: 検証損失が最良だったエポック(1 から数える). + best_val_loss: 最良の検証損失. + stopped_early: 最大エポック数より前に早期終了で止まったか. + """ + + history: tuple[HistoryRow, ...] + best_epoch: int + best_val_loss: float + stopped_early: bool + + +def run_epoch( + model: nn.Module, + loader: DataLoader[Batch], + criterion: nn.Module, + device: torch.device, + optimizer: torch.optim.Optimizer | None = None, +) -> float: + """1 エポック分を回し,バッチごとの損失の平均を返す. + + `optimizer` を渡すと学習(`model.train()`・逆伝播・更新),渡さなければ検証 + (`model.eval()`・勾配なし)になる. + + Args: + model: モデル(出力は `(B, 2, H, W)`). + loader: データ(`(B, 3, H, W)` の画像と `(B, 2, H, W)` の正解).1 バッチ以上あること. + criterion: 損失(`DiceBCELoss`). + device: 計算装置. + optimizer: 最適化手法.None なら検証. + + Returns: + バッチごとの損失の平均(原本と同じく,バッチの大きさで重み付けしない). + """ + training = optimizer is not None + model.train(training) + total = 0.0 + with torch.set_grad_enabled(training): + for inputs, labels in loader: + inputs = inputs.to(device) + labels = labels.to(device) + if optimizer is not None: + optimizer.zero_grad() + outputs = model(inputs) + loss = criterion(outputs, labels) + if optimizer is not None: + loss.backward() + optimizer.step() + total += loss.item() + return total / len(loader) + + +def fit( + model: nn.Module, + *, + train_loader: DataLoader[Batch], + val_loader: DataLoader[Batch], + criterion: nn.Module, + optimizer: torch.optim.Optimizer, + device: torch.device, + max_epochs: int, + patience: int, + checkpoint_path: Path, + on_epoch: Callable[[Sequence[HistoryRow]], None] | None = None, +) -> FitResult: + """学習ループを回す(早期終了・最良の重みの保存を含む). + + Args: + model: モデル(`device` に載せてあること). + train_loader: 学習用のデータ. + val_loader: 検証用のデータ. + criterion: 損失. + optimizer: 最適化手法. + device: 計算装置. + max_epochs: 最大エポック数. + patience: 早期終了の待ち数. + checkpoint_path: 最良の重み(`state_dict`)を上書き保存する先. + on_epoch: 各エポックの後にそれまでの履歴を渡して呼ぶ関数(`history.csv` の書き出し等). + + Returns: + 学習の結果. + + Raises: + ValueError: 検証損失が一度も最良にならなかった(すべて NaN 等)場合.保存する重みが無い. + """ + history: list[HistoryRow] = [] + best = BestState() + stopped_early = False + for epoch in range(1, max_epochs + 1): + train_loss = run_epoch(model, train_loader, criterion, device, optimizer) + val_loss = run_epoch(model, val_loader, criterion, device) + history.append(HistoryRow(epoch=epoch, train_loss=train_loss, val_loss=val_loss)) + best, improved = update_best(best, epoch, val_loss) + if improved: + torch.save(model.state_dict(), checkpoint_path) + logger.info( + "エポック %d/%d: 学習損失 %.4f・検証損失 %.4f%s", + epoch, + max_epochs, + train_loss, + val_loss, + "(最良.重みを保存した)" if improved else "", + ) + if on_epoch is not None: + on_epoch(tuple(history)) + if should_stop(best, epoch, patience): + stopped_early = epoch < max_epochs + if stopped_early: + logger.info("検証損失が %d エポック続けて最良を更新しなかったので止める", patience) + break + if best.epoch is None: + raise ValueError( + "検証損失が一度も有限の値で最良にならなかった(NaN 等)ため,保存する重みが無い" + ) + return FitResult( + history=tuple(history), + best_epoch=best.epoch, + best_val_loss=best.loss, + stopped_early=stopped_early, + ) + + +def predict_ious(model: nn.Module, loader: DataLoader[Batch], device: torch.device) -> list[float]: + """テスト用データを推論し,画像ごとの IoU を原本の手順で計算する. + + 原本はバッチの大きさ 1・並べ替えなしで回す.ここでもバッチの中の 1 枚ずつ + `evaluate_iou`(シグモイド → 255 倍の切り捨て → 大津の 2 値化 → IoU)を使う. + + Args: + model: 最良の重みを読み込んだモデル(`device` に載せてあること). + loader: テスト用のデータ(データ拡張なし・並べ替えなし). + device: 計算装置. + + Returns: + 画像ごとの IoU(`loader` の順). + + Raises: + ValueError: 予測も正解も空の画像がある場合(`evaluate_iou`.入口の事前検証で + 正解が空でないことを確かめてあるので通常は起きない). + """ + model.eval() + ious: list[float] = [] + with torch.no_grad(): + for inputs, labels in loader: + outputs = model(inputs.to(device)) + for output, label in zip(outputs, labels, strict=True): + ious.append(evaluate_iou(output, label)) + return ious diff --git a/src/tongue_seg_model/training/metrics.py b/src/tongue_seg_model/training/metrics.py new file mode 100644 index 0000000..eb80bba --- /dev/null +++ b/src/tongue_seg_model/training/metrics.py @@ -0,0 +1,144 @@ +"""学習の結果の記録 `metrics.json` と画像ごとの IoU `predictions.csv`(SPEC_01「実験の出力」). + +- `metrics.json`(回収する): 集計値だけを書く(最良エポック・最良の検証損失・テスト用データでの + IoU の集計値・件数・バンドルの指紋).画像ごとの値・ファイル名・患者 ID は書かない +- `predictions.csv`(回収しない): テスト用データの画像ごとの IoU.組は画像の行の manifest の + 行番号(`split.json` と同じ識別)で表し,パス・ID は書かない + +原本: `legacy/source/main.py` の `Log.txt`(全体平均)と `Log_detail.csv`(画像のファイル名と +IoU).原本の `Log_detail.csv` は画像のファイル名を含んでいたが,ここでは行番号にする. +内容の組み立ては純関数,書き出しは縁の関数である. +""" + +from __future__ import annotations + +import csv +import io +import json +import math +from collections.abc import Mapping, Sequence +from pathlib import Path +from typing import Any + +METRICS_FILENAME = "metrics.json" +"""集計値のファイル名(回収する).""" +PREDICTIONS_FILENAME = "predictions.csv" +"""画像ごとの IoU のファイル名(回収しない.SPEC_01「回収ホワイトリスト」).""" + +PREDICTION_COLUMNS: tuple[str, ...] = ("image_line", "iou") +"""`predictions.csv` の列.""" + + +def build_metrics_document( + *, + best_epoch: int, + best_val_loss: float, + epochs_run: int, + stopped_early: bool, + test_iou: Mapping[str, int | float], + counts: Mapping[str, int], + data_bundle: Mapping[str, str | int], + elapsed_seconds: float, +) -> dict[str, Any]: + """`metrics.json` に書く内容を作る(純関数). + + Args: + best_epoch: 検証損失が最良だったエポック(1 から数える). + best_val_loss: 最良の検証損失. + epochs_run: 実際に回したエポック数. + stopped_early: 早期終了で止まったか(最大エポック数より前に止まったか). + test_iou: テスト用データでの IoU の集計値(`summarize_ious` の戻り値). + counts: 学習用・検証用・テスト用の組の数(`train`・`val`・`test`). + data_bundle: バンドルの指紋(`BundleFingerprint.to_dict` の戻り値). + elapsed_seconds: 学習と評価にかかった時間(秒). + + Returns: + JSON に書き出せる dict. + """ + return { + "best_epoch": best_epoch, + "best_val_loss": best_val_loss, + "epochs_run": epochs_run, + "stopped_early": stopped_early, + "test_iou": dict(test_iou), + "counts": dict(counts), + "data_bundle": dict(data_bundle), + "elapsed_seconds": elapsed_seconds, + } + + +def json_safe(value: Any) -> Any: + """NaN・無限大を None に置き換える(純関数). + + Python の `json` は NaN・無限大を `NaN`・`Infinity` と書き,厳密な JSON でなくなる + (他の言語・ツールで読めない).損失が発散した実験でも `metrics.json` を読めるように, + 有限でない値は `null` にする. + + Args: + value: JSON に書く値(dict・list・tuple は中までたどる). + + Returns: + 有限でない float を None に置き換えた値.dict・list は新しく作る(tuple は list になる). + """ + if isinstance(value, float) and not math.isfinite(value): + return None + if isinstance(value, Mapping): + return {key: json_safe(item) for key, item in value.items()} + if isinstance(value, list | tuple): + return [json_safe(item) for item in value] + return value + + +def write_metrics_json(path: Path, document: Mapping[str, Any]) -> Path: + """`metrics.json` を書き出す. + + 有限でない値(NaN・無限大)は `null` と書く(`json_safe`). + + Args: + path: 書き出す先(`runs/<実験ID>/metrics.json`). + document: `build_metrics_document` の戻り値. + + Returns: + 書き出したパス. + """ + text = json.dumps(json_safe(document), ensure_ascii=False, indent=2, allow_nan=False) + "\n" + path.write_text(text, encoding="utf-8", newline="") + return path + + +def predictions_csv_text(image_lines: Sequence[int], ious: Sequence[float]) -> str: + """`predictions.csv` の中身を作る(純関数). + + Args: + image_lines: テスト用の組の画像の行の manifest の行番号(評価した順). + ious: 同じ順の画像ごとの IoU. + + Returns: + 見出し行付きの CSV の文字列(改行は LF). + + Raises: + RuntimeError: 行番号と IoU の数が一致しない場合(内部の誤り). + """ + if len(image_lines) != len(ious): + raise RuntimeError(f"行番号の数 {len(image_lines)} と IoU の数 {len(ious)} が一致しない") + buffer = io.StringIO() + writer = csv.writer(buffer, lineterminator="\n") + writer.writerow(PREDICTION_COLUMNS) + for line, iou in zip(image_lines, ious, strict=True): + writer.writerow([line, repr(float(iou))]) + return buffer.getvalue() + + +def write_predictions_csv(path: Path, image_lines: Sequence[int], ious: Sequence[float]) -> Path: + """`predictions.csv` を書き出す. + + Args: + path: 書き出す先(`runs/<実験ID>/predictions.csv`). + image_lines: テスト用の組の画像の行の manifest の行番号. + ious: 同じ順の画像ごとの IoU. + + Returns: + 書き出したパス. + """ + path.write_text(predictions_csv_text(image_lines, ious), encoding="utf-8", newline="") + return path diff --git a/src/tongue_seg_model/training/reproducibility.py b/src/tongue_seg_model/training/reproducibility.py new file mode 100644 index 0000000..f624114 --- /dev/null +++ b/src/tongue_seg_model/training/reproducibility.py @@ -0,0 +1,34 @@ +"""乱数の固定(SPEC_02「学習」.原本: `legacy/source/utils.py` の `fix_rand`). + +学習の入口(`training/experiment.py`)からだけ呼ぶ(`.claude/rules/coding-style.md` +「機械学習コードの規則」). +""" + +from __future__ import annotations + +import os +import random + +import numpy as np +import torch + + +def fix_random_seed(seed: int) -> None: + """Python・NumPy・PyTorch(CPU・GPU)の乱数の種と cuDNN の決定的な動作を設定する. + + 原本の `fix_rand` と同じ範囲を同じ順に設定する.`torch.use_deterministic_algorithms` は + 有効にしない(原本は `False` を明示している).`PYTHONHASHSEED` は実行中のプロセスには + 効かないが,原本どおり設定する(子プロセスに引き継がれる). + + Args: + seed: 乱数の種(`train.seed`.0〜2**32−1). + """ + np.random.seed(seed) + random.seed(seed) + torch.manual_seed(seed) + torch.cuda.manual_seed(seed) + torch.cuda.manual_seed_all(seed) + torch.backends.cudnn.deterministic = True + torch.backends.cudnn.benchmark = False + os.environ["PYTHONHASHSEED"] = str(seed) + torch.use_deterministic_algorithms(False) diff --git a/tests/cli/test_train.py b/tests/cli/test_train.py new file mode 100644 index 0000000..e706325 --- /dev/null +++ b/tests/cli/test_train.py @@ -0,0 +1,151 @@ +"""`tsm-train --config PATH`(`cli/train.py`)の統合テスト. + +期待値は SPEC_01「CLI」(設定に従って学習し,最後に実験 ID を出力する)と,CLI の終了コード +(0: 成功・1: 設定・環境・バンドル・データの問題でスタックトレースを出さない・2: 引数の誤り)を +基準にする.`main` は `bundles_dir` を受け取らないので,バンドルの置き場所は環境変数 +`TIASDATA_BUNDLES` を monkeypatch で `tmp_path` に向ける(テスト後に元に戻る). +""" + +from __future__ import annotations + +import importlib.metadata +import logging +import re +from collections.abc import Iterator +from pathlib import Path +from typing import Any + +import pytest +import yaml + +from tongue_seg_model.cli.train import main +from tongue_seg_model.data.synthetic import write_synthetic_bundle +from tongue_seg_model.training.run_artifacts import GIT_COMMIT_ENV_VAR, configure_logging + +SIZE = (64, 64) +BUNDLES_ENV_VAR = "TIASDATA_BUNDLES" +RUN_ID_RE = re.compile(r"^\d{8}-\d{6}_tiny_abc1234$") + + +@pytest.fixture(autouse=True) +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) + + +@pytest.fixture +def env(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path: + """バンドルの置き場所と git のハッシュを tmp_path 向けに設定し,置き場所を返す.""" + bundles = tmp_path / "bundles" + bundles.mkdir() + monkeypatch.setenv(BUNDLES_ENV_VAR, str(bundles)) + monkeypatch.setenv(GIT_COMMIT_ENV_VAR, "abc1234") + return bundles + + +def _write_config(tmp_path: Path, **overrides: Any) -> Path: + raw: dict[str, Any] = { + "data": {"bundle": {"name": "synthetic", "version": 1}, "image_size": list(SIZE)}, + "model": {"pretrained": False}, + "train": {"batch_size": 2, "max_epochs": 1, "device": "cpu", "seed": 0}, + "run": {"out_dir": str(tmp_path / "runs")}, + } + for section, values in overrides.items(): + raw.setdefault(section, {}).update(values) + path = tmp_path / "tiny.yaml" + path.write_text(yaml.safe_dump(raw), encoding="utf-8") + return path + + +def test_entry_point_is_registered() -> None: + points = importlib.metadata.entry_points(group="console_scripts", name="tsm-train") + assert [p.value for p in points] == ["tongue_seg_model.cli.train:main"] + + +class TestArgumentErrors: + def test_missing_config_option_exits_with_2(self) -> None: + with pytest.raises(SystemExit) as info: + main([]) + assert info.value.code == 2 + + def test_unknown_option_exits_with_2(self, tmp_path: Path) -> None: + with pytest.raises(SystemExit) as info: + main(["--config", str(tmp_path / "x.yaml"), "--epochs", "3"]) + assert info.value.code == 2 + + +class TestInputErrors: + def _assert_clean_failure(self, capsys: pytest.CaptureFixture[str]) -> str: + captured = capsys.readouterr() + assert captured.out == "" + assert "Traceback" not in captured.err + assert "学習を中止した" in captured.err + return captured.err + + def test_missing_config_file( + self, tmp_path: Path, env: Path, capsys: pytest.CaptureFixture[str] + ) -> None: + assert main(["--config", str(tmp_path / "missing.yaml")]) == 1 + self._assert_clean_failure(capsys) + + def test_unknown_key_in_config( + self, tmp_path: Path, env: Path, capsys: pytest.CaptureFixture[str] + ) -> None: + path = _write_config(tmp_path, train={"unknown_key": 1}) + assert main(["--config", str(path)]) == 1 + self._assert_clean_failure(capsys) + assert not (tmp_path / "runs").exists() + + def test_image_size_not_multiple_of_32_creates_nothing( + self, tmp_path: Path, env: Path, capsys: pytest.CaptureFixture[str] + ) -> None: + path = _write_config(tmp_path, data={"image_size": [48, 48]}) + assert main(["--config", str(path)]) == 1 + self._assert_clean_failure(capsys) + runs = tmp_path / "runs" + assert not runs.exists() or not any(runs.iterdir()) + + def test_missing_bundle_keeps_run_dir_and_logs_reason( + self, tmp_path: Path, env: Path, capsys: pytest.CaptureFixture[str] + ) -> None: + path = _write_config(tmp_path) + assert main(["--config", str(path)]) == 1 + self._assert_clean_failure(capsys) + run_dirs = list((tmp_path / "runs").iterdir()) + assert len(run_dirs) == 1 + assert RUN_ID_RE.match(run_dirs[0].name) + for handler in logging.getLogger().handlers: + handler.flush() + log = (run_dirs[0] / "log.txt").read_text(encoding="utf-8") + assert "学習を中止した" in log + assert "Traceback" not in log + assert not (run_dirs[0] / "metrics.json").exists() + + +@pytest.mark.slow +def test_successful_run_prints_only_run_id( + tmp_path: Path, env: Path, capsys: pytest.CaptureFixture[str] +) -> None: + write_synthetic_bundle(env, train_pairs=6, test_pairs=2, seed=0, image_size=SIZE) + path = _write_config(tmp_path) + assert main(["--config", str(path)]) == 0 + captured = capsys.readouterr() + lines = captured.out.split("\n") + assert len(lines) == 2 and lines[1] == "" + run_id = lines[0] + assert RUN_ID_RE.match(run_id) + run_dir = tmp_path / "runs" / run_id + for name in ("config.yaml", "history.csv", "metrics.json", "log.txt", "predictions.csv"): + assert (run_dir / name).is_file() + assert (run_dir / "checkpoints" / "best.pth").is_file() + assert (run_dir / "figures" / "loss.png").is_file() + # ログは標準エラーに出る(標準出力は実験 ID だけ) + assert run_id in captured.err diff --git a/tests/training/test_device.py b/tests/training/test_device.py new file mode 100644 index 0000000..f4ff1f5 --- /dev/null +++ b/tests/training/test_device.py @@ -0,0 +1,57 @@ +"""計算装置の決定(`training/device.py`)のテスト. + +期待値は SPEC_02「設定項目」の `train.device`(`auto`=GPU があれば使い無ければ CPU・`cpu`・ +`cuda`・`cuda:<番号>`)を基準にする.GPU の有無は引数で渡す(実際の GPU に依存しない). +""" + +from __future__ import annotations + +import pytest +import torch + +from tongue_seg_model.training.device import resolve_device, select_device + + +class TestResolveDevice: + def test_auto_uses_gpu_when_available(self) -> None: + assert resolve_device("auto", cuda_available=True, cuda_device_count=2) == "cuda" + + def test_auto_falls_back_to_cpu_without_gpu(self) -> None: + assert resolve_device("auto", cuda_available=False, cuda_device_count=0) == "cpu" + + @pytest.mark.parametrize("available", [True, False]) + def test_cpu_is_always_cpu(self, available: bool) -> None: + count = 1 if available else 0 + assert resolve_device("cpu", cuda_available=available, cuda_device_count=count) == "cpu" + + def test_cuda_with_gpu(self) -> None: + assert resolve_device("cuda", cuda_available=True, cuda_device_count=1) == "cuda" + + @pytest.mark.parametrize("spec", ["cuda", "cuda:0", "cuda:3"]) + def test_gpu_requested_without_gpu_raises(self, spec: str) -> None: + with pytest.raises(ValueError): + resolve_device(spec, cuda_available=False, cuda_device_count=0) + + @pytest.mark.parametrize(("spec", "count"), [("cuda:0", 1), ("cuda:1", 2), ("cuda:3", 4)]) + def test_cuda_index_within_count(self, spec: str, count: int) -> None: + assert resolve_device(spec, cuda_available=True, cuda_device_count=count) == spec + + @pytest.mark.parametrize(("spec", "count"), [("cuda:1", 1), ("cuda:2", 2), ("cuda:7", 4)]) + def test_cuda_index_out_of_range_raises(self, spec: str, count: int) -> None: + with pytest.raises(ValueError): + resolve_device(spec, cuda_available=True, cuda_device_count=count) + + +def test_select_device_cpu_returns_torch_device() -> None: + assert select_device("cpu") == torch.device("cpu") + + +def test_select_device_auto_matches_environment() -> None: + expected = "cuda" if torch.cuda.is_available() else "cpu" + assert select_device("auto").type == expected + + +@pytest.mark.skipif(torch.cuda.is_available(), reason="GPU が無い環境でだけ確かめる") +def test_select_device_cuda_without_gpu_raises() -> None: + with pytest.raises(ValueError): + select_device("cuda") diff --git a/tests/training/test_early_stopping.py b/tests/training/test_early_stopping.py new file mode 100644 index 0000000..7d1c47c --- /dev/null +++ b/tests/training/test_early_stopping.py @@ -0,0 +1,129 @@ +"""最良の検証損失の追跡と早期終了の判定(`training/early_stopping.py`)のテスト. + +期待値は SPEC_02「学習」(検証損失が `early_stopping_patience` エポック続けて最良を更新しなければ +止める)と原本 `legacy/source/main.py` の判定(`epoch_loss < best_loss` で更新,初期値 `1e5`, +`(epoch - best_model_epochs) >= num_epochsEarlyStop` で止める.エポックは 0 から数える)を +基準にする.エポックは本モジュールでは 1 から数える. +""" + +from __future__ import annotations + +import math +from collections.abc import Sequence + +import pytest + +from tongue_seg_model.training.early_stopping import ( + INITIAL_BEST_LOSS, + BestState, + should_stop, + update_best, +) + + +def _original_stop_epoch(val_losses: Sequence[float], patience: int) -> int: + """原本のループで何エポック回るか(1 から数えた最後のエポック)を数える(参照実装).""" + best_loss = 1e5 + best_model_epochs = 0 + for epoch, loss in enumerate(val_losses): # 原本は 0 から数える + if loss < best_loss: + best_loss = loss + best_model_epochs = epoch + if (epoch - best_model_epochs) >= patience: + return epoch + 1 + return len(val_losses) + + +def _stop_epoch(val_losses: Sequence[float], patience: int) -> int: + state = BestState() + for epoch, loss in enumerate(val_losses, start=1): + state, _ = update_best(state, epoch, loss) + if should_stop(state, epoch, patience): + return epoch + return len(val_losses) + + +def test_initial_state_matches_original() -> None: + assert INITIAL_BEST_LOSS == 1e5 + state = BestState() + assert state.epoch is None + assert state.loss == 1e5 + + +class TestUpdateBest: + def test_first_finite_loss_becomes_best(self) -> None: + state, improved = update_best(BestState(), 1, 0.8) + assert improved + assert state == BestState(epoch=1, loss=0.8) + + def test_smaller_loss_updates(self) -> None: + state, improved = update_best(BestState(epoch=1, loss=0.8), 2, 0.5) + assert improved + assert state == BestState(epoch=2, loss=0.5) + + def test_equal_loss_does_not_update(self) -> None: + before = BestState(epoch=1, loss=0.5) + state, improved = update_best(before, 2, 0.5) + assert not improved + assert state == before + + def test_larger_loss_does_not_update(self) -> None: + before = BestState(epoch=1, loss=0.5) + state, improved = update_best(before, 2, 0.6) + assert not improved + assert state == before + + def test_nan_never_becomes_best(self) -> None: + state, improved = update_best(BestState(), 1, math.nan) + assert not improved + assert state.epoch is None + state, improved = update_best(BestState(epoch=1, loss=0.5), 2, math.nan) + assert not improved + assert state == BestState(epoch=1, loss=0.5) + + def test_loss_not_below_initial_value_does_not_update(self) -> None: + state, improved = update_best(BestState(), 1, 1e5) + assert not improved + assert state.epoch is None + + +class TestShouldStop: + def test_stops_when_patience_epochs_passed_since_best(self) -> None: + best = BestState(epoch=3, loss=0.1) + assert not should_stop(best, 3, 2) + assert not should_stop(best, 4, 2) + assert should_stop(best, 5, 2) + + def test_patience_one_stops_right_after_first_non_improving_epoch(self) -> None: + best = BestState(epoch=1, loss=0.1) + assert not should_stop(best, 1, 1) + assert should_stop(best, 2, 1) + + def test_without_best_counts_from_first_epoch(self) -> None: + # 原本の best_model_epochs = 0(1 から数えると 1)を基準にする + assert not should_stop(BestState(), 1, 2) + assert not should_stop(BestState(), 2, 2) + assert should_stop(BestState(), 3, 2) + + +@pytest.mark.parametrize( + ("val_losses", "patience"), + [ + ([1.0, 0.9, 0.8, 0.7, 0.6], 2), # 毎回更新 → 最後まで + ([0.5, 0.6, 0.7, 0.8, 0.9], 2), # 最初だけ最良 → 3 エポックで止まる + ([0.5, 0.6, 0.4, 0.45, 0.45, 0.45, 0.3], 3), + ([0.5, 0.5, 0.5, 0.5], 2), # 同じ値は更新しない + ([math.nan, math.nan, math.nan, math.nan], 2), + ([math.nan, 0.5, 0.6, 0.7, 0.8], 2), + ([0.9, 0.8, 0.85, 0.7, 0.75, 0.76, 0.77, 0.78], 3), + ([0.3] * 40, 30), + ], +) +def test_stop_epoch_matches_original_loop(val_losses: list[float], patience: int) -> None: + assert _stop_epoch(val_losses, patience) == _original_stop_epoch(val_losses, patience) + + +def test_concrete_stop_epoch_with_default_patience() -> None: + # 最初のエポックだけが最良なら,30 エポック待って 31 エポック目の後で止まる + losses = [0.3] + [0.4] * 100 + assert _stop_epoch(losses, 30) == 31 diff --git a/tests/training/test_experiment.py b/tests/training/test_experiment.py new file mode 100644 index 0000000..148c956 --- /dev/null +++ b/tests/training/test_experiment.py @@ -0,0 +1,454 @@ +"""1 回の実験を通す `run_training`(`training/experiment.py`)のテスト. + +期待値は SPEC_01「実験の出力」(`runs/<実験ID>/` のファイル構成・実験 ID の書式・同じ実験 ID の +フォルダがあれば止める・`figures/` には図だけ)・「回収ホワイトリスト」(回収するファイルに画像の +ファイル名・患者 ID が入らないこと)と SPEC_02「学習」「学習後の評価」を基準にする. + +合成バンドルを `tmp_path` に作り,`bundles_dir`・`environ`・`now` を引数で渡す(環境変数を +書き換えない).学習を回すテストは `slow`. +""" + +from __future__ import annotations + +import csv +import io +import json +import logging +import re +from collections.abc import Iterator +from dataclasses import dataclass +from datetime import datetime +from pathlib import Path +from typing import Any + +import pytest +import torch +import yaml + +from tongue_seg_model.data.synthetic import write_synthetic_bundle +from tongue_seg_model.models.resunet import ResUNet +from tongue_seg_model.schema import ExperimentConfig +from tongue_seg_model.training.experiment import run_training +from tongue_seg_model.training.run_artifacts import GIT_COMMIT_ENV_VAR, configure_logging + +SIZE = (64, 64) +TRAIN_PAIRS = 6 +TEST_PAIRS = 2 +NOW = datetime(2026, 11, 19, 10, 20, 30) +COMMIT = "abc1234-dirty" +ENVIRON = {GIT_COMMIT_ENV_VAR: COMMIT} +RUN_ID = "20261119-102030_synthetic_abc1234-dirty" + +# SPEC_01「実験の出力」のファイル構成(ONNX は書き出しを実行したときだけ) +EXPECTED_TOP_LEVEL = { + "config.yaml", + "history.csv", + "metrics.json", + "log.txt", + "figures", + "split.json", + "predictions.csv", + "checkpoints", +} +TEXT_OUTPUTS = ( + "config.yaml", + "history.csv", + "metrics.json", + "log.txt", + "split.json", + "predictions.csv", +) + + +def _close_own_handlers() -> None: + configure_logging(None) + root = logging.getLogger() + for handler in list(root.handlers): + if handler.get_name() and handler.get_name().startswith("tongue_seg_model."): + root.removeHandler(handler) + handler.close() + + +@pytest.fixture +def restore_logging() -> Iterator[None]: + """root logger の状態を戻し,`log.txt` のハンドラを閉じる(Windows での削除失敗を防ぐ).""" + level = logging.getLogger().level + yield + _close_own_handlers() + logging.getLogger().setLevel(level) + + +def _config(out_dir: Path, **overrides: Any) -> ExperimentConfig: + raw: dict[str, Any] = { + "data": {"bundle": {"name": "synthetic", "version": 1}, "image_size": list(SIZE)}, + "model": {"pretrained": False}, + "train": { + "batch_size": 2, + "max_epochs": 2, + "early_stopping_patience": 5, + "device": "cpu", + "seed": 0, + }, + "run": {"out_dir": str(out_dir)}, + } + for section, values in overrides.items(): + raw.setdefault(section, {}).update(values) + return ExperimentConfig.model_validate(raw) + + +def _write_bundle(bundles_dir: Path) -> Path: + return write_synthetic_bundle( + bundles_dir, train_pairs=TRAIN_PAIRS, test_pairs=TEST_PAIRS, seed=0, image_size=SIZE + ) + + +@dataclass(frozen=True) +class TrainedRun: + outcome: Any + bundle_dir: Path + out_dir: Path + + +@pytest.fixture(scope="module") +def trained(tmp_path_factory: pytest.TempPathFactory) -> Iterator[TrainedRun]: + """合成バンドルで 2 エポック回した実験(このモジュールの slow のテストで共有する).""" + root = tmp_path_factory.mktemp("experiment") + bundle_dir = _write_bundle(root / "bundles") + out_dir = root / "runs" + level = logging.getLogger().level + try: + outcome = run_training( + _config(out_dir), + config_name="synthetic", + environ=ENVIRON, + now=NOW, + bundles_dir=root / "bundles", + ) + yield TrainedRun(outcome=outcome, bundle_dir=bundle_dir, out_dir=out_dir) + finally: + _close_own_handlers() + logging.getLogger().setLevel(level) + + +def _read_csv(path: Path) -> list[dict[str, str]]: + return list(csv.DictReader(io.StringIO(path.read_text(encoding="utf-8")))) + + +def _strict_json(path: Path) -> Any: + def _reject(constant: str) -> Any: + raise AssertionError(f"厳密な JSON でない値 {constant} がある") + + return json.loads(path.read_text(encoding="utf-8"), parse_constant=_reject) + + +# --------------------------------------------------------------------------- +# 一通り回したときの出力 +# --------------------------------------------------------------------------- + + +@pytest.mark.slow +class TestOutputs: + def test_run_id_and_dir(self, trained: TrainedRun) -> None: + assert trained.outcome.run_id == RUN_ID + assert trained.outcome.run_dir == trained.out_dir / RUN_ID + assert trained.outcome.run_dir.is_dir() + + def test_files_match_spec01(self, trained: TrainedRun) -> None: + run_dir = trained.outcome.run_dir + assert {p.name for p in run_dir.iterdir()} == EXPECTED_TOP_LEVEL + + def test_figures_contains_only_loss_png(self, trained: TrainedRun) -> None: + figures = trained.outcome.run_dir / "figures" + assert [p.name for p in figures.iterdir()] == ["loss.png"] + assert (figures / "loss.png").read_bytes().startswith(b"\x89PNG\r\n\x1a\n") + + def test_no_png_outside_figures(self, trained: TrainedRun) -> None: + run_dir = trained.outcome.run_dir + pngs = [p.relative_to(run_dir).as_posix() for p in run_dir.rglob("*.png")] + assert pngs == ["figures/loss.png"] + + def test_checkpoints_contains_only_best_pth(self, trained: TrainedRun) -> None: + checkpoints = trained.outcome.run_dir / "checkpoints" + assert [p.name for p in checkpoints.iterdir()] == ["best.pth"] + + def test_best_pth_loads_into_resunet(self, trained: TrainedRun) -> None: + state = torch.load(trained.outcome.run_dir / "checkpoints" / "best.pth", weights_only=True) + ResUNet(pretrained=False).load_state_dict(state) + + def test_history_csv(self, trained: TrainedRun) -> None: + path = trained.outcome.run_dir / "history.csv" + assert path.read_text(encoding="utf-8").split("\n")[0] == "epoch,train_loss,val_loss" + rows = _read_csv(path) + assert [int(r["epoch"]) for r in rows] == list( + range(1, trained.outcome.metrics["epochs_run"] + 1) + ) + for row in rows: + float(row["train_loss"]) + float(row["val_loss"]) + + def test_metrics_json(self, trained: TrainedRun) -> None: + metrics = _strict_json(trained.outcome.run_dir / "metrics.json") + assert metrics == trained.outcome.metrics + assert set(metrics) == { + "best_epoch", + "best_val_loss", + "epochs_run", + "stopped_early", + "test_iou", + "counts", + "data_bundle", + "elapsed_seconds", + } + assert metrics["epochs_run"] == 2 + assert metrics["stopped_early"] is False + assert 1 <= metrics["best_epoch"] <= metrics["epochs_run"] + assert set(metrics["test_iou"]) == {"count", "mean", "median", "min", "max", "std"} + assert metrics["test_iou"]["count"] == TEST_PAIRS + for key in ("mean", "median", "min", "max"): + assert 0.0 <= metrics["test_iou"][key] <= 1.0 + # 学習・検証は train_ratio(既定 2/3)で分ける + assert metrics["counts"] == {"train": 4, "val": 2, "test": TEST_PAIRS} + assert metrics["elapsed_seconds"] > 0 + + def test_best_val_loss_matches_history(self, trained: TrainedRun) -> None: + metrics = trained.outcome.metrics + rows = _read_csv(trained.outcome.run_dir / "history.csv") + val = [float(r["val_loss"]) for r in rows] + assert metrics["best_val_loss"] == min(val) + assert val.index(min(val)) + 1 == metrics["best_epoch"] + + def test_data_bundle_fingerprint_is_same_in_config_and_metrics( + self, trained: TrainedRun + ) -> None: + run_dir = trained.outcome.run_dir + config = yaml.safe_load((run_dir / "config.yaml").read_text(encoding="utf-8")) + metrics = _strict_json(run_dir / "metrics.json") + dataset = json.loads((trained.bundle_dir / "dataset.json").read_text(encoding="utf-8")) + expected = { + "name": "synthetic", + "version": 1, + "manifest_sha256": dataset["manifest_sha256"], + } + assert config["run"]["data_bundle"] == expected + assert metrics["data_bundle"] == expected + + def test_config_yaml_run_section(self, trained: TrainedRun) -> None: + run_dir = trained.outcome.run_dir + config = yaml.safe_load((run_dir / "config.yaml").read_text(encoding="utf-8")) + assert config["run"]["id"] == RUN_ID + assert config["run"]["git_commit"] == COMMIT + assert config["run"]["seed"] == 0 + assert ExperimentConfig.model_validate(config["config"]) == _config(trained.out_dir) + + def test_predictions_csv(self, trained: TrainedRun) -> None: + path = trained.outcome.run_dir / "predictions.csv" + assert path.read_text(encoding="utf-8").split("\n")[0] == "image_line,iou" + rows = _read_csv(path) + assert len(rows) == TEST_PAIRS + lines = [int(r["image_line"]) for r in rows] + assert len(set(lines)) == TEST_PAIRS + assert all(line >= 2 for line in lines) # manifest の行番号(見出しが 1 行目) + split = _strict_json(trained.outcome.run_dir / "split.json") + assert sorted(lines) == sorted(split["image_lines"]["test"]) + ious = [float(r["iou"]) for r in rows] + assert all(0.0 <= v <= 1.0 for v in ious) + metrics = trained.outcome.metrics["test_iou"] + assert min(ious) == pytest.approx(metrics["min"]) + assert max(ious) == pytest.approx(metrics["max"]) + assert sum(ious) / len(ious) == pytest.approx(metrics["mean"]) + + def test_log_txt_has_content(self, trained: TrainedRun) -> None: + text = (trained.outcome.run_dir / "log.txt").read_text(encoding="utf-8") + assert RUN_ID in text + assert text.strip() + + +@pytest.mark.slow +class TestNoIdentifyingInformation: + """出力のどこにもデータのファイル名・パス・患者 ID が入らない(testing.md の最重要項目).""" + + def _secrets(self, trained: TrainedRun) -> list[str]: + files = [p for p in (trained.bundle_dir / "files").iterdir()] + assert files, "合成バンドルにファイルがない" + secrets = [p.stem for p in files] + [p.name for p in files] + secrets += [str(trained.bundle_dir), trained.bundle_dir.as_posix()] + secrets += [str(trained.bundle_dir.parent), trained.bundle_dir.parent.as_posix()] + return secrets + + @pytest.mark.parametrize("name", TEXT_OUTPUTS) + def test_no_file_names_or_data_paths(self, trained: TrainedRun, name: str) -> None: + text = (trained.outcome.run_dir / name).read_text(encoding="utf-8") + for secret in self._secrets(trained): + assert secret not in text, f"{name} にデータのファイル名・パスがある" + + @pytest.mark.parametrize("name", TEXT_OUTPUTS) + def test_no_subject_or_capture_ids(self, trained: TrainedRun, name: str) -> None: + text = (trained.outcome.run_dir / name).read_text(encoding="utf-8") + # 合成データの患者 ID・撮影 ID は syn-s0001・syn-c0001 の形 + assert not re.search(r"syn-[sc]\d{4}", text), f"{name} に患者 ID・撮影 ID がある" + + @pytest.mark.parametrize("name", TEXT_OUTPUTS) + def test_no_hash_other_than_manifest(self, trained: TrainedRun, name: str) -> None: + text = (trained.outcome.run_dir / name).read_text(encoding="utf-8") + manifest = trained.outcome.metrics["data_bundle"]["manifest_sha256"] + hashes = set(re.findall(r"[0-9a-f]{64}", text)) - {manifest} + assert not hashes, f"{name} に manifest 以外のハッシュ(ファイル名)がある" + + +@pytest.mark.slow +@pytest.mark.usefixtures("restore_logging") +def test_same_config_reproduces_history_and_metrics(trained: TrainedRun) -> None: + # 同じ設定・同じバンドルでもう一度回すと(実験 ID だけ違う)履歴と指標が一致する + outcome = run_training( + _config(trained.out_dir), + config_name="synthetic", + environ=ENVIRON, + now=datetime(2026, 11, 19, 10, 20, 31), + bundles_dir=trained.bundle_dir.parents[1], + ) + first = trained.outcome + assert outcome.run_id != first.run_id + for name in ("history.csv", "predictions.csv", "split.json"): + assert (outcome.run_dir / name).read_bytes() == (first.run_dir / name).read_bytes() + a = {k: v for k, v in outcome.metrics.items() if k != "elapsed_seconds"} + b = {k: v for k, v in first.metrics.items() if k != "elapsed_seconds"} + assert a == b + + +@pytest.mark.slow +@pytest.mark.usefixtures("restore_logging") +def test_subject_split_runs(tmp_path: Path) -> None: + _write_bundle(tmp_path / "bundles") + outcome = run_training( + _config(tmp_path / "runs", data={"split": "subject"}, train={"max_epochs": 1}), + config_name="synthetic", + environ={}, + now=NOW, + bundles_dir=tmp_path / "bundles", + ) + assert outcome.run_id == "20261119-102030_synthetic_nogit" + split = _strict_json(outcome.run_dir / "split.json") + assert split["method"] == "subject" + assert outcome.metrics["epochs_run"] == 1 + + +# --------------------------------------------------------------------------- +# 止まり方: フォルダを作る前に止まる +# --------------------------------------------------------------------------- + + +@pytest.mark.usefixtures("restore_logging") +class TestStopsBeforeCreatingRunDir: + def _assert_nothing_created(self, out_dir: Path) -> None: + assert not (out_dir / RUN_ID).exists() + assert not out_dir.exists() or not any(out_dir.iterdir()) + + def test_image_size_not_multiple_of_32(self, tmp_path: Path) -> None: + _write_bundle(tmp_path / "bundles") + out_dir = tmp_path / "runs" + with pytest.raises(ValueError): + run_training( + _config(out_dir, data={"image_size": [48, 48]}), + config_name="synthetic", + environ=ENVIRON, + now=NOW, + bundles_dir=tmp_path / "bundles", + ) + self._assert_nothing_created(out_dir) + + @pytest.mark.skipif(torch.cuda.is_available(), reason="GPU が無い環境でだけ確かめる") + def test_gpu_requested_without_gpu(self, tmp_path: Path) -> None: + _write_bundle(tmp_path / "bundles") + out_dir = tmp_path / "runs" + with pytest.raises(ValueError): + run_training( + _config(out_dir, train={"device": "cuda"}), + config_name="synthetic", + environ=ENVIRON, + now=NOW, + bundles_dir=tmp_path / "bundles", + ) + self._assert_nothing_created(out_dir) + + def test_invalid_git_commit(self, tmp_path: Path) -> None: + out_dir = tmp_path / "runs" + with pytest.raises(ValueError): + run_training( + _config(out_dir), + config_name="synthetic", + environ={GIT_COMMIT_ENV_VAR: "../evil"}, + now=NOW, + bundles_dir=tmp_path / "bundles", + ) + self._assert_nothing_created(out_dir) + + def test_invalid_config_name(self, tmp_path: Path) -> None: + out_dir = tmp_path / "runs" + with pytest.raises(ValueError): + run_training( + _config(out_dir), + config_name="bad name", + environ=ENVIRON, + now=NOW, + bundles_dir=tmp_path / "bundles", + ) + self._assert_nothing_created(out_dir) + + def test_existing_run_dir_is_not_overwritten(self, tmp_path: Path) -> None: + out_dir = tmp_path / "runs" + existing = out_dir / RUN_ID + existing.mkdir(parents=True) + (existing / "metrics.json").write_text("original", encoding="utf-8") + with pytest.raises(ValueError): + run_training( + _config(out_dir), + config_name="synthetic", + environ=ENVIRON, + now=NOW, + bundles_dir=tmp_path / "bundles", + ) + assert [p.name for p in existing.iterdir()] == ["metrics.json"] + assert (existing / "metrics.json").read_text(encoding="utf-8") == "original" + + +# --------------------------------------------------------------------------- +# 止まり方: フォルダを作った後に止まる(実験フォルダと log.txt は残る) +# --------------------------------------------------------------------------- + + +@pytest.mark.usefixtures("restore_logging") +class TestStopsAfterCreatingRunDir: + def test_missing_bundle_leaves_run_dir_and_log(self, tmp_path: Path) -> None: + (tmp_path / "bundles").mkdir() + out_dir = tmp_path / "runs" + with pytest.raises(ValueError): + run_training( + _config(out_dir), + config_name="synthetic", + environ=ENVIRON, + now=NOW, + bundles_dir=tmp_path / "bundles", + ) + run_dir = out_dir / RUN_ID + assert (run_dir / "log.txt").is_file() + for name in ("history.csv", "metrics.json", "split.json", "predictions.csv"): + assert not (run_dir / name).exists() + assert not (run_dir / "checkpoints" / "best.pth").exists() + + def test_image_size_mismatch_stops_before_split(self, tmp_path: Path) -> None: + # バンドルの画像は 64×64,設定は 32×32 → 全件の事前検証で止まる(黙って除かない) + _write_bundle(tmp_path / "bundles") + out_dir = tmp_path / "runs" + with pytest.raises(ValueError): + run_training( + _config(out_dir, data={"image_size": [32, 32]}), + config_name="synthetic", + environ=ENVIRON, + now=NOW, + bundles_dir=tmp_path / "bundles", + ) + run_dir = out_dir / RUN_ID + assert (run_dir / "log.txt").is_file() + assert (run_dir / "config.yaml").is_file() + for name in ("split.json", "history.csv", "metrics.json", "predictions.csv"): + assert not (run_dir / name).exists() diff --git a/tests/training/test_history.py b/tests/training/test_history.py new file mode 100644 index 0000000..445a532 --- /dev/null +++ b/tests/training/test_history.py @@ -0,0 +1,98 @@ +"""学習の履歴 `history.csv` と学習曲線 `figures/loss.png`(`training/history.py`)のテスト. + +期待値は SPEC_01「実験の出力」(`history.csv` はエポックごとの学習損失・検証損失,図は +`figures/loss.png`)と SPEC_02「学習」を基準にする.図は smoke テスト(ファイルが PNG として +できること)だけにする(testing.md「テストを必須としない対象」). +""" + +from __future__ import annotations + +import csv +import io +import math +from pathlib import Path + +from tongue_seg_model.training.history import ( + HISTORY_COLUMNS, + HISTORY_FILENAME, + LOSS_FIGURE_FILENAME, + HistoryRow, + history_csv_text, + plot_loss_curve, + write_history_csv, +) + +PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n" + + +def _rows() -> list[HistoryRow]: + return [ + HistoryRow(epoch=1, train_loss=0.9, val_loss=0.8), + HistoryRow(epoch=2, train_loss=0.7, val_loss=0.75), + HistoryRow(epoch=3, train_loss=0.1 + 0.2, val_loss=1 / 3), + ] + + +def _parse(text: str) -> list[dict[str, str]]: + return list(csv.DictReader(io.StringIO(text))) + + +def test_names_match_spec01() -> None: + assert HISTORY_FILENAME == "history.csv" + assert LOSS_FIGURE_FILENAME == "loss.png" + assert HISTORY_COLUMNS == ("epoch", "train_loss", "val_loss") + + +class TestHistoryCsvText: + def test_header_and_rows(self) -> None: + text = history_csv_text(_rows()) + lines = text.split("\n") + assert lines[0] == "epoch,train_loss,val_loss" + parsed = _parse(text) + assert [row["epoch"] for row in parsed] == ["1", "2", "3"] + + def test_losses_round_trip_exactly(self) -> None: + rows = _rows() + parsed = _parse(history_csv_text(rows)) + for original, row in zip(rows, parsed, strict=True): + assert float(row["train_loss"]) == original.train_loss + assert float(row["val_loss"]) == original.val_loss + + def test_empty_history_is_header_only(self) -> None: + assert history_csv_text([]) == "epoch,train_loss,val_loss\n" + + def test_uses_lf_line_endings(self) -> None: + text = history_csv_text(_rows()) + assert "\r" not in text + assert text.endswith("\n") + assert text.count("\n") == 4 + + def test_nan_loss_is_written_readably(self) -> None: + text = history_csv_text([HistoryRow(epoch=1, train_loss=math.nan, val_loss=math.inf)]) + row = _parse(text)[0] + assert math.isnan(float(row["train_loss"])) + assert math.isinf(float(row["val_loss"])) + + +class TestWriteHistoryCsv: + def test_writes_file(self, tmp_path: Path) -> None: + path = write_history_csv(tmp_path / HISTORY_FILENAME, _rows()) + assert path == tmp_path / "history.csv" + assert path.read_bytes() == history_csv_text(_rows()).encode("utf-8") + + def test_rewriting_replaces_whole_file(self, tmp_path: Path) -> None: + path = tmp_path / HISTORY_FILENAME + write_history_csv(path, _rows()) + write_history_csv(path, _rows()[:1]) + assert len(_parse(path.read_text(encoding="utf-8"))) == 1 + + +class TestPlotLossCurve: + def test_writes_png(self, tmp_path: Path) -> None: + path = plot_loss_curve(tmp_path / LOSS_FIGURE_FILENAME, _rows()) + assert path == tmp_path / "loss.png" + assert path.read_bytes().startswith(PNG_SIGNATURE) + + def test_single_epoch(self, tmp_path: Path) -> None: + path = plot_loss_curve(tmp_path / "loss.png", _rows()[:1]) + assert path.read_bytes().startswith(PNG_SIGNATURE) diff --git a/tests/training/test_loop.py b/tests/training/test_loop.py new file mode 100644 index 0000000..3714d1e --- /dev/null +++ b/tests/training/test_loop.py @@ -0,0 +1,274 @@ +"""学習ループと学習後の評価(`training/loop.py`)のテスト. + +期待値は SPEC_02「学習」(損失はバッチごとの損失の平均・検証損失が最良を更新したエポックの重みを +`checkpoints/best.pth` に上書き・`early_stopping_patience` エポック続けて更新しなければ止める)と +「学習後の評価」(1 枚ずつ シグモイド → 255 倍 → 大津の 2 値化 → IoU)を基準にする. + +早期終了の挙動は,検証のときだけ決めた値を返す損失を使って確かめる(学習の数値に依存しない). +モデルは 1×1 の畳み込みだけの小さなものにする. +""" + +from __future__ import annotations + +import math +from collections.abc import Iterator, Sequence +from pathlib import Path + +import pytest +import torch +from torch import nn +from torch.utils.data import DataLoader, TensorDataset + +from tongue_seg_model.training.history import HistoryRow +from tongue_seg_model.training.loop import fit, predict_ious, run_epoch + +CPU = torch.device("cpu") +SIZE = 8 + + +def _loader(n: int, batch_size: int, seed: int = 0) -> DataLoader: + generator = torch.Generator().manual_seed(seed) + images = torch.rand(n, 3, SIZE, SIZE, generator=generator) + labels = (torch.rand(n, 1, SIZE, SIZE, generator=generator) > 0.5).float() + labels = torch.cat([labels, 1 - labels], dim=1) + return DataLoader(TensorDataset(images, labels), batch_size=batch_size, shuffle=False) + + +def _model(seed: int = 0) -> nn.Module: + torch.manual_seed(seed) + return nn.Conv2d(3, 2, kernel_size=1) + + +class ScriptedValLoss(nn.Module): + """学習のときは本物の損失,検証のときは決めた値を順に返す損失.""" + + def __init__(self, model: nn.Module, val_losses: Sequence[float]) -> None: + super().__init__() + self._model = model + self._val: Iterator[float] = iter(val_losses) + self.train_calls = 0 + self.val_calls = 0 + + def forward(self, outputs: torch.Tensor, labels: torch.Tensor) -> torch.Tensor: + if self._model.training: + self.train_calls += 1 + return nn.functional.binary_cross_entropy_with_logits(outputs, labels) + self.val_calls += 1 + return outputs.sum() * 0 + next(self._val) + + +def _fit( + tmp_path: Path, + val_losses: Sequence[float], + *, + max_epochs: int, + patience: int, + snapshots: list[dict[str, torch.Tensor]] | None = None, + calls: list[tuple[HistoryRow, ...]] | None = None, +): + model = _model() + criterion = ScriptedValLoss(model, val_losses) + optimizer = torch.optim.Adam(model.parameters(), lr=1e-2) + + def on_epoch(rows: Sequence[HistoryRow]) -> None: + if calls is not None: + calls.append(tuple(rows)) + if snapshots is not None: + snapshots.append({k: v.detach().clone() for k, v in model.state_dict().items()}) + + result = fit( + model, + train_loader=_loader(4, 2), + val_loader=_loader(2, 2, seed=1), # 1 バッチ → 検証損失は決めた値そのもの + criterion=criterion, + optimizer=optimizer, + device=CPU, + max_epochs=max_epochs, + patience=patience, + checkpoint_path=tmp_path / "best.pth", + on_epoch=on_epoch, + ) + return result, model + + +# --------------------------------------------------------------------------- +# run_epoch +# --------------------------------------------------------------------------- + + +class ConstantPerBatchLoss(nn.Module): + """バッチごとに決めた値を返す損失(勾配はモデルの出力につなぐ).""" + + def __init__(self, values: Sequence[float]) -> None: + super().__init__() + self._values = iter(values) + + def forward(self, outputs: torch.Tensor, labels: torch.Tensor) -> torch.Tensor: + return (outputs - labels).pow(2).mean() * 0 + next(self._values) + + +class TestRunEpoch: + def test_returns_unweighted_mean_of_batch_losses(self) -> None: + # 3 件をバッチの大きさ 2 で回すと 2 件・1 件のバッチになる.平均は件数で重み付けしない + loss = run_epoch(_model(), _loader(3, 2), ConstantPerBatchLoss([1.0, 4.0]), CPU) + assert loss == pytest.approx(2.5) + + def test_validation_does_not_change_weights_and_uses_eval_mode(self) -> None: + model = _model() + before = {k: v.clone() for k, v in model.state_dict().items()} + seen: list[tuple[bool, bool]] = [] + + class Recording(nn.Module): + def forward(self, outputs: torch.Tensor, labels: torch.Tensor) -> torch.Tensor: + seen.append((model.training, torch.is_grad_enabled())) + return nn.functional.binary_cross_entropy_with_logits(outputs, labels) + + run_epoch(model, _loader(4, 2), Recording(), CPU) + assert seen == [(False, False), (False, False)] + for key, value in model.state_dict().items(): + assert torch.equal(value, before[key]) + + def test_training_updates_weights_and_uses_train_mode(self) -> None: + model = _model() + model.eval() + before = {k: v.clone() for k, v in model.state_dict().items()} + seen: list[bool] = [] + + class Recording(nn.Module): + def forward(self, outputs: torch.Tensor, labels: torch.Tensor) -> torch.Tensor: + seen.append(model.training) + return nn.functional.binary_cross_entropy_with_logits(outputs, labels) + + optimizer = torch.optim.Adam(model.parameters(), lr=1e-2) + run_epoch(model, _loader(4, 2), Recording(), CPU, optimizer) + assert seen == [True, True] + assert not torch.equal(model.weight, before["weight"]) + + +# --------------------------------------------------------------------------- +# fit(早期終了・最良の重みの保存) +# --------------------------------------------------------------------------- + + +class TestFitEarlyStopping: + def test_stops_after_patience_epochs_without_improvement(self, tmp_path: Path) -> None: + result, _ = _fit(tmp_path, [0.9, 0.5, 0.6, 0.7, 0.4, 0.3], max_epochs=6, patience=2) + assert [row.epoch for row in result.history] == [1, 2, 3, 4] + assert result.best_epoch == 2 + assert result.best_val_loss == pytest.approx(0.5) + assert result.stopped_early is True + + def test_runs_all_epochs_while_improving(self, tmp_path: Path) -> None: + result, _ = _fit(tmp_path, [0.9, 0.8, 0.7], max_epochs=3, patience=1) + assert len(result.history) == 3 + assert result.best_epoch == 3 + assert result.stopped_early is False + + def test_stop_condition_on_last_epoch_is_not_early(self, tmp_path: Path) -> None: + # 3 エポック目で止める条件を満たすが,最大エポック数なので「早期終了」ではない + result, _ = _fit(tmp_path, [0.5, 0.6, 0.7], max_epochs=3, patience=2) + assert len(result.history) == 3 + assert result.best_epoch == 1 + assert result.stopped_early is False + + def test_equal_loss_does_not_count_as_improvement(self, tmp_path: Path) -> None: + result, _ = _fit(tmp_path, [0.5, 0.5, 0.5, 0.5], max_epochs=4, patience=2) + assert result.best_epoch == 1 + assert len(result.history) == 3 + assert result.stopped_early is True + + def test_history_records_train_and_scripted_val_losses(self, tmp_path: Path) -> None: + result, _ = _fit(tmp_path, [0.9, 0.8], max_epochs=2, patience=5) + assert [row.val_loss for row in result.history] == pytest.approx([0.9, 0.8]) + assert all(math.isfinite(row.train_loss) for row in result.history) + + def test_on_epoch_receives_history_so_far(self, tmp_path: Path) -> None: + calls: list[tuple[HistoryRow, ...]] = [] + result, _ = _fit(tmp_path, [0.9, 0.8, 0.85], max_epochs=3, patience=5, calls=calls) + assert [len(c) for c in calls] == [1, 2, 3] + assert [row.epoch for row in calls[-1]] == [1, 2, 3] + assert calls[-1] == result.history + + def test_all_nan_validation_raises(self, tmp_path: Path) -> None: + with pytest.raises(ValueError): + _fit(tmp_path, [math.nan] * 5, max_epochs=5, patience=2) + assert not (tmp_path / "best.pth").exists() + + def test_nan_then_finite_is_ok(self, tmp_path: Path) -> None: + result, _ = _fit(tmp_path, [math.nan, 0.7, 0.8], max_epochs=3, patience=5) + assert result.best_epoch == 2 + + +class TestFitCheckpoint: + def test_best_pth_holds_weights_of_best_epoch(self, tmp_path: Path) -> None: + snapshots: list[dict[str, torch.Tensor]] = [] + result, model = _fit( + tmp_path, [0.9, 0.5, 0.6, 0.7], max_epochs=4, patience=5, snapshots=snapshots + ) + assert result.best_epoch == 2 + saved = torch.load(tmp_path / "best.pth", weights_only=True) + best = snapshots[result.best_epoch - 1] + assert set(saved) == set(best) + for key in best: + assert torch.equal(saved[key], best[key]) + # 最後のエポックの重みとは違う(最良のものだけが残る) + assert not torch.equal(saved["weight"], model.state_dict()["weight"]) + + def test_checkpoint_is_overwritten_not_multiplied(self, tmp_path: Path) -> None: + _fit(tmp_path, [0.9, 0.8, 0.7], max_epochs=3, patience=5) + assert sorted(p.name for p in tmp_path.iterdir()) == ["best.pth"] + + def test_checkpoint_loads_into_same_model(self, tmp_path: Path) -> None: + _fit(tmp_path, [0.9, 0.8], max_epochs=2, patience=5) + fresh = _model(seed=123) + fresh.load_state_dict(torch.load(tmp_path / "best.pth", weights_only=True)) + + +# --------------------------------------------------------------------------- +# predict_ious +# --------------------------------------------------------------------------- + + +class PassThroughLogits(nn.Module): + """入力の先頭 2 チャンネルをそのまま出力にするモデル(予測を入力で決めるため).""" + + def __init__(self) -> None: + super().__init__() + self.dummy = nn.Parameter(torch.zeros(1)) + self.modes: list[bool] = [] + + def forward(self, inputs: torch.Tensor) -> torch.Tensor: + self.modes.append(self.training) + return inputs[:, :2] + self.dummy * 0 + + +def _case(pred_rows: int, true_rows: int) -> tuple[torch.Tensor, torch.Tensor]: + """上から `pred_rows` 行を舌と予測し,上から `true_rows` 行が正解の舌である 1 枚.""" + image = torch.full((3, SIZE, SIZE), -10.0) + image[0, :pred_rows] = 10.0 + label = torch.zeros(2, SIZE, SIZE) + label[0, :true_rows] = 1.0 + label[1] = 1 - label[0] + return image, label + + +def test_predict_ious_per_image_in_loader_order() -> None: + cases = [_case(4, 2), _case(4, 4), _case(2, 4), _case(4, 8)] + images = torch.stack([c[0] for c in cases]) + labels = torch.stack([c[1] for c in cases]) + loader = DataLoader(TensorDataset(images, labels), batch_size=3, shuffle=False) + model = PassThroughLogits() + ious = predict_ious(model, loader, CPU) + assert ious == pytest.approx([0.5, 1.0, 0.5, 0.5]) + assert all(isinstance(v, float) for v in ious) + assert model.modes == [False, False] + + +def test_predict_ious_uniformly_negative_output_gives_zero() -> None: + # 一様に十分小さい出力(8 ビットで全画素 0)は 2 値化で全画素 0 になり,正解に舌があれば + # IoU は 0.※ 出力 0(全画素 127)のような 0 でない一様な値では,今の OpenCV の大津の + # 2 値化はしきい値 0 を返して全画素 255 になる(SPEC_02 の記述と合わない.報告済み) + image = torch.full((1, 3, SIZE, SIZE), -20.0) + _, label = _case(0, 4) + loader = DataLoader(TensorDataset(image, label.unsqueeze(0)), batch_size=1) + assert predict_ious(PassThroughLogits(), loader, CPU) == [0.0] diff --git a/tests/training/test_metrics.py b/tests/training/test_metrics.py new file mode 100644 index 0000000..202e504 --- /dev/null +++ b/tests/training/test_metrics.py @@ -0,0 +1,173 @@ +"""`metrics.json` と `predictions.csv`(`training/metrics.py`)のテスト. + +期待値は SPEC_01「実験の出力」(`metrics.json` は最良エポック・最良の検証損失・テスト用データでの +IoU の集計値・バンドルの指紋.`predictions.csv` は画像ごとの IoU で回収しない)と SPEC_02 +「学習後の評価」(`metrics.json` には集計値だけを書き,画像ごとの値は `predictions.csv` に書く)を +基準にする.組は画像の行の manifest の行番号で表し,ファイル名・パス・ID を書かない. +""" + +from __future__ import annotations + +import csv +import io +import json +import math +from pathlib import Path +from typing import Any + +import pytest + +from tongue_seg_model.training.metrics import ( + METRICS_FILENAME, + PREDICTION_COLUMNS, + PREDICTIONS_FILENAME, + build_metrics_document, + json_safe, + predictions_csv_text, + write_metrics_json, + write_predictions_csv, +) + +SHA = "0123456789abcdef" * 4 +TEST_IOU = {"count": 3, "mean": 0.5, "median": 0.4, "min": 0.1, "max": 1.0, "std": 0.3} +COUNTS = {"train": 8, "val": 4, "test": 3} +BUNDLE = {"name": "synthetic", "version": 1, "manifest_sha256": SHA} + + +def _document(**overrides: Any) -> dict[str, Any]: + kwargs: dict[str, Any] = { + "best_epoch": 2, + "best_val_loss": 0.25, + "epochs_run": 5, + "stopped_early": True, + "test_iou": TEST_IOU, + "counts": COUNTS, + "data_bundle": BUNDLE, + "elapsed_seconds": 12.5, + } + kwargs.update(overrides) + return build_metrics_document(**kwargs) + + +def _strict_loads(text: str) -> Any: + def _reject(constant: str) -> Any: + raise AssertionError(f"厳密な JSON でない値 {constant} がある") + + return json.loads(text, parse_constant=_reject) + + +def test_names_match_spec01() -> None: + assert METRICS_FILENAME == "metrics.json" + assert PREDICTIONS_FILENAME == "predictions.csv" + assert PREDICTION_COLUMNS == ("image_line", "iou") + + +class TestBuildMetricsDocument: + def test_has_exactly_the_spec_keys(self) -> None: + doc = _document() + assert set(doc) == { + "best_epoch", + "best_val_loss", + "epochs_run", + "stopped_early", + "test_iou", + "counts", + "data_bundle", + "elapsed_seconds", + } + + def test_values(self) -> None: + doc = _document() + assert doc["best_epoch"] == 2 + assert doc["best_val_loss"] == 0.25 + assert doc["epochs_run"] == 5 + assert doc["stopped_early"] is True + assert doc["test_iou"] == TEST_IOU + assert doc["counts"] == COUNTS + assert doc["data_bundle"] == BUNDLE + assert doc["elapsed_seconds"] == 12.5 + + def test_copies_nested_mappings(self) -> None: + test_iou = dict(TEST_IOU) + doc = _document(test_iou=test_iou) + test_iou["mean"] = 0.0 + assert doc["test_iou"]["mean"] == 0.5 + + def test_contains_no_per_image_values(self) -> None: + # 集計値だけ(画像ごとの値の列が入らない) + doc = _document() + for value in doc["test_iou"].values(): + assert isinstance(value, int | float) + + +class TestJsonSafe: + @pytest.mark.parametrize("value", [math.nan, math.inf, -math.inf]) + def test_non_finite_float_becomes_none(self, value: float) -> None: + assert json_safe(value) is None + + @pytest.mark.parametrize("value", [0.0, 1.5, -2.0, 3, True, "NaN", None]) + def test_other_values_unchanged(self, value: Any) -> None: + assert json_safe(value) == value + assert type(json_safe(value)) is type(value) + + def test_nested_structures(self) -> None: + value = {"a": [1.0, math.nan, (math.inf, 2)], "b": {"c": -math.inf, "d": "x"}} + assert json_safe(value) == {"a": [1.0, None, [None, 2]], "b": {"c": None, "d": "x"}} + + def test_does_not_modify_input(self) -> None: + value = {"a": [math.nan]} + json_safe(value) + assert math.isnan(value["a"][0]) + + +class TestWriteMetricsJson: + def test_round_trips(self, tmp_path: Path) -> None: + doc = _document() + path = write_metrics_json(tmp_path / METRICS_FILENAME, doc) + assert path == tmp_path / "metrics.json" + assert _strict_loads(path.read_text(encoding="utf-8")) == doc + + def test_non_finite_values_are_null(self, tmp_path: Path) -> None: + doc = _document( + best_val_loss=math.nan, + test_iou={**TEST_IOU, "std": math.inf}, + ) + path = write_metrics_json(tmp_path / METRICS_FILENAME, doc) + loaded = _strict_loads(path.read_text(encoding="utf-8")) + assert loaded["best_val_loss"] is None + assert loaded["test_iou"]["std"] is None + assert loaded["test_iou"]["mean"] == 0.5 + + +class TestPredictionsCsvText: + def test_header_and_rows(self) -> None: + text = predictions_csv_text([2, 4, 10], [0.5, 1.0, 0.0]) + assert text == "image_line,iou\n2,0.5\n4,1.0\n10,0.0\n" + + def test_iou_round_trips_exactly(self) -> None: + ious = [1 / 3, 0.1 + 0.2] + rows = list(csv.DictReader(io.StringIO(predictions_csv_text([3, 5], ious)))) + assert [float(r["iou"]) for r in rows] == ious + assert [int(r["image_line"]) for r in rows] == [3, 5] + + def test_accepts_numpy_floats(self) -> None: + np = pytest.importorskip("numpy") + text = predictions_csv_text([2], [np.float32(0.5)]) + assert text == "image_line,iou\n2,0.5\n" + + def test_empty(self) -> None: + assert predictions_csv_text([], []) == "image_line,iou\n" + + def test_length_mismatch_raises(self) -> None: + with pytest.raises(RuntimeError): + predictions_csv_text([2, 3], [0.5]) + + def test_has_only_line_number_and_iou_columns(self) -> None: + rows = list(csv.reader(io.StringIO(predictions_csv_text([2], [0.5])))) + assert all(len(row) == 2 for row in rows) + + +def test_write_predictions_csv(tmp_path: Path) -> None: + path = write_predictions_csv(tmp_path / PREDICTIONS_FILENAME, [2, 4], [0.25, 0.75]) + assert path == tmp_path / "predictions.csv" + assert path.read_bytes() == b"image_line,iou\n2,0.25\n4,0.75\n" diff --git a/tests/training/test_reproducibility.py b/tests/training/test_reproducibility.py new file mode 100644 index 0000000..131edb2 --- /dev/null +++ b/tests/training/test_reproducibility.py @@ -0,0 +1,71 @@ +"""乱数の固定(`training/reproducibility.py`)のテスト. + +期待値は SPEC_02「学習」の乱数の固定の範囲(Python・NumPy・PyTorch の種と cuDNN の決定的な +動作.`torch.use_deterministic_algorithms` は有効にしない)を基準にする. +""" + +from __future__ import annotations + +import os +import random +from collections.abc import Iterator + +import numpy as np +import pytest +import torch + +from tongue_seg_model.training.reproducibility import fix_random_seed + + +@pytest.fixture(autouse=True) +def restore_global_state(monkeypatch: pytest.MonkeyPatch) -> Iterator[None]: + """cuDNN の設定と PYTHONHASHSEED を元に戻す(他のテストに影響させない).""" + deterministic = torch.backends.cudnn.deterministic + benchmark = torch.backends.cudnn.benchmark + algorithms = torch.are_deterministic_algorithms_enabled() + # monkeypatch に登録しておくと,テスト後に元の値(または未設定)に戻る + monkeypatch.setenv("PYTHONHASHSEED", os.environ.get("PYTHONHASHSEED", "0")) + yield + torch.backends.cudnn.deterministic = deterministic + torch.backends.cudnn.benchmark = benchmark + torch.use_deterministic_algorithms(algorithms) + + +def _draw() -> tuple[float, float, list[float]]: + return random.random(), float(np.random.rand()), torch.rand(3).tolist() + + +def test_same_seed_gives_same_random_numbers() -> None: + fix_random_seed(2021) + first = _draw() + fix_random_seed(2021) + second = _draw() + assert first == second + + +def test_different_seed_gives_different_random_numbers() -> None: + fix_random_seed(2021) + first = _draw() + fix_random_seed(2022) + second = _draw() + assert first[0] != second[0] + assert first[1] != second[1] + assert first[2] != second[2] + + +def test_sets_cudnn_flags_and_hash_seed() -> None: + torch.backends.cudnn.deterministic = False + torch.backends.cudnn.benchmark = True + fix_random_seed(7) + assert torch.backends.cudnn.deterministic is True + assert torch.backends.cudnn.benchmark is False + assert os.environ["PYTHONHASHSEED"] == "7" + + +def test_does_not_enable_deterministic_algorithms() -> None: + fix_random_seed(0) + assert torch.are_deterministic_algorithms_enabled() is False + + +def test_accepts_maximum_seed() -> None: + fix_random_seed(2**32 - 1)