diff --git a/CLAUDE.md b/CLAUDE.md index f1b3e17..f45e261 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -8,7 +8,7 @@ ## 開発進捗 -最新: PLAN_02 ステップ 1-5(学習と `tsm-train`)完了.実データのバンドルは両サーバに配置済み(2-1・2-2 完了).次はステップ 1-6(ONNX の書き出し) +最新: PLAN_02 ステップ 1-6(ONNX の書き出しと `tsm-export`)完了.次はステップ 1-7(原本の重みでの確認).実データのバンドルは両サーバに配置済み ※ 本欄は**最新ステップ 1 行のみ上書き更新**.詳細な進捗履歴(動機・設計判断・失敗パターン)は [docs/PROGRESS.md](docs/PROGRESS.md) に追記する.運用ルールは `.claude/rules/progress-log.md` を参照(該当ファイル編集時に自動ロードされる). ## 必須ルール(コード実装時) 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 015090a..2a13488 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,5 +89,5 @@ ## 未確定事項 (Open Items) -- 今の `torch.onnx` で opset 11・同じ入出力名の ONNX を書き出せるか(実装時に確認) +- PyTorch の従来の ONNX の書き出し(TorchScript 経由)がいつまで使えるか.opset 11・配布中と同じ入出力名で書き出せるのはこの方法だけで,非推奨の警告が出ている(2026-11-19 に torch 2.15 で確認.[SPEC_02](../04_SPEC/SPEC_02_学習・ONNX書き出し仕様.md)「ONNX の書き出し」).PyTorch の版を上げるときに確かめる - 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 076ec20..1229a37 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" @@ -48,7 +48,20 @@ - バンドルの読み込み・事前検証で止まった実験のフォルダは `runs/` に残る(`log.txt` に理由がある.不要なら手で消す) - 設定の `run.out_dir` 等にパスを書くときは,Git Bash 形式(`/c/Users/...`)を使わない(Windows の Python が `C:\c\Users\...` と解釈し,別の場所にフォルダができる) -## ONNX の書き出し・リモート実行 (Export & Remote) +## ONNX の書き出し (Export) + +| 目的 | コマンド | 備考 | +| --- | --- | --- | +| 実験の重みから ONNX を書き出す | `uv run tsm-export --run <実験ID>` | `runs/<実験ID>/checkpoints/best.pth` から `checkpoints/ResUNet.onnx` を書き出し,onnxruntime(CPU)で形と PyTorch の出力との差を確かめる.結果は `metrics.json` の `export` に書く.CPU で数秒 | +| 既にある ONNX を作り直す | `uv run tsm-export --run <実験ID> --overwrite` | `--overwrite` が無いと,ONNX が既にあれば止まる | +| 実験ディレクトリの親を指定する | `uv run tsm-export --run <実験ID> --runs-dir <パス>` | 既定は `runs` | + +- 終了コード: 0 成功/1 実験 ID の形式・実験ディレクトリ・設定・重み・`metrics.json` の問題,ONNX が既にある(ログに理由が 1 行出る)/2 引数の誤り/3 書き出した ONNX が確認を通らなかった(ONNX は置かない) +- 成功すると ONNX のパスを標準出力に 1 行出す.ログは標準エラーと実験の `log.txt`(追記) +- 書き出しが失敗したとき,PyTorch が作りかけのグラフを標準出力に大量に出すことがある(止められない).成否は終了コードで判断する +- 書き出しに PyTorch の従来の方法(TorchScript 経由)を使うため,非推奨の警告がログに出る(原本と同じ opset 11・入出力の名前にするため.SPEC_02) + +## リモート実行 (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 5642e72..b20c63f 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" @@ -19,7 +19,7 @@ | 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-6 ONNX の書き出し | `best.pth` から ONNX を書き出し,onnxruntime で形と PyTorch との一致を確かめる(コマンド `tsm-export`) | 合成データで学習した重みから書き出せ,入出力の形が `(1, 3, 256, 256)` → `(1, 2, 256, 256)` | +| 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 で回り,結果を回収できる(実サーバの確認まで行う) | @@ -63,4 +63,4 @@ ## 最初の実装ステップ (First Step) -ステップ 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)に入れる. +ステップ 1-1(設定と実験の出力)から始めた(2026-11-18 に完了).ステップ 1-2(モデル)・1-3(前処理・損失・IoU)・1-4(合成データとデータの読み込み)も完了.ステップ 1-5(学習)・1-6(ONNX の書き出し)も完了(2026-11-19).次は**ステップ 1-7(原本の重みでの確認)**.`/implement ステップ 1-7 原本の重みで新旧のモデルを比べる` で開始できる.実データのバンドルは両サーバに配置済み(ステップ 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 5a844c9..5cfa56b 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" @@ -145,6 +145,7 @@ | `elapsed_seconds` | 学習と評価にかかった時間(秒) | - `history.csv` の列は `epoch,train_loss,val_loss`(エポックは 1 から数える.原本は 0 から),`predictions.csv` の列は `image_line,iou`(`image_line` は画像の行の manifest の行番号.原本の `Log_detail.csv` は画像のファイル名を書いていた) +- `tsm-export` を実行すると,`metrics.json` に `export` というキーが足される(書き出し方法・PyTorch の版・opset・入出力の名前と形と型・比較の入力の seed・PyTorch との最大の絶対差・許容値・ファイルの大きさ・所要時間.パスは入れない) - `metrics.json` は厳密な JSON で書く.損失が発散して値が NaN・無限大になった項目は `null` にする - **失敗した実験のフォルダは残す**(2026-11-19 のユーザー判断).設定の誤り(`image_size`・計算装置・実験 ID)はフォルダを作る前に止めるが,バンドルの読み込み・事前検証で止まった場合は `log.txt`(事前検証まで進んでいれば `config.yaml` も)が残る.サーバで止まった原因を回収できるようにするため @@ -177,7 +178,7 @@ | コマンド(仮) | 役割 | 実行場所 | | --- | --- | --- | | `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-export --run <実験ID> [--runs-dir PATH] [--overwrite]` | その実験の `best.pth` から ONNX を書き出し,onnxruntime で入出力の形と PyTorch の出力との一致を確かめる.結果を `metrics.json` の `export` に書き,ONNX のパスを標準出力に 1 行出す.終了コードは成功 0・実験や設定の問題 1・引数の誤り 2・確認を通らなかった 3([SPEC_02](SPEC_02_学習・ONNX書き出し仕様.md)「ONNX の書き出し」).書き出しに失敗すると 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 91939ee..07dd901 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" @@ -127,13 +127,27 @@ | 入力 | `(1, 3, 256, 256)` の float32(BGR を 255 で割った値).大きさは固定 | | 出力 | `(1, 2, 256, 256)` の float32(活性化関数を掛ける前の値.チャンネル 0 が舌) | | モデルの状態 | 推論モード(`eval`) | -| opset | 11(原本と同じ).今の PyTorch で 11 を書き出せない場合は,動く最小の版にして記録する | +| opset | 11(原本と同じ.設定 `export.opset` で変えられる) | +| 書き出し方法 | PyTorch の従来の方法(TorchScript 経由.`torch.onnx.export` の `dynamo=False`).入出力の名前は指定しない(原本と同じ) | +| 書き出す場所 | CPU.事前学習の重みは読まず,`best.pth` の重みだけを使う | -書き出した後に次を確かめ,結果を `metrics.json`(または書き出しの記録)に残す. +- **書き出し方法を従来の方法にした理由**(2026-11-19 に torch 2.15 で確認): 従来の方法では,opset 11 で書き出せ,入出力の名前が配布中の `ResUNet.onnx` と同じ(入力 `input.1`・出力 `269`)になった.今の既定の方法(`dynamo=True`)は,追加の依存(onnxscript)が要り,opset 11 に変換できず(opset 18 のまま),名前も変わった(`x`・`conv2d_32`) +- 従来の方法は非推奨で,将来の PyTorch で消えるという警告が出る(ログに残す).消えたときは opset か入出力の名前を変えるしかなく,DeepTIAS・推論サーバー・TIASJudgeModel 側の確認が要る.PyTorch の版を上げるときに,この書き出しが動くことを確かめる +- 書き出したグラフのノードの数は配布中のものと少し違う(今の PyTorch が何もしないノードを足すため).出力の数値の一致はステップ 1-7 で確かめる + +書き出した後に次を確かめ,結果を `metrics.json` の `export` に残す(回収ホワイトリストの中の名前に残すため,別のファイルにしない). - onnxruntime(CPU)で読み込めること.入出力の形と型が上の表のとおりであること -- 同じ入力に対する PyTorch の出力との差が小さいこと(最大の絶対差を記録する) -- 入出力の名前を記録する.配布中の `ResUNet.onnx`(サーバの `~/models/TongueSegmentation/`)と違っていても,DeepTIAS・推論サーバー・TIASJudgeModel が名前に依存しているかを確かめるまでは合わせ込みをしない(確かめた結果で決める) +- 同じ入力に対する PyTorch の出力との差が小さいこと(最大の絶対差を記録する).入力は乱数(seed 0・値域 0 以上 1 未満)の画像 1 枚,許容値は `1e-4`(実測は約 `5e-7`) +- 入出力の名前を記録する.配布中の `ResUNet.onnx`(サーバの `~/models/TongueSegmentation/`)と違っていても,DeepTIAS・推論サーバー・TIASJudgeModel が名前に依存しているかを確かめるまでは合わせ込みをしない(確かめた結果で決める).名前の違いは確認の失敗にしない + +書き出しの手順と止まり方: + +- 実験の `config.yaml` から設定を読み戻す(入力の大きさは `data.image_size`).学習が最後まで終わっていない実験(`metrics.json` が無い)は書き出さない +- 一時ファイルに書き出し,確認を通ったものだけを `checkpoints/ResUNet.onnx` に置き換える.**確認を通らなかった ONNX は残さず,`metrics.json` も変えない**(終了コード 3) +- ONNX が既にあるときは止める.`--overwrite` を付けたときだけ置き換える +- 実験 ID は形式(`tsm-train` が作る形)を確かめてからパスに使う(`..` や区切り文字で `runs/` の外を指せない) +- 実装は `src/tongue_seg_model/export/check.py`(確認の判定.純関数)・`export/onnx_export.py`(書き出し・読み直し・onnxruntime の実行)・`cli/export.py`(全体の流れ) ## 設定項目 (Configuration Keys) diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index 0fedff0..afcd9dd 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -50,3 +50,9 @@ - 失敗パターン: 動作確認で設定の `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` のほうが自然) +- [x] **ステップ 1-6 ONNX の書き出しと `tsm-export`**: 実験の `best.pth` から ONNX を書き出し,onnxruntime で形・型・PyTorch の出力との差を確かめて `metrics.json` の `export` に記録する.手元の合成データの実験で,opset 11・入力 `input.1` `(1, 3, 256, 256)`・出力 `269` `(1, 2, 256, 256)`・差の最大 約 `5e-7` + - 設計判断: 書き出しは PyTorch の従来の方法(TorchScript 経由)にした.今の既定の方法(dynamo)は onnxscript が要り,opset 11 に変換できず,入出力の名前も配布中のものと変わるため.従来の方法は非推奨で将来消えるので,PyTorch の版を上げるときに確かめる(ENV_01「未確定事項」) + - 設計判断: 一時ファイルに書き出し,確認を通ったものだけを `ResUNet.onnx` に置き換える(確認を通らない ONNX を配布用の名前で残さない).記録は `metrics.json` に足す(回収ホワイトリストを変えずに回収できる) + - 失敗パターン: ① 壊れた ONNX を読むと protobuf の `DecodeError`(`ValueError` でも `OSError` でもない)が素通りした → `ValueError` に変える.② 形式の確認が `match` と `$` のため末尾の改行を通した(改行入りの実験フォルダ名ができえた)→ `fullmatch` に(TIASDataHub と同じ穴) + - 判明: 書き出しに失敗すると,PyTorch の C++ 部分が作りかけのグラフを標準出力に直接書く(Python からは止められない).リモート実行ツールは標準出力ではなく終了コードで成否を判断する + - 未実装・後段: サーバ(Linux・torch 2.14 系)での書き出し(1-8).配布中の ONNX との出力の一致(1-7).`tsm-export` の全体の流れが `cli/export.py` にある(`training` と `export` の両方を使うため.`cli/` を薄くするなら,実験フォルダの道具を `training/` から共通の場所に出す構成の見直しが要る).CLI が 3 つになったら `cli/` の共通部分をまとめる diff --git a/pyproject.toml b/pyproject.toml index 910edd6..81208d9 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -19,6 +19,7 @@ [project.scripts] tsm-train = "tongue_seg_model.cli.train:main" +tsm-export = "tongue_seg_model.cli.export:main" [dependency-groups] dev = [ diff --git a/src/tongue_seg_model/cli/export.py b/src/tongue_seg_model/cli/export.py new file mode 100644 index 0000000..f15792d --- /dev/null +++ b/src/tongue_seg_model/cli/export.py @@ -0,0 +1,298 @@ +"""`tsm-export --run <実験ID>`: 実験の `best.pth` から ONNX を書き出して確かめる(SPEC_01「CLI」). + +原本: `legacy/source/pytorchToOnnx.py`(`ResNetUNet(n_class=2)` に重みを読み込み,推論モードで +`(1, 3, 256, 256)` の入力・opset 11 で書き出す).書き出した後の確認は新しいコードで足したもの +(SPEC_02「ONNX の書き出し」): + +1. `onnx` で読み,検査器を通し,opset・入出力の名前・形・型を確かめる +2. onnxruntime(CPU)で読み込み,同じ入力に対する PyTorch の出力との最大の絶対差を確かめる +3. 確認を通ったものだけを `runs/<実験ID>/checkpoints/ResUNet.onnx` に置き,結果を + `metrics.json` の `export` に書く(回収する名前に残すため) + +書き出しと確認は CPU で行う(GPU を使わない.共用サーバの GPU を占有しないため). +最後に書き出した ONNX のパスを標準出力に 1 行出す(ログは標準エラーと実験の `log.txt` に追記). + +終了コード: + +- 0: 成功 +- 1: 実験 ID・実験ディレクトリ・設定・重みの問題,ONNX が既にある(`--overwrite` 無し)等 + (`ValueError`).メッセージをログに出し,スタックトレースは出さない +- 2: 引数の誤り(`argparse` の既定) +- 3: 書き出した ONNX が確認を通らなかった(ONNX は置かず,`metrics.json` も書き換えない) +- それ以外の例外はスタックトレースを出して異常終了する(バグとして扱う) +""" + +from __future__ import annotations + +import argparse +import json +import logging +import math +import os +import sys +import time +from collections.abc import Sequence +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +import torch + +from tongue_seg_model.data.bundle import validate_image_size +from tongue_seg_model.export.check import ( + CHECK_INPUT_SEED, + MAX_ABS_DIFF_TOLERANCE, + build_export_record, + export_input_shape, + export_output_shape, + find_export_problems, + make_check_input, + max_abs_diff, +) +from tongue_seg_model.export.onnx_export import ( + EXPORTER_NAME, + ONNX_FILENAME, + export_to_onnx, + read_onnx_info, + run_onnxruntime, + run_pytorch, +) +from tongue_seg_model.models.resunet import NUM_CLASSES, ResUNet, build_model +from tongue_seg_model.schema import ExperimentConfig, RunConfig +from tongue_seg_model.training.experiment import BEST_CHECKPOINT_FILENAME +from tongue_seg_model.training.metrics import METRICS_FILENAME, write_metrics_json +from tongue_seg_model.training.run_artifacts import ( + CHECKPOINTS_DIRNAME, + configure_logging, + load_run_config, + resolve_run_dir, +) + +logger = logging.getLogger(__name__) + +EXIT_OK = 0 +EXIT_INPUT_ERROR = 1 +EXIT_CHECK_FAILED = 3 + +METRICS_EXPORT_KEY = "export" +"""`metrics.json` の中で書き出しの記録を置くキー.""" + +# 書き出しの途中のファイル.確認を通ってから `ResUNet.onnx` に置き換える(確認を通らない +# ONNX や書きかけのファイルを `ResUNet.onnx` の名前で残さないため). +_TEMP_ONNX_FILENAME = "ResUNet.tmp.onnx" + + +@dataclass(frozen=True) +class ExportOutcome: + """書き出しの結果. + + Attributes: + onnx_path: 書き出した ONNX の場所(確認を通らなければ None). + problems: 確認で見つかった問題(空なら確認を通った). + record: `metrics.json` の `export` に書いた内容(確認を通らなければ書いていない内容). + """ + + onnx_path: Path | None + problems: list[str] + record: dict[str, Any] + + +def _read_metrics(path: Path) -> dict[str, Any]: + try: + document: Any = json.loads(path.read_text(encoding="utf-8")) + except FileNotFoundError as exc: + raise ValueError( + f"実験の {METRICS_FILENAME} が無い: {path}" + "(学習が最後まで終わっていない実験は書き出さない)" + ) from exc + except (OSError, UnicodeDecodeError, json.JSONDecodeError) as exc: + raise ValueError(f"実験の {METRICS_FILENAME} を読めない: {path}({exc})") from exc + if not isinstance(document, dict): + raise ValueError(f"実験の {METRICS_FILENAME} のトップレベルが辞書でない: {path}") + return document + + +def _load_model(config: ExperimentConfig, checkpoint_path: Path) -> ResUNet: + """`best.pth` を読み込んだ ResUNet を CPU に作る. + + 事前学習の重みは使わない(すぐに `best.pth` で全体を上書きするため.ダウンロードや + 重みファイルの有無に左右されないようにする). + """ + model_config = config.model.model_copy(update={"pretrained": False, "pretrained_weights": None}) + model = build_model(model_config) + try: + state_dict = torch.load(checkpoint_path, map_location="cpu", weights_only=True) + except Exception as exc: # 壊れたファイル・pickle の制限等,torch.load の失敗は種類が多い + raise ValueError(f"重みファイルを読めない: {checkpoint_path}({exc})") from exc + try: + model.load_state_dict(state_dict, strict=True) + except (RuntimeError, TypeError, AttributeError) as exc: + raise ValueError( + f"重みファイルが ResUNet の重みとして合わない: {checkpoint_path}({exc})" + ) from exc + model.eval() + return model + + +def export_run(run_dir: Path, *, overwrite: bool = False) -> ExportOutcome: + """実験の `best.pth` から ONNX を書き出し,確かめ,結果を `metrics.json` に書く. + + Args: + run_dir: 実験ディレクトリ(`resolve_run_dir` で求めたもの). + overwrite: `checkpoints/ResUNet.onnx` が既にあるとき上書きするか. + + Returns: + 書き出しの結果.確認を通らなければ `onnx_path` が None で `problems` が空でない + (その場合 `ResUNet.onnx` と `metrics.json` は変えない). + + Raises: + ValueError: 設定・重み・`metrics.json` が無い・読めない場合,ONNX が既にあって + `overwrite` が False の場合,書き出した ONNX を読めない場合. + """ + started = time.monotonic() + config = load_run_config(run_dir) + image_size = config.data.image_size + validate_image_size(image_size) + opset = config.export.opset + + checkpoints_dir = run_dir / CHECKPOINTS_DIRNAME + checkpoint_path = checkpoints_dir / BEST_CHECKPOINT_FILENAME + if not checkpoint_path.is_file(): + raise ValueError(f"最良の重みが無い: {checkpoint_path}") + onnx_path = checkpoints_dir / ONNX_FILENAME + if onnx_path.exists() and not overwrite: + raise ValueError( + f"ONNX が既にある: {onnx_path}(上書きしない.作り直すときは --overwrite を付ける)" + ) + metrics_path = run_dir / METRICS_FILENAME + metrics = _read_metrics(metrics_path) + + model = _load_model(config, checkpoint_path) + input_shape = export_input_shape(image_size) + output_shape = export_output_shape(image_size, NUM_CLASSES) + logger.info( + "ONNX を書き出す(%s 経由・opset %d・入力 %s・CPU)", EXPORTER_NAME, opset, input_shape + ) + + temp_path = checkpoints_dir / _TEMP_ONNX_FILENAME + try: + for message in export_to_onnx(model, temp_path, input_shape=input_shape, opset=opset): + logger.warning("書き出しの警告: %s", message) + info = read_onnx_info(temp_path) + check_input = make_check_input(input_shape, CHECK_INPUT_SEED) + expected = run_pytorch(model, check_input) + actual = run_onnxruntime(temp_path, check_input) + diff = max_abs_diff(expected, actual) if expected.shape == actual.shape else math.nan + problems = find_export_problems( + info, + opset=opset, + input_shape=input_shape, + output_shape=output_shape, + runtime_output_shape=actual.shape, + runtime_output_dtype=actual.dtype.name, + diff=diff, + ) + file_bytes = temp_path.stat().st_size + if not problems: + os.replace(temp_path, onnx_path) + finally: + temp_path.unlink(missing_ok=True) + + record = build_export_record( + info, + onnx_file=f"{CHECKPOINTS_DIRNAME}/{ONNX_FILENAME}", + exporter=EXPORTER_NAME, + torch_version=torch.__version__, + check_input_seed=CHECK_INPUT_SEED, + diff=diff, + tolerance=MAX_ABS_DIFF_TOLERANCE, + file_bytes=file_bytes, + elapsed_seconds=time.monotonic() - started, + ) + _log_record(record) + if problems: + return ExportOutcome(onnx_path=None, problems=problems, record=record) + + metrics[METRICS_EXPORT_KEY] = record + write_metrics_json(metrics_path, metrics) + return ExportOutcome(onnx_path=onnx_path, problems=[], record=record) + + +def _log_record(record: dict[str, Any]) -> None: + for kind in ("inputs", "outputs"): + for spec in record[kind]: + logger.info( + "ONNX の%s: 名前 %s・形 %s・型 %s", + "入力" if kind == "inputs" else "出力", + spec["name"], + tuple(spec["shape"]), + spec["dtype"], + ) + logger.info( + "opset %s・PyTorch との最大の絶対差 %.3g(許容値 %.1g)・%d バイト・%.1f 秒", + record["opset"], + record["max_abs_diff"], + record["tolerance"], + record["file_bytes"], + record["elapsed_seconds"], + ) + + +def _build_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser( + prog="tsm-export", + description=( + "実験の checkpoints/best.pth から ONNX(checkpoints/ResUNet.onnx)を書き出し," + "onnxruntime で入出力の形と PyTorch の出力との一致を確かめる." + "最後に書き出した ONNX のパスを標準出力に出す." + ), + ) + parser.add_argument( + "--run", + required=True, + help="実験 ID(tsm-train が標準出力に出したもの.例: 20261119-115704_synthetic_nogit)", + ) + parser.add_argument( + "--runs-dir", + type=Path, + default=RunConfig().out_dir, + help="実験ディレクトリの親(既定: 設定の run.out_dir の既定値 runs)", + ) + parser.add_argument( + "--overwrite", + action="store_true", + help="checkpoints/ResUNet.onnx が既にあるとき上書きする(既定は止める)", + ) + return parser + + +def main(argv: Sequence[str] | None = None) -> int: + """`tsm-export` を実行する. + + Args: + argv: コマンドライン引数(プログラム名を除く).None なら `sys.argv[1:]`. + + Returns: + 終了コード(0: 成功,1: 入力の問題,3: 確認を通らなかった). + """ + args = _build_parser().parse_args(argv) + configure_logging() + try: + run_dir = resolve_run_dir(args.runs_dir, args.run) + configure_logging(run_dir) + outcome = export_run(run_dir, overwrite=args.overwrite) + except ValueError as exc: + logger.error("ONNX の書き出しを中止した: %s", exc) + return EXIT_INPUT_ERROR + if outcome.onnx_path is None: + for problem in outcome.problems: + logger.error("ONNX の確認を通らなかった: %s", problem) + return EXIT_CHECK_FAILED + logger.info("ONNX を書き出した: %s", outcome.onnx_path) + sys.stdout.write(f"{outcome.onnx_path}\n") + sys.stdout.flush() + return EXIT_OK + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/src/tongue_seg_model/export/__init__.py b/src/tongue_seg_model/export/__init__.py new file mode 100644 index 0000000..fbe3c97 --- /dev/null +++ b/src/tongue_seg_model/export/__init__.py @@ -0,0 +1 @@ +"""ONNX の書き出しと,書き出した ONNX の確認(SPEC_02「ONNX の書き出し」).""" diff --git a/src/tongue_seg_model/export/check.py b/src/tongue_seg_model/export/check.py new file mode 100644 index 0000000..46bdc6e --- /dev/null +++ b/src/tongue_seg_model/export/check.py @@ -0,0 +1,243 @@ +"""書き出した ONNX の確認の判定と,書き出しの記録の組み立て(SPEC_02「ONNX の書き出し」). + +すべて純関数である(ファイル I/O・onnxruntime の実行は `export/onnx_export.py` の縁の関数で行い, +その結果を受け取って判定する).原本(`legacy/source/pytorchToOnnx.py`)は書き出した後に何も +確かめていない.確認は新しいコードで足したもの(SPEC_02「原本との対応」). +""" + +from __future__ import annotations + +from collections.abc import Sequence +from dataclasses import dataclass +from typing import Any + +import numpy as np + +EXPORT_BATCH_SIZE = 1 +"""書き出す ONNX のバッチの大きさ(原本と同じ 1.大きさは固定).""" + +INPUT_CHANNELS = 3 +"""入力のチャンネル数(BGR).""" + +ELEM_TYPE_FLOAT32 = "float32" +"""入出力の要素型(SPEC_02 の表).""" + +CHECK_INPUT_SEED = 0 +"""PyTorch と onnxruntime の出力を比べる入力の乱数の種(学習の seed とは独立に固定する).""" + +MAX_ABS_DIFF_TOLERANCE = 1e-4 +"""PyTorch と onnxruntime の出力の最大の絶対差の許容値. + +同じ float32 の計算でも演算の順序・実装の違いで丸め誤差が出る.出力は活性化関数を掛ける前の値で, +DeepTIAS の後処理はシグモイド → 8 ビット化(1/255 の刻み)なので,1e-4 の差は結果に影響しない. +""" + + +@dataclass(frozen=True) +class TensorSpec: + """ONNX のグラフの入力・出力 1 つの情報. + + Attributes: + name: 名前. + shape: 形.次元が固定でなければ,その次元は次元の名前(文字列)になる. + elem_type: 要素型(`float32` 等.ONNX の型を NumPy の名前で表したもの). + """ + + name: str + shape: tuple[int | str, ...] + elem_type: str + + def to_dict(self) -> dict[str, Any]: + """書き出しの記録に書く形の dict を返す. + + Returns: + `name`・`shape`(list)・`dtype` をキーとする dict. + """ + return {"name": self.name, "shape": list(self.shape), "dtype": self.elem_type} + + +@dataclass(frozen=True) +class OnnxModelInfo: + """書き出した ONNX のグラフの情報(`onnx` で読んだもの). + + Attributes: + opset: 既定の領域(`ai.onnx`)の opset の版.既定の領域の記載が無ければ None. + inputs: グラフの入力(重みを除く). + outputs: グラフの出力. + """ + + opset: int | None + inputs: tuple[TensorSpec, ...] + outputs: tuple[TensorSpec, ...] + + +def export_input_shape(image_size: Sequence[int]) -> tuple[int, int, int, int]: + """書き出す ONNX の入力の形を返す. + + Args: + image_size: 画像の大きさ `(高さ, 幅)`(設定の `data.image_size`.既定 `(256, 256)`). + + Returns: + `(1, 3, 高さ, 幅)`. + """ + height, width = image_size + return (EXPORT_BATCH_SIZE, INPUT_CHANNELS, int(height), int(width)) + + +def export_output_shape(image_size: Sequence[int], num_classes: int) -> tuple[int, int, int, int]: + """書き出す ONNX の出力の形を返す. + + Args: + image_size: 画像の大きさ `(高さ, 幅)`. + num_classes: 出力のチャンネル数(舌・舌以外の 2). + + Returns: + `(1, num_classes, 高さ, 幅)`. + """ + height, width = image_size + return (EXPORT_BATCH_SIZE, int(num_classes), int(height), int(width)) + + +def make_check_input(shape: Sequence[int], seed: int) -> np.ndarray: + """PyTorch と onnxruntime の出力を比べるための入力を作る. + + 実際の入力(BGR を 255 で割った値)と同じ値域の一様乱数にする.専用の乱数生成器を使い, + グローバルな乱数の状態に依存しない. + + Args: + shape: 入力の形(`(1, 3, H, W)`). + seed: 乱数の種. + + Returns: + `shape` の float32 の配列(値域 0.0 以上 1.0 未満). + """ + rng = np.random.default_rng(seed) + return rng.random(tuple(shape), dtype=np.float32) + + +def max_abs_diff(expected: np.ndarray, actual: np.ndarray) -> float: + """2 つの出力の最大の絶対差を返す. + + Args: + expected: PyTorch の出力. + actual: onnxruntime の出力(`expected` と同じ形). + + Returns: + 最大の絶対差.どちらかに NaN があれば NaN. + + Raises: + RuntimeError: 形が違う場合(呼び出し側が先に形を確かめる前提のため,内部の誤り). + """ + if expected.shape != actual.shape: + raise RuntimeError(f"出力の形が違うものは比べられない: {expected.shape} と {actual.shape}") + if expected.size == 0: + return 0.0 + diff = np.abs(expected.astype(np.float64) - actual.astype(np.float64)) + return float(np.max(diff)) + + +def _spec_problems( + kind: str, + specs: Sequence[TensorSpec], + expected_shape: Sequence[int], +) -> list[str]: + if len(specs) != 1: + return [f"{kind}の数が {len(specs)} である(1 つのはず)"] + spec = specs[0] + problems: list[str] = [] + if tuple(spec.shape) != tuple(expected_shape): + problems.append(f"{kind}の形が {spec.shape} である({tuple(expected_shape)} のはず)") + if spec.elem_type != ELEM_TYPE_FLOAT32: + problems.append(f"{kind}の型が {spec.elem_type} である({ELEM_TYPE_FLOAT32} のはず)") + return problems + + +def find_export_problems( + info: OnnxModelInfo, + *, + opset: int, + input_shape: Sequence[int], + output_shape: Sequence[int], + runtime_output_shape: Sequence[int], + runtime_output_dtype: str, + diff: float, + tolerance: float = MAX_ABS_DIFF_TOLERANCE, +) -> list[str]: + """書き出した ONNX が SPEC_02 の表のとおりかを判定する. + + Args: + info: `onnx` で読んだグラフの情報. + opset: 書き出しに指定した opset の版. + input_shape: 期待する入力の形(`(1, 3, H, W)`). + output_shape: 期待する出力の形(`(1, 2, H, W)`). + runtime_output_shape: onnxruntime で実際に推論した出力の形. + runtime_output_dtype: onnxruntime で実際に推論した出力の要素型(NumPy の名前). + diff: PyTorch の出力との最大の絶対差(`max_abs_diff`). + tolerance: 最大の絶対差の許容値. + + Returns: + 問題の説明の一覧(空なら問題なし). + """ + problems: list[str] = [] + if info.opset != opset: + problems.append(f"opset が {info.opset} である({opset} のはず)") + problems.extend(_spec_problems("入力", info.inputs, input_shape)) + problems.extend(_spec_problems("出力", info.outputs, output_shape)) + if tuple(runtime_output_shape) != tuple(output_shape): + problems.append( + f"onnxruntime の出力の形が {tuple(runtime_output_shape)} である" + f"({tuple(output_shape)} のはず)" + ) + if runtime_output_dtype != ELEM_TYPE_FLOAT32: + problems.append( + f"onnxruntime の出力の型が {runtime_output_dtype} である({ELEM_TYPE_FLOAT32} のはず)" + ) + # NaN は比較が常に偽になるため,「許容値以下」で判定する(NaN も問題として扱う). + if not diff <= tolerance: + problems.append(f"PyTorch の出力との最大の絶対差 {diff} が許容値 {tolerance} を超える") + return problems + + +def build_export_record( + info: OnnxModelInfo, + *, + onnx_file: str, + exporter: str, + torch_version: str, + check_input_seed: int, + diff: float, + tolerance: float, + file_bytes: int, + elapsed_seconds: float, +) -> dict[str, Any]: + """`metrics.json` の `export` に書く内容を作る. + + データのパス・ファイル名・患者 ID は含まない(回収する `metrics.json` に書くため). + + Args: + info: `onnx` で読んだグラフの情報. + onnx_file: 実験ディレクトリから見た ONNX の場所(`checkpoints/ResUNet.onnx`). + exporter: 使った書き出し方法(`torchscript` 等). + torch_version: 書き出しに使った PyTorch の版. + check_input_seed: 比較に使った入力の乱数の種. + diff: PyTorch の出力との最大の絶対差. + tolerance: 最大の絶対差の許容値. + file_bytes: ONNX のファイルの大きさ(バイト). + elapsed_seconds: 書き出しと確認にかかった時間(秒). + + Returns: + JSON に書き出せる dict. + """ + return { + "onnx_file": onnx_file, + "exporter": exporter, + "torch_version": torch_version, + "opset": info.opset, + "inputs": [spec.to_dict() for spec in info.inputs], + "outputs": [spec.to_dict() for spec in info.outputs], + "check_input_seed": check_input_seed, + "max_abs_diff": diff, + "tolerance": tolerance, + "file_bytes": file_bytes, + "elapsed_seconds": elapsed_seconds, + } diff --git a/src/tongue_seg_model/export/onnx_export.py b/src/tongue_seg_model/export/onnx_export.py new file mode 100644 index 0000000..03cbb01 --- /dev/null +++ b/src/tongue_seg_model/export/onnx_export.py @@ -0,0 +1,186 @@ +"""ResUNet の ONNX への書き出しと,書き出した ONNX の読み込み・推論(縁の関数). + +原本: `legacy/source/pytorchToOnnx.py` の +`torch.onnx.export(model, torch.zeros([1, 3, 256, 256]), path, opset_version=11)`. + +書き出しには従来の TorchScript 経由の方法(`dynamo=False`)を使う.PyTorch 2.9 以降の既定 +(`dynamo=True`.`torch.export` 経由)は opset 18 で書き出し,opset 11 へ変換できない +(onnx の版の変換器に Identity の 16 → 15 の変換が無い).また入出力の名前も原本と変わる +(`x`・`conv2d_32` 等).TorchScript 経由なら原本と同じ opset 11・同じ入出力の名前 +(`input.1`・`269`)になる.入出力の名前は原本と同じく指定しない(PyTorch が付ける名前のまま. +SPEC_02「ONNX の書き出し」: 名前の合わせ込みはしない). + +判定は `export/check.py` の純関数で行う. +""" + +from __future__ import annotations + +import warnings +from collections.abc import Sequence +from pathlib import Path + +import numpy as np +import onnx +import onnxruntime +import torch +from google.protobuf.message import DecodeError +from onnxruntime.capi import onnxruntime_pybind11_state as _ort_state +from torch import nn + +from tongue_seg_model.export.check import OnnxModelInfo, TensorSpec + +ONNX_FILENAME = "ResUNet.onnx" +"""書き出す ONNX のファイル名(`checkpoints/` の下.原本と同じ名前).""" + +EXPORTER_NAME = "torchscript" +"""書き出しの記録に書く,使った書き出し方法の名前.""" + +# ONNX の既定の領域(ai.onnx).opset_import では空文字列か "ai.onnx" で表される. +_DEFAULT_DOMAINS = ("", "ai.onnx") + +# onnxruntime が読み込み・推論の失敗で送出する例外(RuntimeError の派生ではなく Exception の直下). +# NotImplemented は onnxruntime が対応しない演算・opset の場合に出る. +_ORT_ERRORS: tuple[type[Exception], ...] = ( + _ort_state.EPFail, + _ort_state.Fail, + _ort_state.InvalidArgument, + _ort_state.InvalidGraph, + _ort_state.InvalidProtobuf, + _ort_state.NoModel, + _ort_state.NoSuchFile, + _ort_state.NotFound, + _ort_state.NotImplemented, + _ort_state.RuntimeException, + RuntimeError, +) + + +def export_to_onnx( + model: nn.Module, path: Path, *, input_shape: Sequence[int], opset: int +) -> list[str]: + """モデルを推論モード・CPU で ONNX に書き出す. + + Args: + model: 重みを読み込んだ ResUNet(CPU 上にあること).推論モードにして書き出す. + path: 書き出す先. + input_shape: 入力の形(`(1, 3, H, W)`.大きさは固定で書き出す). + opset: opset の版(既定は原本と同じ 11). + + Returns: + 書き出しの間に出た警告の文面(TorchScript 経由の書き出しが非推奨である旨等). + 呼び出し側がログに残す. + + Raises: + ValueError: 指定した opset で書き出せない場合. + """ + model.eval() + dummy = torch.zeros(tuple(input_shape), dtype=torch.float32) + # 書き出しに失敗すると,PyTorch(C++ の部分)が作りかけのグラフ(数百行)を標準出力に直接 + # 書く(Python の sys.stdout を差し替えても止められない).失敗は終了コードで判断する. + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + try: + torch.onnx.export( + model, + (dummy,), + str(path), + opset_version=opset, + dynamo=False, + ) + except torch.onnx.errors.OnnxExporterError as exc: + # 設定の export.opset で書き出せない演算がある場合等(設定の問題として扱う). + # 文面にはグラフの内容が続くことがあるので,ログには最初の行だけを出す. + text = str(exc).strip() + first_line = text.splitlines()[0] if text else type(exc).__name__ + raise ValueError(f"opset {opset} で ONNX を書き出せない({first_line})") from exc + return [f"{item.category.__name__}: {item.message}" for item in caught] + + +def _np_dtype_name(elem_type: int) -> str: + try: + return np.dtype(onnx.helper.tensor_dtype_to_np_dtype(elem_type)).name + except (KeyError, TypeError, ValueError): + return f"onnx:{elem_type}" + + +def _tensor_spec(value_info: onnx.ValueInfoProto) -> TensorSpec: + tensor_type = value_info.type.tensor_type + shape: list[int | str] = [] + for dim in tensor_type.shape.dim: + if dim.HasField("dim_value"): + shape.append(int(dim.dim_value)) + else: + shape.append(dim.dim_param or "?") + return TensorSpec( + name=value_info.name, shape=tuple(shape), elem_type=_np_dtype_name(tensor_type.elem_type) + ) + + +def read_onnx_info(path: Path) -> OnnxModelInfo: + """書き出した ONNX を `onnx` で読み,検査器に通して opset と入出力の情報を返す. + + Args: + path: ONNX のファイル. + + Returns: + opset・入力(重みを除く)・出力の情報. + + Raises: + ValueError: ONNX として読めない・検査器を通らない場合. + """ + try: + proto = onnx.load(str(path)) + onnx.checker.check_model(proto) + except DecodeError: + # 壊れたファイルを onnx.load で読むと protobuf の DecodeError が出る + # (ValueError・OSError の派生ではない). + raise ValueError("書き出した ONNX を読めない(ONNX の形式として解釈できない)") from None + except (onnx.checker.ValidationError, OSError, ValueError) as exc: + raise ValueError(f"書き出した ONNX を読めない・検査を通らない({exc})") from exc + opsets = [entry.version for entry in proto.opset_import if entry.domain in _DEFAULT_DOMAINS] + initializers = {init.name for init in proto.graph.initializer} + inputs = tuple( + _tensor_spec(value) for value in proto.graph.input if value.name not in initializers + ) + outputs = tuple(_tensor_spec(value) for value in proto.graph.output) + return OnnxModelInfo(opset=opsets[0] if opsets else None, inputs=inputs, outputs=outputs) + + +def run_onnxruntime(path: Path, x: np.ndarray) -> np.ndarray: + """onnxruntime(CPU)で ONNX を読み込み,1 回推論する. + + Args: + path: ONNX のファイル. + x: 入力(`(1, 3, H, W)`, float32, BGR を 255 で割った値). + + Returns: + 最初の出力(`(1, 2, H, W)` のはず.活性化関数を掛ける前の値). + + Raises: + ValueError: onnxruntime で読み込めない・推論できない場合,入力が 1 つでない場合. + """ + try: + session = onnxruntime.InferenceSession(str(path), providers=["CPUExecutionProvider"]) + session_inputs = session.get_inputs() + if len(session_inputs) != 1: + raise ValueError(f"ONNX の入力が {len(session_inputs)} 個ある(1 つのはず)") + outputs = session.run(None, {session_inputs[0].name: x}) + except _ORT_ERRORS as exc: + raise ValueError(f"onnxruntime で ONNX を読み込めない・推論できない({exc})") from exc + return np.asarray(outputs[0]) + + +def run_pytorch(model: nn.Module, x: np.ndarray) -> np.ndarray: + """PyTorch(CPU・推論モード)で 1 回推論する. + + Args: + model: ResUNet(CPU 上にあること). + x: 入力(`(1, 3, H, W)`, float32). + + Returns: + 出力(`(1, 2, H, W)`, float32.活性化関数を掛ける前の値). + """ + model.eval() + with torch.no_grad(): + output = model(torch.from_numpy(x)) + return output.numpy() diff --git a/src/tongue_seg_model/training/run_artifacts.py b/src/tongue_seg_model/training/run_artifacts.py index 8993dda..1ebb9bb 100644 --- a/src/tongue_seg_model/training/run_artifacts.py +++ b/src/tongue_seg_model/training/run_artifacts.py @@ -34,9 +34,17 @@ # 実験 ID はディレクトリ名・環境変数の値として使うため,安全な文字だけを許す # (git の短縮ハッシュと `-dirty` を想定). -_GIT_COMMIT_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$") -_CONFIG_NAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$") -_SHA256_RE = re.compile(r"^[0-9a-f]{64}$") +# いずれも `fullmatch` で使う(`match` と `$` では末尾の改行を通してしまうため). +_GIT_COMMIT_PATTERN = r"[A-Za-z0-9][A-Za-z0-9_-]{0,63}" +_CONFIG_NAME_PATTERN = r"[A-Za-z0-9][A-Za-z0-9._-]{0,63}" +_GIT_COMMIT_RE = re.compile(_GIT_COMMIT_PATTERN) +_CONFIG_NAME_RE = re.compile(_CONFIG_NAME_PATTERN) +_SHA256_RE = re.compile(r"[0-9a-f]{64}") +# `make_run_id` が作る実験 ID の形(`YYYYmmdd-HHMMSS_<設定ファイル名>_`). +# 外から受け取った実験 ID をパスの組み立てに使う前に確かめる(`..`・区切り文字で +# 実験ディレクトリの親の外を指せないようにするため.各部分は英数字で始まり `/`・`\` を含まない). +# 各部分は `make_run_id` の確認と同じ形を使う(2 か所でずれないようにするため). +_RUN_ID_RE = re.compile(rf"[0-9]{{8}}-[0-9]{{6}}_{_CONFIG_NAME_PATTERN}_{_GIT_COMMIT_PATTERN}") _LOG_FORMAT = "%(asctime)s %(levelname)s %(name)s: %(message)s" # 本モジュールが root logger に付けるハンドラの名前.2 回目の呼び出しで付け直すために使う. @@ -66,7 +74,7 @@ raise ValueError("バンドルの指紋の name が空である") if isinstance(self.version, bool) or not isinstance(self.version, int) or self.version < 1: raise ValueError("バンドルの指紋の version は 1 以上の整数でなければならない") - if not _SHA256_RE.match(self.manifest_sha256): + if not _SHA256_RE.fullmatch(self.manifest_sha256): raise ValueError("バンドルの指紋の manifest_sha256 は 16 進の小文字 64 文字である") def to_dict(self) -> dict[str, str | int]: @@ -98,7 +106,7 @@ value = env.get(GIT_COMMIT_ENV_VAR, "").strip() if not value: return NO_GIT - if not _GIT_COMMIT_RE.match(value): + if not _GIT_COMMIT_RE.fullmatch(value): raise ValueError( f"環境変数 {GIT_COMMIT_ENV_VAR} の値が不正である: {value!r}" "(英数字で始まり,英数字・_・- のみ,64 文字以内)" @@ -120,16 +128,80 @@ Raises: ValueError: `config_name` または `git_commit` がディレクトリ名に使えない文字を含む場合. """ - if not _CONFIG_NAME_RE.match(config_name): + if not _CONFIG_NAME_RE.fullmatch(config_name): raise ValueError( f"設定ファイル名が実験 ID に使えない: {config_name!r}" "(英数字で始まり,英数字・.・_・- のみ,64 文字以内)" ) - if not _GIT_COMMIT_RE.match(git_commit): + if not _GIT_COMMIT_RE.fullmatch(git_commit): raise ValueError(f"git のハッシュが実験 ID に使えない: {git_commit!r}") return f"{now:%Y%m%d-%H%M%S}_{config_name}_{git_commit}" +def validate_run_id(run_id: str) -> str: + """外から受け取った実験 ID の形式を確かめる(純関数). + + Args: + run_id: 実験 ID(`make_run_id` の形 `YYYYmmdd-HHMMSS_<設定ファイル名>_`). + + Returns: + `run_id` そのもの. + + Raises: + ValueError: 実験 ID の形でない場合(区切り文字・`..` を含む等). + """ + if not _RUN_ID_RE.fullmatch(run_id): + raise ValueError( + f"実験 ID の形式が不正である: {run_id!r}" + "(YYYYmmdd-HHMMSS_<設定ファイル名>_ の形.tsm-train が出した ID)" + ) + return run_id + + +def resolve_run_dir(out_dir: Path, run_id: str) -> Path: + """既存の実験ディレクトリ `//` を返す. + + Args: + out_dir: 実験ディレクトリの親. + run_id: 実験 ID(形式を確かめてからパスに使う). + + Returns: + 実験ディレクトリ. + + Raises: + ValueError: 実験 ID の形式が不正な場合,実験ディレクトリが無い場合. + """ + run_dir = out_dir / validate_run_id(run_id) + if not run_dir.is_dir(): + raise ValueError(f"実験ディレクトリが無い: {run_dir}") + return run_dir + + +def load_run_config(run_dir: Path) -> ExperimentConfig: + """実験ディレクトリの `config.yaml` から,その実験の設定を読み戻す. + + Args: + run_dir: 実験ディレクトリ. + + Returns: + `config.yaml` の `config`(解決済みの設定)を検証したもの. + + Raises: + ValueError: `config.yaml` が無い・読めない・`config` が辞書でない場合. + pydantic.ValidationError: 設定の内容が今のスキーマで不正な場合. + """ + path = run_dir / CONFIG_FILENAME + try: + document: Any = yaml.safe_load(path.read_text(encoding="utf-8")) + except FileNotFoundError as exc: + raise ValueError(f"実験の {CONFIG_FILENAME} が無い: {path}") from exc + except (OSError, UnicodeDecodeError, yaml.YAMLError) as exc: + raise ValueError(f"実験の {CONFIG_FILENAME} を読めない: {path}({exc})") from exc + if not isinstance(document, dict) or not isinstance(document.get("config"), dict): + raise ValueError(f"実験の {CONFIG_FILENAME} に設定(config)が無い: {path}") + return ExperimentConfig.model_validate(document["config"]) + + def create_run_dir(out_dir: Path, run_id: str) -> Path: """実験ディレクトリ `//` と,その下の `figures/`・`checkpoints/` を作る. diff --git a/tests/cli/test_export.py b/tests/cli/test_export.py new file mode 100644 index 0000000..c994fd7 --- /dev/null +++ b/tests/cli/test_export.py @@ -0,0 +1,515 @@ +"""`tsm-export --run <実験ID>`(`cli/export.py`)の統合テスト. + +期待値は SPEC_01「CLI」「実験の出力」(`checkpoints/ResUNet.onnx`・`metrics.json` は集計値だけで +ファイル名を含まない)と SPEC_02「ONNX の書き出し」(opset 11・入出力の形と型・PyTorch との差を +確かめて記録する),ENV_04 の終了コード(0 成功/1 入力の問題/2 引数の誤り/3 確認を通らなかった. +確認を通らなければ ONNX を置かず `metrics.json` も変えない)を基準にする. + +実験フォルダは学習を回さずに作る(`build_model` の state_dict を `best.pth` に保存し, +`config.yaml`・`metrics.json` は run_artifacts・metrics の関数で書く).画像は 64×64. +実際に書き出すテストは `slow`.書き出すたびに約 70MB のファイルができるので,回数を絞り, +テストの後で ONNX を消す. +""" + +from __future__ import annotations + +import importlib.metadata +import json +import logging +from collections.abc import Iterator +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +import pytest +import torch + +import tongue_seg_model.cli.export as export_cli +from tongue_seg_model.cli.export import main +from tongue_seg_model.export.check import MAX_ABS_DIFF_TOLERANCE +from tongue_seg_model.models.resunet import build_model +from tongue_seg_model.schema import ExperimentConfig +from tongue_seg_model.training.metrics import build_metrics_document, write_metrics_json +from tongue_seg_model.training.run_artifacts import ( + build_config_document, + configure_logging, + create_run_dir, + write_config_yaml, +) + +SIZE = (64, 64) +RUN_ID = "20261119-102030_synthetic_abc1234" +SHA = "0123456789abcdef" * 4 +PREVIOUS_LOG_LINE = "previous training log line" + + +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(autouse=True) +def restore_logging() -> Iterator[None]: + """root logger の状態を戻し,`log.txt` のハンドラを閉じる(Windows での削除失敗を防ぐ).""" + level = logging.getLogger().level + yield + _close_own_handlers() + logging.getLogger().setLevel(level) + + +def _config(**overrides: Any) -> ExperimentConfig: + raw: dict[str, Any] = { + "data": {"bundle": {"name": "synthetic", "version": 1}, "image_size": list(SIZE)}, + # 学習時の設定は事前学習の重みあり(書き出しでは使わずダウンロードもしないこと) + "model": {"pretrained": True}, + "train": {"device": "cpu", "seed": 0}, + } + for section, values in overrides.items(): + raw.setdefault(section, {}).update(values) + return ExperimentConfig.model_validate(raw) + + +def _metrics() -> dict[str, Any]: + return build_metrics_document( + best_epoch=1, + best_val_loss=0.5, + epochs_run=2, + stopped_early=False, + test_iou={"count": 2, "mean": 0.5, "median": 0.5, "min": 0.4, "max": 0.6, "std": 0.1}, + counts={"train": 4, "val": 2, "test": 2}, + data_bundle={"name": "synthetic", "version": 1, "manifest_sha256": SHA}, + elapsed_seconds=1.0, + ) + + +def _make_run( + runs_dir: Path, + *, + config: ExperimentConfig | None = None, + best_pth: bool = True, + metrics: bool = True, +) -> Path: + """学習を回さずに,書き出しに要るものだけをそろえた実験ディレクトリを作る.""" + config = _config() if config is None else config + run_dir = create_run_dir(runs_dir, RUN_ID) + write_config_yaml(run_dir, build_config_document(config, run_id=RUN_ID, git_commit="abc1234")) + if best_pth: + torch.manual_seed(0) + model = build_model(config.model.model_copy(update={"pretrained": False})) + torch.save(model.state_dict(), run_dir / "checkpoints" / "best.pth") + if metrics: + write_metrics_json(run_dir / "metrics.json", _metrics()) + (run_dir / "log.txt").write_text(PREVIOUS_LOG_LINE + "\n", encoding="utf-8") + return run_dir + + +def _argv(runs_dir: Path, *extra: str, run_id: str = RUN_ID) -> list[str]: + return ["--run", run_id, "--runs-dir", str(runs_dir), *extra] + + +def _onnx(run_dir: Path) -> Path: + return run_dir / "checkpoints" / "ResUNet.onnx" + + +def _checkpoint_names(run_dir: Path) -> set[str]: + return {p.name for p in (run_dir / "checkpoints").iterdir()} + + +def _read_log(run_dir: Path) -> str: + for handler in logging.getLogger().handlers: + handler.flush() + return (run_dir / "log.txt").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) + + +def test_entry_point_is_registered() -> None: + points = importlib.metadata.entry_points(group="console_scripts", name="tsm-export") + assert [p.value for p in points] == ["tongue_seg_model.cli.export:main"] + + +# --------------------------------------------------------------------------- +# 引数の誤り(終了コード 2) +# --------------------------------------------------------------------------- + + +class TestArgumentErrors: + def test_missing_run_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([*_argv(tmp_path), "--unknown"]) + assert info.value.code == 2 + + def test_overwrite_takes_no_value(self, tmp_path: Path) -> None: + with pytest.raises(SystemExit) as info: + main(["--run", RUN_ID, "--overwrite=yes"]) + assert info.value.code == 2 + + +# --------------------------------------------------------------------------- +# 入力の問題(終了コード 1.書き出す前に止まる) +# --------------------------------------------------------------------------- + + +class TestInputErrors: + @pytest.mark.parametrize( + "run_id", + [ + "..", + ".", + "", + "../" + RUN_ID, + RUN_ID + "/..", + "..\\" + RUN_ID, + RUN_ID + "\n", + "not-a-run-id", + ], + ) + def test_invalid_run_id_exits_with_1( + self, tmp_path: Path, run_id: str, caplog: pytest.LogCaptureFixture + ) -> None: + runs_dir = tmp_path / "runs" + _make_run(runs_dir, best_pth=False) + assert main(_argv(runs_dir, run_id=run_id)) == 1 + assert "実験 ID" in caplog.text + assert "Traceback" not in caplog.text + + def test_parent_dir_run_id_does_not_touch_parent(self, tmp_path: Path) -> None: + # runs/.. が「実験ディレクトリ」として扱われ,その下に何か作られることがない + runs_dir = tmp_path / "runs" + runs_dir.mkdir() + before = sorted(p.name for p in tmp_path.rglob("*")) + assert main(_argv(runs_dir, run_id="..")) == 1 + assert sorted(p.name for p in tmp_path.rglob("*")) == before + + def test_missing_run_dir_exits_with_1( + self, tmp_path: Path, caplog: pytest.LogCaptureFixture + ) -> None: + assert main(_argv(tmp_path / "runs")) == 1 + assert "実験ディレクトリが無い" in caplog.text + + def test_missing_config_exits_with_1( + self, tmp_path: Path, caplog: pytest.LogCaptureFixture + ) -> None: + run_dir = _make_run(tmp_path, best_pth=False) + (run_dir / "config.yaml").unlink() + assert main(_argv(tmp_path)) == 1 + assert "config.yaml" in caplog.text + + def test_invalid_config_content_exits_with_1(self, tmp_path: Path) -> None: + # pydantic の ValidationError も ValueError の一種として終了コード 1 + run_dir = _make_run(tmp_path, best_pth=False) + (run_dir / "config.yaml").write_text( + "config:\n data:\n bundle: {name: synthetic, version: 1}\n export: {opset: 3}\n", + encoding="utf-8", + ) + assert main(_argv(tmp_path)) == 1 + + def test_image_size_not_multiple_of_32_exits_with_1( + self, tmp_path: Path, caplog: pytest.LogCaptureFixture + ) -> None: + config = _config( + data={"bundle": {"name": "synthetic", "version": 1}, "image_size": [48, 64]} + ) + _make_run(tmp_path, config=config, best_pth=False) + assert main(_argv(tmp_path)) == 1 + assert "32" in caplog.text + + def test_missing_best_pth_exits_with_1( + self, tmp_path: Path, caplog: pytest.LogCaptureFixture + ) -> None: + run_dir = _make_run(tmp_path, best_pth=False) + assert main(_argv(tmp_path)) == 1 + assert "best.pth" in caplog.text + assert _checkpoint_names(run_dir) == set() + + def test_broken_best_pth_exits_with_1(self, tmp_path: Path) -> None: + run_dir = _make_run(tmp_path, best_pth=False) + (run_dir / "checkpoints" / "best.pth").write_bytes(b"not a checkpoint") + assert main(_argv(tmp_path)) == 1 + assert _checkpoint_names(run_dir) == {"best.pth"} + + def test_mismatched_best_pth_exits_with_1(self, tmp_path: Path) -> None: + run_dir = _make_run(tmp_path, best_pth=False) + torch.save({"unexpected.weight": torch.zeros(1)}, run_dir / "checkpoints" / "best.pth") + assert main(_argv(tmp_path)) == 1 + assert _checkpoint_names(run_dir) == {"best.pth"} + + def test_missing_metrics_exits_with_1( + self, tmp_path: Path, caplog: pytest.LogCaptureFixture + ) -> None: + run_dir = _make_run(tmp_path, metrics=False) + assert main(_argv(tmp_path)) == 1 + assert "metrics.json" in caplog.text + assert _checkpoint_names(run_dir) == {"best.pth"} + assert not (run_dir / "metrics.json").exists() + + @pytest.mark.parametrize("text", ["{broken", "[1, 2]", '"text"']) + def test_unreadable_metrics_exits_with_1(self, tmp_path: Path, text: str) -> None: + run_dir = _make_run(tmp_path) + (run_dir / "metrics.json").write_text(text, encoding="utf-8") + assert main(_argv(tmp_path)) == 1 + assert (run_dir / "metrics.json").read_text(encoding="utf-8") == text + assert _checkpoint_names(run_dir) == {"best.pth"} + + def test_existing_onnx_without_overwrite_exits_with_1( + self, tmp_path: Path, caplog: pytest.LogCaptureFixture + ) -> None: + run_dir = _make_run(tmp_path) + _onnx(run_dir).write_bytes(b"old onnx") + metrics_before = (run_dir / "metrics.json").read_bytes() + assert main(_argv(tmp_path)) == 1 + assert "--overwrite" in caplog.text + assert _onnx(run_dir).read_bytes() == b"old onnx" + assert (run_dir / "metrics.json").read_bytes() == metrics_before + + def test_error_is_appended_to_log_txt(self, tmp_path: Path) -> None: + run_dir = _make_run(tmp_path, best_pth=False) + assert main(_argv(tmp_path)) == 1 + log = _read_log(run_dir) + assert log.startswith(PREVIOUS_LOG_LINE + "\n") + assert "best.pth" in log + + def test_nothing_written_to_stdout_on_error( + self, tmp_path: Path, capsys: pytest.CaptureFixture[str] + ) -> None: + _make_run(tmp_path, best_pth=False) + assert main(_argv(tmp_path)) == 1 + assert capsys.readouterr().out == "" + + +# --------------------------------------------------------------------------- +# 書き出しの成功(終了コード 0.slow) +# --------------------------------------------------------------------------- + + +@dataclass(frozen=True) +class ExportedRun: + run_dir: Path + runs_dir: Path + exit_code: int + stdout: str + metrics_before: dict[str, Any] + + +@pytest.fixture(scope="module") +def exported_run(tmp_path_factory: pytest.TempPathFactory) -> Iterator[ExportedRun]: + """実験フォルダを作り,`tsm-export` を 1 回通す(このモジュールの成功系で共有する).""" + import contextlib + import io + + runs_dir = tmp_path_factory.mktemp("export") / "runs" + run_dir = _make_run(runs_dir) + metrics_before = _strict_json(run_dir / "metrics.json") + level = logging.getLogger().level + stdout = io.StringIO() + try: + with contextlib.redirect_stdout(stdout): + code = main(_argv(runs_dir)) + _close_own_handlers() + yield ExportedRun( + run_dir=run_dir, + runs_dir=runs_dir, + exit_code=code, + stdout=stdout.getvalue(), + metrics_before=metrics_before, + ) + finally: + _close_own_handlers() + logging.getLogger().setLevel(level) + _onnx(run_dir).unlink(missing_ok=True) + + +@pytest.mark.slow +class TestExportSucceeds: + def test_exit_code_is_0(self, exported_run: ExportedRun) -> None: + assert exported_run.exit_code == 0 + + def test_prints_onnx_path_on_one_line(self, exported_run: ExportedRun) -> None: + assert exported_run.stdout == f"{_onnx(exported_run.run_dir)}\n" + + def test_onnx_is_placed_and_temp_file_removed(self, exported_run: ExportedRun) -> None: + assert _onnx(exported_run.run_dir).is_file() + assert _checkpoint_names(exported_run.run_dir) == {"best.pth", "ResUNet.onnx"} + + def test_run_dir_has_no_other_new_files(self, exported_run: ExportedRun) -> None: + names = {p.name for p in exported_run.run_dir.iterdir()} + assert names == {"config.yaml", "metrics.json", "log.txt", "figures", "checkpoints"} + assert list((exported_run.run_dir / "figures").iterdir()) == [] + + def test_metrics_keeps_existing_keys(self, exported_run: ExportedRun) -> None: + metrics = _strict_json(exported_run.run_dir / "metrics.json") + assert {k: v for k, v in metrics.items() if k != "export"} == exported_run.metrics_before + + def test_metrics_export_record(self, exported_run: ExportedRun) -> None: + record = _strict_json(exported_run.run_dir / "metrics.json")["export"] + assert record["onnx_file"] == "checkpoints/ResUNet.onnx" + assert record["opset"] == 11 + assert len(record["inputs"]) == 1 + assert len(record["outputs"]) == 1 + assert record["inputs"][0]["shape"] == [1, 3, *SIZE] + assert record["inputs"][0]["dtype"] == "float32" + assert record["outputs"][0]["shape"] == [1, 2, *SIZE] + assert record["outputs"][0]["dtype"] == "float32" + # 名前は記録する(合わせ込みはしない) + assert isinstance(record["inputs"][0]["name"], str) and record["inputs"][0]["name"] + assert isinstance(record["outputs"][0]["name"], str) and record["outputs"][0]["name"] + assert 0.0 <= record["max_abs_diff"] <= MAX_ABS_DIFF_TOLERANCE + assert record["tolerance"] == MAX_ABS_DIFF_TOLERANCE + assert record["file_bytes"] == _onnx(exported_run.run_dir).stat().st_size + assert record["elapsed_seconds"] > 0 + assert record["torch_version"] == torch.__version__ + assert isinstance(record["check_input_seed"], int) + + def test_metrics_has_no_absolute_paths(self, exported_run: ExportedRun) -> None: + text = (exported_run.run_dir / "metrics.json").read_text(encoding="utf-8") + assert str(exported_run.runs_dir) not in text + assert str(exported_run.runs_dir).replace("\\", "\\\\") not in text + assert exported_run.runs_dir.as_posix() not in text + + def test_log_txt_is_appended(self, exported_run: ExportedRun) -> None: + log = (exported_run.run_dir / "log.txt").read_text(encoding="utf-8") + assert log.startswith(PREVIOUS_LOG_LINE + "\n") + assert "ONNX" in log + assert "opset 11" in log + + def test_exported_onnx_runs_and_matches_record(self, exported_run: ExportedRun) -> None: + from tongue_seg_model.export.check import make_check_input + from tongue_seg_model.export.onnx_export import read_onnx_info, run_onnxruntime + + path = _onnx(exported_run.run_dir) + info = read_onnx_info(path) + record = _strict_json(exported_run.run_dir / "metrics.json")["export"] + assert [s.to_dict() for s in info.inputs] == record["inputs"] + assert [s.to_dict() for s in info.outputs] == record["outputs"] + y = run_onnxruntime(path, make_check_input((1, 3, *SIZE), 0)) + assert y.shape == (1, 2, *SIZE) + + def test_onnx_uses_best_pth_weights(self, exported_run: ExportedRun) -> None: + # best.pth の重みで書き出していること(PyTorch に best.pth を読ませた出力と一致) + from tongue_seg_model.export.check import make_check_input, max_abs_diff + from tongue_seg_model.export.onnx_export import run_onnxruntime, run_pytorch + from tongue_seg_model.models.resunet import ResUNet + + model = ResUNet(pretrained=False) + state = torch.load( + exported_run.run_dir / "checkpoints" / "best.pth", map_location="cpu", weights_only=True + ) + model.load_state_dict(state) + x = make_check_input((1, 3, *SIZE), 5) + diff = max_abs_diff(run_pytorch(model, x), run_onnxruntime(_onnx(exported_run.run_dir), x)) + assert diff <= MAX_ABS_DIFF_TOLERANCE + + def test_second_run_without_overwrite_exits_with_1(self, exported_run: ExportedRun) -> None: + path = _onnx(exported_run.run_dir) + before = (path.stat().st_mtime_ns, path.stat().st_size) + metrics_before = (exported_run.run_dir / "metrics.json").read_bytes() + assert main(_argv(exported_run.runs_dir)) == 1 + assert (path.stat().st_mtime_ns, path.stat().st_size) == before + assert (exported_run.run_dir / "metrics.json").read_bytes() == metrics_before + + +@pytest.mark.slow +def test_overwrite_replaces_existing_onnx(tmp_path: Path) -> None: + run_dir = _make_run(tmp_path) + _onnx(run_dir).write_bytes(b"old onnx") + try: + assert main(_argv(tmp_path, "--overwrite")) == 0 + assert _onnx(run_dir).read_bytes() != b"old onnx" + assert _onnx(run_dir).stat().st_size > 1000 + assert _checkpoint_names(run_dir) == {"best.pth", "ResUNet.onnx"} + record = _strict_json(run_dir / "metrics.json")["export"] + assert record["file_bytes"] == _onnx(run_dir).stat().st_size + finally: + _close_own_handlers() + _onnx(run_dir).unlink(missing_ok=True) + + +# --------------------------------------------------------------------------- +# 確認を通らない(終了コード 3.slow) +# --------------------------------------------------------------------------- + + +def _force_check_failure(monkeypatch: pytest.MonkeyPatch) -> None: + original = export_cli.find_export_problems + + def failing(*args: Any, **kwargs: Any) -> list[str]: + kwargs["tolerance"] = -1.0 # 差 0 でも通らない + return original(*args, **kwargs) + + monkeypatch.setattr(export_cli, "find_export_problems", failing) + + +@pytest.mark.slow +def test_failed_check_exits_with_3_and_leaves_nothing( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + caplog: pytest.LogCaptureFixture, + capsys: pytest.CaptureFixture[str], +) -> None: + run_dir = _make_run(tmp_path) + metrics_before = (run_dir / "metrics.json").read_bytes() + _force_check_failure(monkeypatch) + try: + assert main(_argv(tmp_path)) == 3 + # ONNX(一時ファイルも)を置かず,metrics.json も変えない + assert _checkpoint_names(run_dir) == {"best.pth"} + assert (run_dir / "metrics.json").read_bytes() == metrics_before + assert "確認を通らなかった" in caplog.text + assert "絶対差" in caplog.text + assert str(_onnx(run_dir)) not in capsys.readouterr().out + log = _read_log(run_dir) + assert log.startswith(PREVIOUS_LOG_LINE + "\n") + assert "確認を通らなかった" in log + finally: + _close_own_handlers() + for path in (run_dir / "checkpoints").glob("*.onnx"): + path.unlink() + + +@pytest.mark.slow +def test_failed_check_with_overwrite_keeps_old_onnx( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + run_dir = _make_run(tmp_path) + _onnx(run_dir).write_bytes(b"old onnx") + metrics_before = (run_dir / "metrics.json").read_bytes() + _force_check_failure(monkeypatch) + try: + assert main(_argv(tmp_path, "--overwrite")) == 3 + assert _onnx(run_dir).read_bytes() == b"old onnx" + assert _checkpoint_names(run_dir) == {"best.pth", "ResUNet.onnx"} + assert (run_dir / "metrics.json").read_bytes() == metrics_before + finally: + _close_own_handlers() + for path in (run_dir / "checkpoints").glob("*.onnx"): + path.unlink() + + +@pytest.mark.slow +def test_unsupported_opset_exits_with_1_and_leaves_no_temp_file( + tmp_path: Path, caplog: pytest.LogCaptureFixture +) -> None: + # 設定の export.opset(7 以上で受け付ける)で書き出せない場合は設定の問題として 1 + run_dir = _make_run(tmp_path, config=_config(export={"opset": 10})) + metrics_before = (run_dir / "metrics.json").read_bytes() + try: + assert main(_argv(tmp_path)) == 1 + assert "opset 10" in caplog.text + assert _checkpoint_names(run_dir) == {"best.pth"} + assert (run_dir / "metrics.json").read_bytes() == metrics_before + finally: + _close_own_handlers() diff --git a/tests/export/test_check.py b/tests/export/test_check.py new file mode 100644 index 0000000..c5a734e --- /dev/null +++ b/tests/export/test_check.py @@ -0,0 +1,375 @@ +"""書き出した ONNX の確認の判定(`export/check.py`)のテスト. + +期待値は SPEC_02「ONNX の書き出し」の表(入力 `(1, 3, 256, 256)` float32・出力 +`(1, 2, 256, 256)` float32・opset 11)と,確認の項目(onnxruntime で読めること・入出力の形と型・ +PyTorch の出力との最大の絶対差を記録すること)を基準にする.すべて純関数なのでファイルを作らない. +""" + +from __future__ import annotations + +import json +import math +from pathlib import Path +from typing import Any + +import numpy as np +import pytest + +from tongue_seg_model.export.check import ( + CHECK_INPUT_SEED, + MAX_ABS_DIFF_TOLERANCE, + OnnxModelInfo, + TensorSpec, + build_export_record, + export_input_shape, + export_output_shape, + find_export_problems, + make_check_input, + max_abs_diff, +) +from tongue_seg_model.training.metrics import write_metrics_json + +IN_SHAPE = (1, 3, 256, 256) +OUT_SHAPE = (1, 2, 256, 256) + + +def _info( + *, + opset: int | None = 11, + inputs: tuple[TensorSpec, ...] | None = None, + outputs: tuple[TensorSpec, ...] | None = None, +) -> OnnxModelInfo: + return OnnxModelInfo( + opset=opset, + inputs=(TensorSpec("input.1", IN_SHAPE, "float32"),) if inputs is None else inputs, + outputs=(TensorSpec("269", OUT_SHAPE, "float32"),) if outputs is None else outputs, + ) + + +def _problems(info: OnnxModelInfo | None = None, **overrides: Any) -> list[str]: + kwargs: dict[str, Any] = { + "opset": 11, + "input_shape": IN_SHAPE, + "output_shape": OUT_SHAPE, + "runtime_output_shape": OUT_SHAPE, + "runtime_output_dtype": "float32", + "diff": 0.0, + } + kwargs.update(overrides) + return find_export_problems(_info() if info is None else info, **kwargs) + + +# --------------------------------------------------------------------------- +# 定数・形 +# --------------------------------------------------------------------------- + + +def test_tolerance_and_seed_constants() -> None: + assert MAX_ABS_DIFF_TOLERANCE == 1e-4 + assert CHECK_INPUT_SEED == 0 + + +class TestShapes: + def test_default_input_shape_matches_spec02(self) -> None: + assert export_input_shape((256, 256)) == IN_SHAPE + + def test_default_output_shape_matches_spec02(self) -> None: + assert export_output_shape((256, 256), 2) == OUT_SHAPE + + def test_height_then_width(self) -> None: + assert export_input_shape((64, 128)) == (1, 3, 64, 128) + assert export_output_shape((64, 128), 2) == (1, 2, 64, 128) + + def test_accepts_list(self) -> None: + assert export_input_shape([32, 64]) == (1, 3, 32, 64) + + def test_shape_values_are_python_ints(self) -> None: + shape = export_input_shape((np.int64(64), np.int64(64))) + assert all(type(v) is int for v in shape) + + +# --------------------------------------------------------------------------- +# 比較用の入力 +# --------------------------------------------------------------------------- + + +class TestMakeCheckInput: + def test_shape_and_dtype(self) -> None: + x = make_check_input(IN_SHAPE, 0) + assert x.shape == IN_SHAPE + assert x.dtype == np.float32 + + def test_values_in_unit_interval(self) -> None: + # 実際の入力(BGR を 255 で割った値)と同じ値域 + x = make_check_input((1, 3, 64, 64), 0) + assert float(x.min()) >= 0.0 + assert float(x.max()) < 1.0 + assert float(x.std()) > 0.1 # 定数ではない + + def test_same_seed_reproduces(self) -> None: + np.testing.assert_array_equal( + make_check_input((1, 3, 32, 32), 0), make_check_input((1, 3, 32, 32), 0) + ) + + def test_different_seed_differs(self) -> None: + assert not np.array_equal( + make_check_input((1, 3, 32, 32), 0), make_check_input((1, 3, 32, 32), 1) + ) + + def test_independent_of_global_random_state(self) -> None: + state = np.random.get_state() + try: + np.random.seed(123) + a = make_check_input((1, 3, 16, 16), CHECK_INPUT_SEED) + np.random.seed(456) + np.random.random(10) + b = make_check_input((1, 3, 16, 16), CHECK_INPUT_SEED) + finally: + np.random.set_state(state) + np.testing.assert_array_equal(a, b) + + def test_does_not_advance_global_random_state(self) -> None: + state = np.random.get_state() + try: + np.random.seed(7) + expected = np.random.random(3) + np.random.seed(7) + make_check_input((1, 3, 16, 16), 0) + np.testing.assert_array_equal(np.random.random(3), expected) + finally: + np.random.set_state(state) + + +# --------------------------------------------------------------------------- +# 最大の絶対差 +# --------------------------------------------------------------------------- + + +class TestMaxAbsDiff: + def test_identical_is_zero(self) -> None: + a = make_check_input((1, 2, 8, 8), 0) + assert max_abs_diff(a, a.copy()) == 0.0 + + def test_known_value(self) -> None: + a = np.array([[0.0, 1.0], [2.0, -3.0]], dtype=np.float32) + b = np.array([[0.5, 1.0], [2.0, -1.0]], dtype=np.float32) + assert max_abs_diff(a, b) == pytest.approx(2.0) + + def test_symmetric(self) -> None: + a = np.array([1.0, -2.0, 3.0], dtype=np.float32) + b = np.array([1.5, -2.25, 2.0], dtype=np.float32) + assert max_abs_diff(a, b) == max_abs_diff(b, a) == pytest.approx(1.0) + + def test_returns_python_float(self) -> None: + a = np.zeros((2, 2), dtype=np.float32) + assert type(max_abs_diff(a, a)) is float + + def test_small_float32_difference_is_not_lost(self) -> None: + a = np.array([1.0], dtype=np.float32) + b = np.nextafter(a, np.float32(2.0)) + assert max_abs_diff(a, b) == pytest.approx(float(b[0]) - 1.0) + assert max_abs_diff(a, b) > 0.0 + + def test_nan_propagates(self) -> None: + a = np.array([0.0, 1.0], dtype=np.float32) + b = np.array([0.0, np.nan], dtype=np.float32) + assert math.isnan(max_abs_diff(a, b)) + + def test_shape_mismatch_raises(self) -> None: + with pytest.raises(RuntimeError): + max_abs_diff(np.zeros((1, 2, 4, 4)), np.zeros((1, 2, 4, 5))) + + def test_empty_is_zero(self) -> None: + assert max_abs_diff(np.zeros((0, 2)), np.zeros((0, 2))) == 0.0 + + +# --------------------------------------------------------------------------- +# 問題の検出 +# --------------------------------------------------------------------------- + + +class TestFindExportProblems: + def test_spec_conforming_export_has_no_problems(self) -> None: + assert _problems() == [] + + def test_accepts_sequences_for_shapes(self) -> None: + assert ( + _problems( + input_shape=list(IN_SHAPE), + output_shape=list(OUT_SHAPE), + runtime_output_shape=list(OUT_SHAPE), + ) + == [] + ) + + @pytest.mark.parametrize("opset", [10, 12, 18, None]) + def test_opset_mismatch(self, opset: int | None) -> None: + problems = _problems(_info(opset=opset)) + assert len(problems) == 1 + assert "opset" in problems[0] + + def test_opset_compared_to_requested(self) -> None: + # 設定の export.opset を 13 にしたなら 13 が正しい + assert _problems(_info(opset=13), opset=13) == [] + assert len(_problems(_info(opset=11), opset=13)) == 1 + + @pytest.mark.parametrize("count", [0, 2]) + def test_input_count_must_be_one(self, count: int) -> None: + spec = TensorSpec("input.1", IN_SHAPE, "float32") + problems = _problems(_info(inputs=(spec,) * count)) + assert len(problems) == 1 + assert "入力" in problems[0] + + @pytest.mark.parametrize("count", [0, 2]) + def test_output_count_must_be_one(self, count: int) -> None: + spec = TensorSpec("269", OUT_SHAPE, "float32") + problems = _problems(_info(outputs=(spec,) * count)) + assert len(problems) == 1 + assert "出力" in problems[0] + + @pytest.mark.parametrize( + "shape", + [ + (1, 3, 256, 255), + (2, 3, 256, 256), + (1, 1, 256, 256), + (3, 256, 256), + ("batch", 3, 256, 256), + (1, 3, "height", "width"), + ], + ) + def test_input_shape_mismatch(self, shape: tuple[int | str, ...]) -> None: + problems = _problems(_info(inputs=(TensorSpec("input.1", shape, "float32"),))) + assert len(problems) == 1 + assert "入力の形" in problems[0] + + @pytest.mark.parametrize( + "shape", [(1, 1, 256, 256), (1, 2, 128, 128), ("batch", 2, 256, 256), (1, 2, 256)] + ) + def test_output_shape_mismatch(self, shape: tuple[int | str, ...]) -> None: + problems = _problems(_info(outputs=(TensorSpec("269", shape, "float32"),))) + assert len(problems) == 1 + assert "出力の形" in problems[0] + + @pytest.mark.parametrize("dtype", ["float64", "float16", "uint8", "onnx:16"]) + def test_input_dtype_mismatch(self, dtype: str) -> None: + problems = _problems(_info(inputs=(TensorSpec("input.1", IN_SHAPE, dtype),))) + assert len(problems) == 1 + assert "入力の型" in problems[0] + + @pytest.mark.parametrize("dtype", ["float64", "float16", "int64"]) + def test_output_dtype_mismatch(self, dtype: str) -> None: + problems = _problems(_info(outputs=(TensorSpec("269", OUT_SHAPE, dtype),))) + assert len(problems) == 1 + assert "出力の型" in problems[0] + + def test_shape_and_dtype_both_reported(self) -> None: + problems = _problems(_info(inputs=(TensorSpec("input.1", (1, 3, 8, 8), "float64"),))) + assert len(problems) == 2 + + def test_names_are_not_checked(self) -> None: + # SPEC_02: 入出力の名前は記録するが合わせ込みはしない(名前の違いは問題にしない) + info = _info( + inputs=(TensorSpec("x", IN_SHAPE, "float32"),), + outputs=(TensorSpec("conv2d_32", OUT_SHAPE, "float32"),), + ) + assert _problems(info) == [] + + def test_runtime_output_shape_mismatch(self) -> None: + problems = _problems(runtime_output_shape=(1, 2, 128, 128)) + assert len(problems) == 1 + assert "onnxruntime" in problems[0] + + def test_runtime_output_dtype_mismatch(self) -> None: + problems = _problems(runtime_output_dtype="float64") + assert len(problems) == 1 + assert "onnxruntime" in problems[0] + + def test_diff_equal_to_tolerance_is_ok(self) -> None: + assert _problems(diff=MAX_ABS_DIFF_TOLERANCE) == [] + + def test_diff_just_above_tolerance_is_problem(self) -> None: + above = float(np.nextafter(MAX_ABS_DIFF_TOLERANCE, 1.0)) + problems = _problems(diff=above) + assert len(problems) == 1 + assert "絶対差" in problems[0] + + def test_typical_float32_rounding_is_ok(self) -> None: + # 実測の差(4.77e-07)程度は通ること + assert _problems(diff=4.77e-07) == [] + + @pytest.mark.parametrize("diff", [math.nan, math.inf, 1.0, 1e-3]) + def test_large_or_nan_diff_is_problem(self, diff: float) -> None: + problems = _problems(diff=diff) + assert len(problems) == 1 + assert "絶対差" in problems[0] + + def test_default_tolerance_is_constant(self) -> None: + assert _problems(diff=MAX_ABS_DIFF_TOLERANCE * 1.5) != [] + assert _problems(diff=MAX_ABS_DIFF_TOLERANCE * 0.5) == [] + + def test_custom_tolerance(self) -> None: + assert _problems(diff=0.01, tolerance=0.1) == [] + assert len(_problems(diff=0.2, tolerance=0.1)) == 1 + + def test_negative_tolerance_rejects_even_zero_diff(self) -> None: + assert len(_problems(diff=0.0, tolerance=-1.0)) == 1 + + def test_all_problems_reported_together(self) -> None: + info = OnnxModelInfo(opset=9, inputs=(), outputs=()) + problems = _problems( + info, + runtime_output_shape=(1, 1, 8, 8), + runtime_output_dtype="float64", + diff=math.nan, + ) + assert len(problems) == 6 + + +# --------------------------------------------------------------------------- +# 書き出しの記録 +# --------------------------------------------------------------------------- + + +def _record(**overrides: Any) -> dict[str, Any]: + kwargs: dict[str, Any] = { + "onnx_file": "checkpoints/ResUNet.onnx", + "exporter": "torchscript", + "torch_version": "2.15.0", + "check_input_seed": 0, + "diff": 4.77e-07, + "tolerance": MAX_ABS_DIFF_TOLERANCE, + "file_bytes": 71_000_000, + "elapsed_seconds": 2.5, + } + kwargs.update(overrides) + return build_export_record(_info(), **kwargs) + + +class TestBuildExportRecord: + def test_contents(self) -> None: + assert _record() == { + "onnx_file": "checkpoints/ResUNet.onnx", + "exporter": "torchscript", + "torch_version": "2.15.0", + "opset": 11, + "inputs": [{"name": "input.1", "shape": [1, 3, 256, 256], "dtype": "float32"}], + "outputs": [{"name": "269", "shape": [1, 2, 256, 256], "dtype": "float32"}], + "check_input_seed": 0, + "max_abs_diff": 4.77e-07, + "tolerance": MAX_ABS_DIFF_TOLERANCE, + "file_bytes": 71_000_000, + "elapsed_seconds": 2.5, + } + + def test_tensor_spec_to_dict_keeps_dim_names(self) -> None: + spec = TensorSpec("x", ("batch", 3, 64, 64), "float32") + assert spec.to_dict() == {"name": "x", "shape": ["batch", 3, 64, 64], "dtype": "float32"} + + def test_written_as_strict_json(self, tmp_path: Path) -> None: + path = write_metrics_json(tmp_path / "metrics.json", {"export": _record()}) + assert json.loads(path.read_text(encoding="utf-8"))["export"] == _record() + + def test_nan_diff_is_written_as_null(self, tmp_path: Path) -> None: + path = write_metrics_json(tmp_path / "metrics.json", {"export": _record(diff=math.nan)}) + assert json.loads(path.read_text(encoding="utf-8"))["export"]["max_abs_diff"] is None diff --git a/tests/export/test_onnx_export.py b/tests/export/test_onnx_export.py new file mode 100644 index 0000000..2a91b23 --- /dev/null +++ b/tests/export/test_onnx_export.py @@ -0,0 +1,268 @@ +"""ONNX の書き出しと読み込み・推論(`export/onnx_export.py`)のテスト. + +期待値は SPEC_02「ONNX の書き出し」(原本と同じ条件: 入力 `(1, 3, 256, 256)` float32 → 出力 +`(1, 2, 256, 256)` float32・推論モード・opset 11.onnxruntime(CPU)で読めること・PyTorch の +出力との差が小さいこと)と `.claude/rules/testing.md` の必須対象 9 を基準にする. + +実際に ResUNet を書き出すテストは `slow`(1 回だけ書き出して module スコープで共有する). +`read_onnx_info`・`run_onnxruntime` の細かい場合分けは,onnx.helper で作る小さなグラフで確かめる. +""" + +from __future__ import annotations + +from collections.abc import Iterator +from dataclasses import dataclass +from pathlib import Path + +import numpy as np +import onnx +import pytest +import torch +from onnx import TensorProto, helper + +from tongue_seg_model.export.check import ( + CHECK_INPUT_SEED, + MAX_ABS_DIFF_TOLERANCE, + OnnxModelInfo, + TensorSpec, + export_input_shape, + export_output_shape, + find_export_problems, + make_check_input, + max_abs_diff, +) +from tongue_seg_model.export.onnx_export import ( + ONNX_FILENAME, + export_to_onnx, + read_onnx_info, + run_onnxruntime, + run_pytorch, +) +from tongue_seg_model.models.resunet import ResUNet + + +def test_onnx_filename_is_same_as_original() -> None: + assert ONNX_FILENAME == "ResUNet.onnx" + + +# --------------------------------------------------------------------------- +# 小さなグラフでの読み込み・推論 +# --------------------------------------------------------------------------- + + +def _save(model: onnx.ModelProto, path: Path) -> Path: + onnx.save(model, str(path)) + return path + + +def _identity_model( + *, + shape: list[int | str] | None = None, + opset_imports: list[onnx.OperatorSetIdProto] | None = None, + with_initializer_input: bool = False, + second_input: bool = False, +) -> onnx.ModelProto: + shape = [1, 3, 4, 4] if shape is None else shape + x = helper.make_tensor_value_info("x", TensorProto.FLOAT, shape) + y = helper.make_tensor_value_info("y", TensorProto.FLOAT, shape) + nodes = [helper.make_node("Identity", ["x"], ["y"])] + inputs = [x] + initializers = [] + if with_initializer_input: + # 古い書き出し方では重みもグラフの入力に並ぶ(重みは入力として数えない) + w = helper.make_tensor("w", TensorProto.FLOAT, [1], [0.0]) + initializers.append(w) + inputs.append(helper.make_tensor_value_info("w", TensorProto.FLOAT, [1])) + if second_input: + inputs.append(helper.make_tensor_value_info("z", TensorProto.FLOAT, shape)) + graph = helper.make_graph(nodes, "g", inputs, [y], initializer=initializers) + opsets = [helper.make_opsetid("", 11)] if opset_imports is None else opset_imports + model = helper.make_model(graph, opset_imports=opsets) + model.ir_version = 7 + return model + + +class TestReadOnnxInfo: + def test_reads_opset_inputs_outputs(self, tmp_path: Path) -> None: + path = _save(_identity_model(), tmp_path / "m.onnx") + assert read_onnx_info(path) == OnnxModelInfo( + opset=11, + inputs=(TensorSpec("x", (1, 3, 4, 4), "float32"),), + outputs=(TensorSpec("y", (1, 3, 4, 4), "float32"),), + ) + + def test_excludes_initializers_from_inputs(self, tmp_path: Path) -> None: + path = _save(_identity_model(with_initializer_input=True), tmp_path / "m.onnx") + info = read_onnx_info(path) + assert [spec.name for spec in info.inputs] == ["x"] + + def test_dynamic_dims_become_names(self, tmp_path: Path) -> None: + path = _save(_identity_model(shape=["batch", 3, 4, 4]), tmp_path / "m.onnx") + info = read_onnx_info(path) + assert info.inputs[0].shape == ("batch", 3, 4, 4) + + def test_reads_default_domain_opset_among_others(self, tmp_path: Path) -> None: + opsets = [helper.make_opsetid("com.example", 1), helper.make_opsetid("", 13)] + path = _save(_identity_model(opset_imports=opsets), tmp_path / "m.onnx") + assert read_onnx_info(path).opset == 13 + + def test_reads_ai_onnx_domain_name(self, tmp_path: Path) -> None: + path = _save( + _identity_model(opset_imports=[helper.make_opsetid("ai.onnx", 12)]), tmp_path / "m.onnx" + ) + assert read_onnx_info(path).opset == 12 + + def test_missing_file_is_value_error(self, tmp_path: Path) -> None: + with pytest.raises(ValueError): + read_onnx_info(tmp_path / "missing.onnx") + + def test_garbage_file_is_value_error(self, tmp_path: Path) -> None: + path = tmp_path / "bad.onnx" + path.write_bytes(b"this is not an onnx model\x00\xff" * 10) + with pytest.raises(ValueError): + read_onnx_info(path) + + def test_model_failing_checker_is_value_error(self, tmp_path: Path) -> None: + model = _identity_model() + model.graph.node[0].input[0] = "undefined_tensor" + path = _save(model, tmp_path / "m.onnx") + with pytest.raises(ValueError): + read_onnx_info(path) + + +class TestRunOnnxruntime: + def test_runs_identity(self, tmp_path: Path) -> None: + path = _save(_identity_model(), tmp_path / "m.onnx") + x = make_check_input((1, 3, 4, 4), 0) + y = run_onnxruntime(path, x) + assert isinstance(y, np.ndarray) + np.testing.assert_array_equal(y, x) + + def test_two_inputs_is_value_error(self, tmp_path: Path) -> None: + path = _save(_identity_model(second_input=True), tmp_path / "m.onnx") + with pytest.raises(ValueError, match="入力"): + run_onnxruntime(path, make_check_input((1, 3, 4, 4), 0)) + + def test_wrong_input_shape_is_value_error(self, tmp_path: Path) -> None: + path = _save(_identity_model(), tmp_path / "m.onnx") + with pytest.raises(ValueError): + run_onnxruntime(path, make_check_input((1, 3, 8, 8), 0)) + + def test_garbage_file_is_value_error(self, tmp_path: Path) -> None: + path = tmp_path / "bad.onnx" + path.write_bytes(b"not onnx" * 10) + with pytest.raises(ValueError): + run_onnxruntime(path, make_check_input((1, 3, 4, 4), 0)) + + def test_missing_file_is_value_error(self, tmp_path: Path) -> None: + with pytest.raises(ValueError): + run_onnxruntime(tmp_path / "missing.onnx", make_check_input((1, 3, 4, 4), 0)) + + +# --------------------------------------------------------------------------- +# ResUNet の書き出し(slow) +# --------------------------------------------------------------------------- + +SIZE = (256, 256) + + +@dataclass(frozen=True) +class Exported: + model: ResUNet + path: Path + warnings: list[str] + + +@pytest.fixture(scope="module") +def exported(tmp_path_factory: pytest.TempPathFactory) -> Iterator[Exported]: + """乱数の重みの ResUNet を 256×256・opset 11 で 1 回書き出す(このモジュールで共有する).""" + torch.manual_seed(0) + model = ResUNet(pretrained=False) + path = tmp_path_factory.mktemp("onnx") / ONNX_FILENAME + warnings = export_to_onnx(model, path, input_shape=export_input_shape(SIZE), opset=11) + try: + yield Exported(model=model, path=path, warnings=warnings) + finally: + path.unlink(missing_ok=True) # 約 70MB のファイルを残さない + + +@pytest.mark.slow +class TestExportResUNet: + def test_file_is_written(self, exported: Exported) -> None: + assert exported.path.is_file() + assert exported.path.stat().st_size > 0 + + def test_model_is_left_in_eval_mode(self, exported: Exported) -> None: + assert not exported.model.training + + def test_warnings_are_returned_as_strings(self, exported: Exported) -> None: + assert all(isinstance(message, str) for message in exported.warnings) + + def test_opset_is_11(self, exported: Exported) -> None: + assert read_onnx_info(exported.path).opset == 11 + + def test_input_and_output_match_spec02(self, exported: Exported) -> None: + info = read_onnx_info(exported.path) + assert len(info.inputs) == 1 + assert len(info.outputs) == 1 + assert info.inputs[0].shape == (1, 3, 256, 256) + assert info.inputs[0].elem_type == "float32" + assert info.outputs[0].shape == (1, 2, 256, 256) + assert info.outputs[0].elem_type == "float32" + + def test_onnxruntime_output_matches_pytorch(self, exported: Exported) -> None: + x = make_check_input(export_input_shape(SIZE), CHECK_INPUT_SEED) + expected = run_pytorch(exported.model, x) + actual = run_onnxruntime(exported.path, x) + assert expected.shape == (1, 2, 256, 256) + assert actual.shape == (1, 2, 256, 256) + assert actual.dtype == np.float32 + assert max_abs_diff(expected, actual) <= MAX_ABS_DIFF_TOLERANCE + + def test_output_is_raw_logits_not_activated(self, exported: Exported) -> None: + # 出力は活性化関数を掛ける前の値(0〜1 に収まるとは限らない.シグモイドの値でない) + x = make_check_input(export_input_shape(SIZE), CHECK_INPUT_SEED) + actual = run_onnxruntime(exported.path, x) + with torch.no_grad(): + expected = exported.model(torch.from_numpy(x)).numpy() + np.testing.assert_allclose(actual, expected, atol=MAX_ABS_DIFF_TOLERANCE, rtol=0) + + def test_no_problems_found(self, exported: Exported) -> None: + x = make_check_input(export_input_shape(SIZE), CHECK_INPUT_SEED) + expected = run_pytorch(exported.model, x) + actual = run_onnxruntime(exported.path, x) + problems = find_export_problems( + read_onnx_info(exported.path), + opset=11, + input_shape=export_input_shape(SIZE), + output_shape=export_output_shape(SIZE, 2), + runtime_output_shape=actual.shape, + runtime_output_dtype=actual.dtype.name, + diff=max_abs_diff(expected, actual), + ) + assert problems == [] + + +def test_run_pytorch_uses_eval_mode() -> None: + # 推論モード(BatchNorm が移動平均を使う).同じ入力の 2 回の結果が一致し,学習モードと異なる + torch.manual_seed(0) + model = ResUNet(pretrained=False) + model.train() + x = make_check_input((1, 3, 64, 64), 0) + first = run_pytorch(model, x) + assert not model.training + assert first.shape == (1, 2, 64, 64) + assert first.dtype == np.float32 + np.testing.assert_array_equal(first, run_pytorch(model, x)) + model.eval() + with torch.no_grad(): + np.testing.assert_array_equal(first, model(torch.from_numpy(x)).numpy()) + + +@pytest.mark.slow +def test_unsupported_opset_is_value_error(tmp_path: Path) -> None: + # ResUNet の bilinear(align_corners=True)の拡大は opset 11 より前では書き出せない + path = tmp_path / ONNX_FILENAME + with pytest.raises(ValueError, match="opset 10"): + export_to_onnx(ResUNet(pretrained=False), path, input_shape=(1, 3, 64, 64), opset=10) + assert not path.exists() diff --git a/tests/test_schema.py b/tests/test_schema.py index 5963315..c5aeb5f 100644 --- a/tests/test_schema.py +++ b/tests/test_schema.py @@ -162,6 +162,9 @@ pytest.param({"data": {"bundle": {"name": "a", "version": "1"}}}, id="bundle-version-str"), pytest.param({"data": {"bundle": {"name": "", "version": 1}}}, id="bundle-name-empty"), pytest.param({"data": {"bundle": {"name": "../x", "version": 1}}}, id="bundle-name-path"), + pytest.param( + {"data": {"bundle": {"name": "a\n", "version": 1}}}, id="bundle-name-trailing-newline" + ), pytest.param(_with("data", {"image_size": [0, 256]}), id="image-size-0"), pytest.param(_with("data", {"image_size": [256]}), id="image-size-1d"), pytest.param(_with("data", {"image_size": [256, 256, 3]}), id="image-size-3d"), @@ -202,6 +205,7 @@ pytest.param(_with("train", {"num_workers": -1}), id="num-workers-negative"), pytest.param(_with("train", {"device": "gpu"}), id="device-unknown"), pytest.param(_with("train", {"device": "cuda:"}), id="device-cuda-colon"), + pytest.param(_with("train", {"device": "cpu\n"}), id="device-trailing-newline"), # export pytest.param(_with("export", {"opset": 6}), id="opset-too-old"), pytest.param(_with("export", {"opset": "11"}), id="opset-str"), diff --git a/tests/training/test_run_artifacts.py b/tests/training/test_run_artifacts.py index 4ed6e06..31d4209 100644 --- a/tests/training/test_run_artifacts.py +++ b/tests/training/test_run_artifacts.py @@ -12,6 +12,7 @@ from pathlib import Path from typing import Any +import pydantic import pytest import yaml @@ -27,8 +28,11 @@ build_config_document, configure_logging, create_run_dir, + load_run_config, make_run_id, resolve_git_commit, + resolve_run_dir, + validate_run_id, write_config_yaml, ) @@ -148,6 +152,13 @@ with pytest.raises(ValueError): make_run_id(datetime(2026, 1, 1), "resunet", commit) + @pytest.mark.parametrize( + ("name", "commit"), [("resunet\n", "abc1234"), ("resunet", "abc1234\n")] + ) + def test_rejects_trailing_newline(self, name: str, commit: str) -> None: + with pytest.raises(ValueError): + make_run_id(datetime(2026, 1, 1), name, commit) + # --------------------------------------------------------------------------- # create_run_dir @@ -202,6 +213,7 @@ ("a", 1, SHA[:-1]), ("a", 1, SHA.upper()), ("a", 1, "g" * 64), + ("a", 1, SHA + "\n"), ], ) def test_rejects_invalid_values(self, name: str, version: Any, sha: str) -> None: @@ -358,3 +370,165 @@ for h in _own_handlers(): h.flush() assert "suppressed-info" not in (tmp_path / "log.txt").read_text(encoding="utf-8") + + +# --------------------------------------------------------------------------- +# 外から受け取った実験 ID の検証・実験ディレクトリの解決・設定の読み戻し(tsm-export の入口) +# --------------------------------------------------------------------------- + +VALID_RUN_ID = "20261119-102030_synthetic_abc1234-dirty" + + +class TestValidateRunId: + @pytest.mark.parametrize( + "run_id", + [ + VALID_RUN_ID, + "20261119-115704_synthetic_nogit", + "20260101-000000_resunet.v2_0123abc", + "20260101-000000_a_b", + ], + ) + def test_accepts_ids_made_by_make_run_id(self, run_id: str) -> None: + assert validate_run_id(run_id) == run_id + + def test_round_trips_make_run_id(self) -> None: + run_id = make_run_id(datetime(2026, 11, 19, 10, 20, 30), "synthetic", "abc1234-dirty") + assert validate_run_id(run_id) == run_id + + @pytest.mark.parametrize( + "run_id", + [ + "", + "..", + ".", + "../20261119-102030_synthetic_abc1234", + "20261119-102030_synthetic_abc1234/..", + "20261119-102030_synthetic_abc1234/../x", + "20261119-102030_synthetic_abc1234\\..", + "..\\20261119-102030_synthetic_abc1234", + "20261119-102030_../_abc1234", + "20261119-102030_.._abc1234", + "20261119-102030_a/b_abc1234", + "20261119-102030_a\\b_abc1234", + "20261119-102030_synthetic_abc1234\n", + "\n20261119-102030_synthetic_abc1234", + "20261119-102030_synthetic_abc1234 ", + " 20261119-102030_synthetic_abc1234", + "20261119-102030_synthetic_abc1234\x00", + "C:\\20261119-102030_synthetic_abc1234", + "/20261119-102030_synthetic_abc1234", + "20261119-102030_synthetic", + "2026111-102030_synthetic_abc1234", + "20261119102030_synthetic_abc1234", + "20261119-102030__abc1234", + "20261119-102030_synthetic_", + "20261119-102030_synthetic_.abc", + "20261119-102030_-synthetic_abc1234", + "20261119-102030_synthetic_abc.1234", + ], + ) + def test_rejects_ids_that_are_not_run_ids(self, run_id: str) -> None: + with pytest.raises(ValueError, match="実験 ID"): + validate_run_id(run_id) + + def test_rejects_too_long_parts(self) -> None: + with pytest.raises(ValueError): + validate_run_id("20261119-102030_" + "a" * 65 + "_abc1234") + with pytest.raises(ValueError): + validate_run_id("20261119-102030_synthetic_" + "a" * 65) + + def test_accepts_64_char_parts(self) -> None: + run_id = "20261119-102030_" + "a" * 64 + "_" + "b" * 64 + assert validate_run_id(run_id) == run_id + + +class TestResolveRunDir: + def test_returns_existing_run_dir(self, tmp_path: Path) -> None: + run_dir = create_run_dir(tmp_path, VALID_RUN_ID) + assert resolve_run_dir(tmp_path, VALID_RUN_ID) == run_dir + + def test_missing_run_dir_is_value_error(self, tmp_path: Path) -> None: + with pytest.raises(ValueError, match="実験ディレクトリが無い"): + resolve_run_dir(tmp_path, VALID_RUN_ID) + + def test_file_instead_of_dir_is_value_error(self, tmp_path: Path) -> None: + (tmp_path / VALID_RUN_ID).write_text("x", encoding="utf-8") + with pytest.raises(ValueError, match="実験ディレクトリが無い"): + resolve_run_dir(tmp_path, VALID_RUN_ID) + + @pytest.mark.parametrize("run_id", ["..", ".", "../outside", "sub/..", "", "x\\..\\.."]) + def test_cannot_point_outside_out_dir(self, tmp_path: Path, run_id: str) -> None: + # 親・自分自身は実在するディレクトリだが,形式で止まること + out_dir = tmp_path / "runs" + out_dir.mkdir() + (tmp_path / "outside").mkdir() + (out_dir / "sub").mkdir() + with pytest.raises(ValueError, match="実験 ID"): + resolve_run_dir(out_dir, run_id) + + def test_existing_dir_with_trailing_newline_name_is_not_resolved(self, tmp_path: Path) -> None: + # 改行付きの ID は形式で止まる(`$` の末尾改行の抜け道が無いこと) + create_run_dir(tmp_path, VALID_RUN_ID) + with pytest.raises(ValueError, match="実験 ID"): + resolve_run_dir(tmp_path, VALID_RUN_ID + "\n") + + +class TestLoadRunConfig: + def test_round_trips_written_config(self, tmp_path: Path) -> None: + config = _config( + data={"bundle": {"name": "synthetic", "version": 3}, "image_size": [64, 96]}, + export={"opset": 13}, + ) + write_config_yaml( + tmp_path, build_config_document(config, run_id=VALID_RUN_ID, git_commit="abc1234") + ) + loaded = load_run_config(tmp_path) + assert isinstance(loaded, ExperimentConfig) + assert loaded == config + assert loaded.export.opset == 13 + assert tuple(loaded.data.image_size) == (64, 96) + + def test_missing_config_yaml_is_value_error(self, tmp_path: Path) -> None: + with pytest.raises(ValueError, match=CONFIG_FILENAME): + load_run_config(tmp_path) + + def test_broken_yaml_is_value_error(self, tmp_path: Path) -> None: + (tmp_path / CONFIG_FILENAME).write_text("config: [unclosed\n", encoding="utf-8") + with pytest.raises(ValueError, match=CONFIG_FILENAME): + load_run_config(tmp_path) + + def test_non_utf8_is_value_error(self, tmp_path: Path) -> None: + (tmp_path / CONFIG_FILENAME).write_bytes(b"config: \xff\xfe\x80\n") + with pytest.raises(ValueError, match=CONFIG_FILENAME): + load_run_config(tmp_path) + + @pytest.mark.parametrize( + "text", + ["", "- a\n- b\n", "run: {id: x}\n", "config: null\n", "config: [1, 2]\n", "config: 3\n"], + ) + def test_document_without_config_mapping_is_value_error( + self, tmp_path: Path, text: str + ) -> None: + (tmp_path / CONFIG_FILENAME).write_text(text, encoding="utf-8") + with pytest.raises(ValueError, match="config"): + load_run_config(tmp_path) + + def test_invalid_config_content_is_validation_error(self, tmp_path: Path) -> None: + document = build_config_document(_config(), run_id=VALID_RUN_ID, git_commit="abc1234") + document["config"]["export"]["opset"] = 6 # 7 以上のはず + write_config_yaml(tmp_path, document) + with pytest.raises(pydantic.ValidationError): + load_run_config(tmp_path) + + def test_unknown_key_is_validation_error(self, tmp_path: Path) -> None: + document = build_config_document(_config(), run_id=VALID_RUN_ID, git_commit="abc1234") + document["config"]["unknown"] = 1 + write_config_yaml(tmp_path, document) + with pytest.raises(pydantic.ValidationError): + load_run_config(tmp_path) + + def test_config_dir_instead_of_file_is_value_error(self, tmp_path: Path) -> None: + (tmp_path / CONFIG_FILENAME).mkdir() + with pytest.raises(ValueError, match=CONFIG_FILENAME): + load_run_config(tmp_path)