ルータをバージョン管理し、人への引き継ぎを監視し、人にフォールバックする
読了まで約38 分分、8 節 節の 4 例 例。
この章を終えると、次のことができるようになる。ルータを、その回答を生み出す各部分によって名付けること。ルートが読み込む前にそれらの部分を検査すること。メッセージの各ウィンドウについて、明示したベースラインに対する引き継ぎ率を数えること。引き継がれた各メッセージがどこへ行くかを示すこと。
第8章ではルータをルートの背後に置いた。各回答には、メッセージを人に送るためのチームまたはフラグが付いている。銀行のサポートメッセージを何か月も受け付けるルートでは、ルートだけでは答えられない三つの問いが生じる。どのモデルが回答しているのか。そのファイルは検査済みのものか。引き継がれるメッセージは増えているのか、減っているのか。この章では、各問いに一つの制御と出力される一つの件数を対応させる。これらの制御は本書で独自に用意したものである。
この章で扱うのは、自前のモデルを運用することで加わる事柄、すなわちバージョン、人へのフォールバック、再学習である。ダッシュボード、ログ、アラートを含むサービス一般の監視は、本番監視を扱う書籍が扱う範囲であり、この章では繰り返さない。
ルーターをその構成要素で名付ける
ルーターはモデルだけではない。ベースモデル、そのベース上で学習したアダプター、メッセージを人に回すしきい値、そしてアダプターを生み出したデータとレシピからなる。このうちどれか一つでも異なる二つのルーターは、同じメッセージに対して異なる応答を返すことがある。「ルーター」とだけ書いたログの行では、両者を区別できない。
アダプターのファイルにはベースモデルが含まれない。PEFT checkpoint guideによれば、保存される重みはアダプターモジュールのパラメーターだけであり、ベースのものは何も含まれない。したがってアダプターは、学習に用いたベースを名指しする必要があり、その名指しは正確でなければならない。本書では、ベースをそのコミットで指定する。これが examples/models.toml にあるピンである。短いコミットハッシュでは使えないためだ。Hugging Face download guide, at v2.4.0は、コミットを指定する場合には常に完全な長さのハッシュを要求している。リビジョンを指定しなければ、ダウンロードされるのは main ブランチの内容である。ブランチ名はブランチとともに動くため、ピンではない。第5章では、ベースのリビジョンを、しきい値、データのコミット、レシピのハッシュとともにアダプターのマニフェストに記録した。
バージョンは名前に書き込む。banking77-lora-v1 は、dev 分割に含まれない学習用の行で 1 エポック学習させた、記録済みの LoRA アダプターであり、バージョン 1 である。同じレシピをもう一度記録したものは v2 であり、独自の名前と独自のマニフェストを持つ。マニフェストには、独立したバージョンのフィールドはない。名前がバージョンである。第8章のルートは、アダプター名の接尾辞をバージョンとして報告する。banking77-lora-v1 の場合、その接尾辞は v1 である。第7章の int8 コピーは別のモデルである banking77-lora-v1-int8 であり、このルートはそれを提供しない。その接尾辞は int8 となり、バージョンを示さないため、名前で提供するコピーには、それ専用のバージョンのフィールドが必要になる。
最初の検査では、マニフェストを読み、そのベースのリビジョンをピンと比較する。出力では、まずアダプターの名前が表示され、続いて比較の結果が表示される。
1"""Show what the adapter check does before a route loads an adapter, and what it does to two edited copies.2The point rests on the "route may load" line and on the two "refused by make_app" lines."""3import os45os.environ["HF_HUB_OFFLINE"] = "1"6os.environ["TRANSFORMERS_OFFLINE"] = "1"7import tempfile # noqa: E4028import warnings # noqa: E4029from pathlib import Path # noqa: E4021011import torch # noqa: E4021213torch.set_num_threads(2)1415import router_lib # noqa: E4021617router_lib.setup_runtime()18RECORDED = router_lib.HERE / "data" / "recorded" / "lora-full"19# check_adapter hashes the manifest, the outputs and the LoRA settings; pinned is the manifest's digest matching its pin20manifest, s_ok, s_n, f_ok, f_n, pinned = router_lib.check_adapter(RECORDED)21# the base pin in models.toml, compared with the manifest's base revision22base = router_lib.pinned_revision(manifest["model"]) == manifest["model_version"]23print(f"adapter: {manifest['adapter']}")24print(f"base revision matches pin: {'yes' if base else 'no'}")25print(f"manifest matches pin: {'yes' if pinned else 'no'}")26print(f"settings matching: {s_ok}/{s_n}")27print(f"files matching: {f_ok}/{f_n}")28print("route may load: " + ("yes" if base and pinned and s_ok == s_n and f_ok == f_n else "no"))29with tempfile.TemporaryDirectory() as tmp:30 # changes a manifest field that is neither a LoRA setting nor an output file, so only the manifest digest sees it31 threshold = router_lib.edited_copy(RECORDED, Path(tmp) / "threshold", "manifest.json", "handoff_threshold", 0.0)32 # adds a key that LoraConfig does not know, to the config the settings are read from33 extra = router_lib.edited_copy(RECORDED, Path(tmp) / "extra", "adapter/adapter_config.json", "future_key", 1)34 for label, folder in [("threshold copy", threshold), ("extra-key copy", extra)]:35 _, s_ok, s_n, f_ok, f_n, pinned = router_lib.check_adapter(folder)36 print(f"{label}: manifest matches pin {'yes' if pinned else 'no'}, settings {s_ok}/{s_n}, files {f_ok}/{f_n}")37 print(f"{label} refused by make_app: {'yes' if router_lib.refused_by_make_app(folder) else 'no'}")38 with warnings.catch_warnings(record=True) as caught:39 warnings.simplefilter("always")40 router_lib.load_classifier(extra / "adapter")41 named = [w for w in caught if "future_key" in str(w.message)] # only the warning about the extra key42 print(f"warnings naming the extra key while PEFT loads the copy: {len(named)}")43 # the warning's first sentence: the text up to the first ". " in its message44 print(f"that warning: {named[0].category.__name__}: {str(named[0].message).split('. ')[0]}.")
python adapter-manifest-check.pyadapter: banking77-lora-v1
base revision matches pin: yes
manifest matches pin: yes
settings matching: 3/3
files matching: 3/3
route may load: yes
threshold copy: manifest matches pin no, settings 3/3, files 3/3
threshold copy refused by make_app: yes
extra-key copy: manifest matches pin yes, settings 3/3, files 2/3
extra-key copy refused by make_app: yes
warnings naming the extra key while PEFT loads the copy: 1
that warning: UserWarning: Unexpected keyword arguments ['future_key'] for class LoraConfig, these are ignored.
名前はバージョンを含んでおり(banking77-lora-v1)、ベースのリビジョンはピンと一致している(yes)。これらは、ファイルを一つも読まないうちに、読者がピンと照らして確認できる二つの要素である。
実践ルール: ルーターは、ベースのリビジョン、バージョンを名前に含むアダプターの名前、データのコミット、しきい値、レシピのハッシュの五つで名付け、ルートが提供する前にこの五つすべてをアダプターのマニフェストに書き込む。アダプターを読み込むたびに、マニフェストのベースのリビジョンを examples/models.toml のピンと比較する。ピンが動いていれば、ベースモデルが別物になったことを意味し、アダプターは提供の前に改めて検査を受ける必要がある。
アダプタのファイルをマニフェストと照合する
ロードはバージョンの検査ではない。PEFT checkpoint guideが述べているように、LoRA の設定の項目の大半はモデルのロードに必要ではないため、誰かが手で書き換えた設定でもロードは成功しうる。ロードが成功しても、そのアダプタが固定されたものであることは示されない。以下の余分なキーを持つコピーも、ロードは成功し、そのロードは余分なキーを名指しする警告を出す。ベースが一致しない場合は、調査用のプローブではロード時に state-dict エラーで失敗する。この例ではそのケースは出力しない。
そこで、この検査ではアダプタをマニフェストと照合する。照合は三つの部分からなる。まず manifest.json の SHA-256 を自ら計算し、examples/adapter-pins.json にあるそのアダプタ名に対して固定されたダイジェストと比較する。この固定は、しきい値、ベースのリビジョン、出力のダイジェストを含め、マニフェストが持つすべてのフィールドに及ぶ。次に、マニフェストが列挙する各出力ファイルの SHA-256 を計算し、マニフェストが記録しているダイジェストと比較する。さらに、設定にある三つの LoRA 設定、すなわちランク、スケーリングを決める alpha、対象レイヤーを読み取り、マニフェストと比較する。出力される行には、それぞれ何件が一致したか、およびルートがそのフォルダをロードしてよいかどうかが示される。
記録済みのアダプタでは、マニフェストは固定値と一致し(yes)、設定は 3/3、ファイルは 3/3 が一致するため、ルートはそれをロードしてよい。
この検査は編集した二つのコピーにも実行され、それぞれに専用の行が出力される。一つ目は、マニフェストの handoff_threshold を 0 に変更したもので、その行は manifest matches pin no, settings 3/3, files 3/3 である。しきい値は設定ではなく、出力ファイルも変更されていないため、設定とファイルは依然として一致する。変更を検知するのはマニフェスト自身のダイジェストだけであり、そのためこのコピーは拒否される。二つ目は、設定に余分なキーを一つ加えたもので、その行は manifest matches pin yes, settings 3/3, files 2/3 である。設定は依然として一致するが、設定ファイルのハッシュがもはや一致しないため、ファイルの検査で拒否される。PEFT はこのコピーをそれでもロードし、ロードが出す警告のうち 1 が余分なキーを名指しする。全文は次のとおりである。UserWarning: Unexpected keyword arguments ['future_key'] for class LoraConfig, these are ignored. ロードはそのキーを無視したモデルを返し、PEFT がそれについて述べるのはこの警告だけである。警告は拒否ではない。コピーを拒否するのは検査である。
第 8 章のルートはこの検査を実行する。その make_app は、モデルをロードする前に check_adapter を呼び出し、マニフェストのベースのリビジョンも固定値と比較する。不一致があればエラーを送出するため、検査に失敗したコピーはモデルがメモリに載る前に拒否される。しきい値のコピーは make_app によって拒否され(yes)、余分なキーを持つコピーも同様である(yes)。この検査はリポジトリを信頼する。固定されたダイジェストはコードと並んで examples/adapter-pins.json にあるため、フォルダだけを編集して固定ファイルを編集しない読者は拒否され、両方を編集する読者は拒否されない。したがって、固定ファイルは他のコードと同様にレビューする。
実践ルール: どのルートでも、アダプタをロードする前にこの検査を実行する。マニフェストの SHA-256 をコードとともに固定し、一致した設定とファイルを数え、各件数を総数とともに出力し、いずれかの件数が足りない場合、またはマニフェストのダイジェストが一致しない場合はロードを拒否する。ハッシュはディスク上のファイルから取り、検査とロードは同じファイルに対して行い、その間にそれらへ書き込むものがないようにする。
ハンドオフ率を監視する
ハンドオフ率とは、しきい値を下回ったメッセージの数を、ウィンドウ内の全メッセージ数で割った値である。第2章でこれを定義した。本章では、この値を時間の流れに沿って監視する。監視には三つのものが必要である。ウィンドウ、ベースライン、そしてウィンドウがベースラインから離れすぎたと判断するための規則である。
ベースラインは、アダプタのしきい値における dev 分割でのハンドオフ率である。dev_handed_offは、dev の全メッセージを一度ルーティングしてハンドオフの数を数えることでこれを計算し、その結果は148/1003 (14.8%)となる。第5章のしきい値の例も同じ数を出力しており、その値は148/1003 (14.8%)である。両者は一致しているので、このベースラインは、その章がしきい値を選んだときのものと同じである。
dev から得たベースラインは、受信箱に対する予測ではない。dev 分割は、訓練用の行からチームごとに抽出したものである。テスト標本は、テスト分割から抽出したものである。どちらも受信箱のトラフィックの標本ではなく、実際のメッセージにおけるチームの構成も分かっていない。したがって、ウィンドウとベースラインの差は、問いを立てるきっかけであり、それ自体が答えになるわけではない。
ドリフト規則は、出典にある数値ではなく、本書が選んだものである。ウィンドウのハンドオフ率がベースラインから、上下いずれの方向にも、定めた点数より大きく離れたとき、そのウィンドウはドリフトしているとする。出力された規則はmore than 10 points from the baselineである。監視を運用する者は、ウィンドウを読む前に、自分で数値を選んで書き留めておくべきである。
コミット済みのテスト標本test_1001には日付がないので、ウィンドウは先頭の100件のメッセージから切り出す。最初の二つのウィンドウは、それぞれ25件のメッセージからなり、標本の順序どおりの先頭のメッセージである。第3週と第4週はリプレイであり、新しいトラフィックではない。この2週間については、例は標本の次のメッセージを取り、ルーターの確信度が低い順から高い順に並べ替え、並べ替えた一覧を二つに分ける。例は、出力行のsimulated replay of sample messages 51 to 100でリプレイがシミュレーションであることを示している。リプレイは確信度に幅が出るように作られているので、偏ったウィンドウに対して規則がどう働くかを示す。ただし、ベースラインと同様に、受信箱については何も語らない。
1"""Watch the router's hand-off rate week by week on a fixed, ordered sample of test_1001, against the dev baseline.2The point rests on the "drift" lines and on the "lowest confidence" and "right" lines of weeks 3 and 4, which the output3labels as a simulated replay."""45import os67os.environ["HF_HUB_OFFLINE"] = "1"8os.environ["TRANSFORMERS_OFFLINE"] = "1"910import json # noqa: E4021112import torch # noqa: E4021314torch.set_num_threads(2)1516import router_lib # noqa: E4021718router_lib.setup_runtime()19RECORDED = router_lib.HERE / "data" / "recorded" / "lora-full"20# the threshold is read from the manifest, not typed here21threshold = json.loads((RECORDED / "manifest.json").read_text())["handoff_threshold"]22tokenizer, model = router_lib.load_classifier(RECORDED / "adapter")2324handed_dev, n_dev = router_lib.dev_handed_off(model, tokenizer, threshold)25base = 100 * handed_dev / n_dev26print(f"dev hand-off rate (baseline): {handed_dev}/{n_dev} ({base:.1f}%)")27print(f"drift rule: more than {router_lib.DRIFT_POINTS:.0f} points from the baseline")28print("weeks 3 and 4: simulated replay of sample messages 51 to 100")29test = router_lib.read_rows("test")30# simulated=True (the default) adds weeks 3 and 4: messages 51 to 100, lowest confidence first, ties by position31for w, (rows, preds, confs) in enumerate(router_lib.watch_weeks(model, tokenizer, threshold), 1):32 n = len(rows)33 handed = sum(router_lib.handoff(c, threshold) for c in confs)34 rate = 100 * handed / n35 # the messages the router keeps, each with its gold team: test row i holds (text, gold team)36 kept = [(p, test[i][1]) for i, p, c in zip(rows, preds, confs) if not router_lib.handoff(c, threshold)]37 right = sum(p == g for p, g in kept)38 print(f"week {w} messages: {n}")39 print(f"week {w} handed off: {handed}/{n} ({rate:.1f}%)")40 # abs makes the rule two-sided, so a fall in the rate drifts as a rise does41 print(f"week {w} drift: {'yes' if abs(rate - base) > router_lib.DRIFT_POINTS else 'no'}")42 print(f"week {w} lowest confidence: {min(confs):.3f}")43 print(f"week {w} right among messages not handed off: {right}/{len(kept)}")
python handoff-windows.pydev hand-off rate (baseline): 148/1003 (14.8%)
drift rule: more than 10 points from the baseline
weeks 3 and 4: simulated replay of sample messages 51 to 100
week 1 messages: 25
week 1 handed off: 6/25 (24.0%)
week 1 drift: no
week 1 lowest confidence: 0.479
week 1 right among messages not handed off: 17/19
week 2 messages: 25
week 2 handed off: 4/25 (16.0%)
week 2 drift: no
week 2 lowest confidence: 0.378
week 2 right among messages not handed off: 19/21
week 3 messages: 25
week 3 handed off: 9/25 (36.0%)
week 3 drift: yes
week 3 lowest confidence: 0.246
week 3 right among messages not handed off: 16/16
week 4 messages: 25
week 4 handed off: 0/25 (0.0%)
week 4 drift: yes
week 4 lowest confidence: 0.981
week 4 right among messages not handed off: 25/25
標本が小さいのでウィンドウも小さく、四つのウィンドウはそれぞれ25件のメッセージからなる。この大きさのウィンドウでは、1件のメッセージが率の4ポイントに当たるため、1件のメッセージでウィンドウが規則の境界を越えうる。実際の受信箱の監視では、1件のメッセージがフラグを左右しない程度に大きなウィンドウが必要である。ウィンドウの大きさは、ウィンドウを読む前に明示し、報告に記載すべきである。
第1週と第2週は規則の範囲内に収まり、リプレイは両方向にドリフトする。四つのウィンドウの結果は次のとおりで、それぞれに件数とフラグを付している。
- 第1週のハンドオフは6/25 (24.0%)で、ドリフトのフラグはnoである。
- 第2週のハンドオフは4/25 (16.0%)で、ドリフトのフラグはnoである。
- 第3週のハンドオフは9/25 (36.0%)で、ドリフトのフラグはyesである。
- 第4週のハンドオフは0/25 (0.0%)で、ドリフトのフラグはyesである。
第4週は、読者が注意深く見るべき事例である。この規則では、率がゼロまで下がることもドリフトになる。規則は、低下を上昇と同じように変化として扱うからである。率がゼロなのは、第4週の最低の確信度が0.981でしきい値を上回り、ウィンドウ内のどのメッセージもハンドオフされないからである。ルーターは、ハンドオフしなかったメッセージのうち25/25で正しかった。このウィンドウは、確信度が高く正しい回答からなるウィンドウであり、ドリフトのフラグが報告しているのはハンドオフ率が動いたことであって、ルーターが誤りを犯したことではない。
第3週は、もう一方の種類のウィンドウである。最低の確信度は0.246で、ハンドオフは9/25 (36.0%)に増え、ルーターは保持したメッセージのうち16/16で正しい。ハンドオフが増えるということは、より多くのメッセージが人の手に届くということである。それだけでは、増加の原因がメッセージの変化なのか、現れるチームの変化なのか、モデルの変化なのかは分からない。ルートの回答にはメッセージの記録が含まれないので、ルートはどれが原因かを答えられない。第8章も、ルートが返す率について同じことを述べている。
実践ルール: 同じ大きさの各ウィンドウでハンドオフを数え、各件数を分母とともに出力し、各率をアダプタのしきい値における dev のベースラインと比較する。ウィンドウを読む前にドリフト規則とその点数を定め、報告に書き込む。ドリフトしたウィンドウは、そのメッセージとチームを読む理由として扱い、ルーターに対する判定としては扱わない。
人に引き継いだメッセージの標本
引き継ぎの監視は、人に渡されるメッセージの件数を数える。しかし、この監視では二つの問いが未解決のまま残る。一つは、引き継いだメッセージについてルーターの判断が正しかったかどうかである。もう一つは、自分で処理を続けたメッセージについてルーターの判断が正しかったかどうかである。本節では、このうち前者にどう答えるかを述べる。これは次の段階の作業であり、本章では標本を抽出せず、ラベルも報告せず、そのための数値も示さない。
人が、固定したシードで抽出した引き継ぎメッセージの標本にラベルを付ける。ラベルは、人がそれぞれのメッセージに対して選ぶチームを表す。これをルーターのモデルが選んだはずのチームと突き合わせると、ルーターが判断に迷ったメッセージで両者がどのくらいの頻度で食い違うかが分かる。ルーターが迷うメッセージは、人が最も確認すべき判断にあたる。したがって、この標本を最初に抽出するのがよい。この標本を作る読者は、人のラベルの代わりに公開データセットの正解ラベルを使ってもよい。ただしその場合は、報告にその旨を記す必要がある。
引き継ぎメッセージの標本からは、ルーターが自分で処理を続けたメッセージでの成績は分からない。処理を続けたメッセージとは、経路が答えを返したメッセージのことであり、引き継ぎによって人に送られることはない。それらの正解率を推定できるのは、経路がすでに答えを返した後で、人がその一部も確認した場合に限られる。処理を続けたメッセージの確認は、同じ方法で抽出する二つ目の標本で行う。これは引き継ぎメッセージの標本の副産物ではない。指標は、第5章で定めたとおり、引き継がなかったメッセージでの正解率であり、その件数と分母を添えて示す。
実践ルール: 標本を作るときは、固定したシードで抽出し、ラベルを付けたメッセージの件数を出力し、ルーターのチームと人のチームが一致する頻度をその件数とともに報告する。処理を続けたメッセージの標本にも同じ日程でラベルを付け、処理を続けたメッセージでのルーターの正解率は、その標本からだけ読み取る。処理を続けたメッセージの率を、引き継ぎメッセージの標本から読み取ってはならない。
人に回す
第8章で構築したルートは、人に引き継がれたメッセージに対して、フラグを返し、チームは返さない。それでも、そのメッセージに対して何らかの処理は行わなければならない。この章の実践ルールは、引き継がれたメッセージは必ず人に回す、というものである。代役であるQwen3-4B-Instruct-2507の記録済みの回答は、代役のものであると明示したうえで、提案として引き継ぎメッセージに添えてよい。それを使うかどうかは人が決める。test_1001に対する代役の回答はstandin-baselineに記録されている(第2章)。引き継がれたメッセージに対して、ルーターのチームを返すことは決してない。
ルートのJSONにはteam、confidence、handed_off、adapter、versionがあり、誰が回答したかを示すフィールドはない。したがって、フォールバックの回答をこの形のまま送り出してはならない。レスポンスに提案を含めたい読者は、意図して独自のフィールドを追加し、そのフィールドが何であるかをレスポンスの中で明示する。
本書は、フォールバックとしてホスト型モデルを呼び出す方法を扱わず、代役に対するしきい値も設けない。代役の回答は記録されたものから得られ、フォールバックのスクリプトがそれを読み込む。このスクリプトは提案がどれだけの頻度で正しいかを測定するが、その測定値から何かを決定することはない。
1"""Hand each handed-off message to a person, with the stand-in's recorded answer as a labelled suggestion.2The point rests on the "team returned for a handed-off message" line and the "suggestions right" line."""34import os56os.environ["HF_HUB_OFFLINE"] = "1"7os.environ["TRANSFORMERS_OFFLINE"] = "1"89import json # noqa: E4021011import torch # noqa: E4021213torch.set_num_threads(2)1415import router_lib # noqa: E4021617router_lib.setup_runtime()18RECORDED = router_lib.HERE / "data" / "recorded" / "lora-full"19# the threshold is read from the manifest, not typed here20threshold = json.loads((RECORDED / "manifest.json").read_text())["handoff_threshold"]21tokenizer, model = router_lib.load_classifier(RECORDED / "adapter")22test = router_lib.read_rows("test")23standin = router_lib.standin_rows() # a dict from test row index to the stand-in's answer, for the rows it answered24rows, handed = [], []25# simulated=False keeps weeks 1 and 2 only: the replay belongs to the watch, not to this example26for weekly_rows, _, confs in router_lib.watch_weeks(model, tokenizer, threshold, simulated=False):27 rows += weekly_rows28 handed += [i for i, c in zip(weekly_rows, confs) if router_lib.handoff(c, threshold)]2930# the list of records stands in for the person's queue, which the book does not build31# the suggestion is None where the stand-in has no recorded answer, and the team is always None32queue = [{"index": i, "team": None, "suggestion": standin[i]["label"] if i in standin else None} for i in handed]33suggested = [r for r in queue if r["suggestion"] is not None]34right = sum(r["suggestion"] == test[r["index"]][1] for r in suggested) # index 1 of a test row is its gold team3536print(f"messages routed: {len(rows)}")37print(f"handed off by the router: {len(handed)}/{len(rows)} ({100 * len(handed) / len(rows):.1f}%)")38print(f"sent to a person: {len(queue)}/{len(handed)}")39print(f"suggestions attached: {len(suggested)}/{len(handed)}")40print(f"suggestions right: {right}/{len(suggested)}")41print(f"team returned for a handed-off message: {sum(r['team'] is not None for r in queue)}")
python fallback-to-larger-model.pymessages routed: 50
handed off by the router: 10/50 (20.0%)
sent to a person: 10/10
suggestions attached: 10/10
suggestions right: 4/10
team returned for a handed-off message: 0
この例では最初の二つのウィンドウをルーティングし、合計50件のメッセージのうち10/50 (20.0%)件がルーターによって引き継がれる。引き継がれたメッセージにはそれぞれ1件のレコードが作られ、出力では人に送られたレコードの数が数えられる。代役の記録済みの回答がある場合、レコードはそれを提案として保持する。レコードのうち10/10件が提案を持ち、引き継がれたメッセージに対して返されたチームの数は0である。レコードのリストは、人の待ち行列の代わりである。本書はその待ち行列を構築しない。構築する読者は、各レコードをそのメッセージと対応づけて保持するべきである。
提案を持つ引き継ぎメッセージのうち、提案が正しいのは4/10である。これは半数に満たず、提案を人に示すだけにとどめ、回答としては決して使わない理由である。フォールバックのスクリプトは、ルーターが自ら処理するメッセージについては代役を測定しない。この標本では引き継がれたメッセージのすべてが提案を持つが、受信箱全体についても同じだとは本章では主張しない。
実践ルール: 引き継がれたメッセージはそれぞれ人に送る。代役の記録済みの回答は、提案であると明示したうえで添えてよい。そのメッセージに対してチームを返してはならず、誰が回答したかを示すフィールドなしに、提案をルートのレスポンスの形に入れてはならない。読者が提案にどれだけの重みを置くかを決める前に、正しい提案の数を、その分母とともに数える。
この部分はまだ翻訳されていないため、英語で表示している。
Retrain on a trigger
A drifting window is a signal to look, and it does not on its own start a retraining. The book sets three triggers, and this section states each one. The first is drift, the rule in this chapter's watch applied to consecutive windows. The book retrains when two consecutive windows drift, a number no source gives, and you may choose another, provided you state it in advance. The second trigger is a team added to the 77 the router returns. The router has no training rows for it, and people's labels would show it as a team outside the 77. The third is a rise in wrong teams on messages the router keeps, confirmed in the kept-message sample from the previous section. It is not the sample of handed-off messages, whose teams are never returned, so wrong teams there are expected and do no harm. The retrain script below exercises only the first. The recorded data holds no added team and no person's labels, so the second and third are rules without a test here.
1"""Decide whether to retrain, as a rule over the weekly drift flags from handoff-windows. The rule is the book's choice,2not a sourced threshold: retrain when two consecutive weeks drift, that is, their hand-off rate is more than3router_lib.DRIFT_POINTS from the dev baseline. The point rests on the "retrain trigger" line."""45import os67os.environ["HF_HUB_OFFLINE"] = "1"8os.environ["TRANSFORMERS_OFFLINE"] = "1"910import json # noqa: E4021112import torch # noqa: E4021314torch.set_num_threads(2)1516import router_lib # noqa: E4021718router_lib.setup_runtime()19RECORDED = router_lib.HERE / "data" / "recorded" / "lora-full"20# the threshold is read from the manifest, not typed here21threshold = json.loads((RECORDED / "manifest.json").read_text())["handoff_threshold"]22tokenizer, model = router_lib.load_classifier(RECORDED / "adapter")23handed_dev, n_dev = router_lib.dev_handed_off(model, tokenizer, threshold)24base = 100 * handed_dev / n_dev2526drifting, run, longest = [], 0, 027# the default simulated=True: weeks 3 and 4 are the replay, the same four windows the watch reads28for rows, _, confs in router_lib.watch_weeks(model, tokenizer, threshold):29 rate = 100 * sum(router_lib.handoff(c, threshold) for c in confs) / len(rows)30 flag = abs(rate - base) > router_lib.DRIFT_POINTS # two-sided, as in the watch31 drifting.append(flag)32 run = run + 1 if flag else 033 longest = max(longest, run)34 print(f"week {len(drifting)} drift: {'yes' if flag else 'no'}")3536print(f"weeks drifting: {sum(drifting)}/{len(drifting)}")37print(f"longest run of drifting weeks: {longest}")38print("rule: retrain when two consecutive weeks drift")39print("retrain trigger: " + ("fired" if longest >= 2 else "not fired"))
python retrain-trigger.pyweek 1 drift: no
week 2 drift: no
week 3 drift: yes
week 4 drift: yes
weeks drifting: 2/4
longest run of drifting weeks: 2
rule: retrain when two consecutive weeks drift
retrain trigger: fired
The retrain script applies the drift rule to the same four windows as the watch, in order, and finds 2/4 windows that drift, with a longest run of 2. Weeks 3 and 4 drive that result, since they are the replay from the watch. The trigger fired because of how the replay was built, so the run shows the rule working as stated, not anything the inbox did.
When a retraining does start, it follows the same path as the first adapter. It is a recording in recordings/, as banking77-lora-v1 was, written by a script there, and it writes a manifest with the same fields. It is named as the next version of the same recipe, so the retrained adapter is v2. Its threshold is chosen again on the dev split by the rule in chapter 5, never on the test sample. The retrained folder then needs its manifest's digest added to examples/adapter-pins.json, as a change to the repository that someone reviews. Until then, make_app refuses to build the app from it. The old adapter stays in place until make_app builds an app from the new folder.
Working rule: Retrain when the trigger you stated is met, and not on one drifting window. Write the trigger, its number and the rule beside the windows that met it. A retrained adapter is a recording named as the next version, with its manifest digest pinned and its threshold chosen again on dev. Keep the previous adapter until the new one passes the check in make_app.
本番環境で起こりうる問題
- マニフェストが手作業で編集される。 マニフェストのダイジェストは固定されているため、検査はそのマニフェストを拒否する。リポジトリを信頼する検査を破るには、ピンのファイルも編集するしかない。そしてその変更は、誰かがレビューすることになる。
- ピンが動く。
examples/models.tomlのベースのピンは、マニフェストが古いリビジョンを指したままのアダプターの下で変わりうる。make_appは両者を比較し、ビルドを拒否する。 - フォールバックが誤ったスケールで振り分ける。 閾値に対して較正されたことのないモデルの確信度は、ゲートにならない。そのため本書のフォールバックは振り分けを行わず、提案は人間のメッセージに付随してのみ届く。
- ウィンドウが小さすぎる。 25 件のメッセージからなるウィンドウでは、1 件のメッセージが 4 ポイントに相当する。そのため、フラグは 1、2 件のメッセージを反映するにすぎず、それに基づいて行動した読み手は、ノイズに基づいて行動したことになる。
- 率が動くのに、その理由を説明するものがない。 このルートの回答にはメッセージの記録が残らない。したがって、率の動きは、メッセージとそのチームから答えを出すべき問いであり、本章が次のステップとして述べるサンプルを使って調べる。
最初の種類の失敗は、アプリのビルド時に気づく。拒否されたフォルダーは起動時にエラーを送出するため、起動時にアプリをビルドするデプロイでは、メッセージが一つも失敗しないうちに不正なフォルダーが見つかる。その他の失敗は、件数に表れる。引き継ぎ率の変動はウィンドウの件数に表れ、ドリフトルールがそれを報告する。誤ったメッセージに対して提案を出すフォールバックは提案の件数に表れ、残りは人間が付けたラベルのサンプルから分かる。
実践ルール: 各制御の件数は、起動時と各ウィンドウで読み手が見られる場所に出力し、失敗を明らかにしうる件数は、それが説明する率と同じレポートに載せる。
この部分はまだ翻訳されていないため、英語で表示している。
The decisions this chapter made
- A handed-off message always goes to a person. The stand-in's answer, when there is one, is a labelled suggestion, and the chapter counts how often it is right.
- The version check pins the SHA-256 of each adapter's
manifest.jsoninexamples/adapter-pins.json, andmake_apprefuses to build on any mismatch or a moved base pin. - The drift rule is 10 points from the dev baseline, in either direction, on windows of 25 messages.
- A retrain is due when two consecutive windows drift. The second and third triggers are stated rules, not tested here.
Chapter 10 uses the same measures as this chapter.
All four are the book's choices; see the drift rule. Together the controls check which model answers, count what it hands off and send each handed-off message to a person. The fallback rule follows the rule from chapter 1 that a flagged message goes to a person. The pin rule trades a review of the repository for a check that a load alone cannot make.
Working rule: Write each decision above into the report with its number and whether it is the book's choice or a sourced figure. Change a decision only by changing the rule it names, and rerun the examples that print its counts.
この版における本章
第2026.11.9版2026年11月20日時点で例が通過この章の4 例件のうち4件が合格
英語版の書籍(版2026.11.9)から翻訳した。