LoRAによる分類ヘッドのファインチューニング

読了まで約36 分分、6 節 節の 5 例 例。

第2026.11.9版 2026年11月20日時点で例が通過 36 例中 36 例が合格 変更点

AIによる翻訳。英語版は人による検証済みである。 当社の書籍の作り方

英語版の書籍(版2026.11.9)から翻訳した。 原文を読む

この章を終えると、ラベル付きメッセージを使って LoRA で分類ヘッドを学習し、学習によって変化するパラメータを数え、述べられた規則に従って dev 分割上で引き継ぎの閾値を選び、その閾値を、それが生んだ結果とともに記録できるようになる。

ここまでのルーターは、スタンドインを実行している。これは、ホスト型モデルの代わりに回答をテキストとして書き出すものである。その閾値は仮の値 0.5 であり、誰も選んでおらず、すべての出力が仮の値であると明示している。回答はチームでなければならず、閾値は選ばれなければならない。そこで本章では、その回答を、チームと確信度を 1 回の順伝播で返すヘッドに置き換え、テスト結果を報告する前に dev 上で閾値を選ぶ。学習には、ルーターの各チームに対応するラベル付きメッセージが必要であり、これには公開データセットである BANKING77 を用いる。第 3 章では基盤モデルとして SmolLM2-135M-Instruct を選んだ。本章ではこのモデルだけをファインチューニングし、他のモデルは扱わない。第 3 章で述べたとおり、360M は比較用にとどめる。ルーターの評価には、第 2 章で固定したサンプルを用いる。

本章では、アダプターと 360M の比較は行わず、蒸留も量子化も行わない。アダプターの蒸留、量子化、バージョン管理は、第 6 章、第 7 章、第 9 章で扱う。

チームを採点するヘッド

最終変更:版2026.11.9

代役モデルは回答をテキストとして書き出し、デコード中は文法がそのテキストを77のチーム名に制限する(第4章)。分類ヘッドは代役モデルとは異なる仕組みで動く。言語モデルの層はそのまま残し、77個の出力を持つ出力層を1つ加える。出力の1つ1つが各チームに対応する。メッセージごとに、モデルは77個のスコアを出す。softmax はそのスコアを、合計が1になる77個の確率に変換する。ルーターは確率が最も高いチームを返し、確信度はその確率である。

回答は77のチームに対する添字であるから、必ずそのいずれかになる。第4章では、プロンプトで動かすモデルについて、そのテキストを制約することで同じ保証を得る。このヘッドはテキストを書かないので、制約すべきものがない。

メッセージ1件の処理にかかるのは順伝播1回である。これは入力からスコアまでネットワークを1回走らせることを指し、トークンを1つずつ書き出すループは含まない。チームと確信度は、この同じ1回の処理から得られる。この点は人への引き継ぎにとって重要である。メッセージを人に回すかどうかのフラグは、それが保護するチームと同じ確率から計算される。そのため、2回の呼び出しの間で両者がずれることはない。別個に採点を呼び出す方式であれば、両者が一致していることを確かめる検査が別に必要になる。

ここでの確信度は、代役モデルの場合より意味が狭い。第1章では、確信度は代役モデルが記録した回答の持つ確率であり、チームに対する softmax ではなかった。この章での確信度は、選ばれたチームの softmax 確率である。2つの数値はどちらも確信度と呼ばれ、どちらも閾値と比較されるが、同じ量ではない。したがって、一方のために選んだ閾値を他方の閾値として使うことはできない。

2つのチームが同点のとき、router_lib の classify 関数はラベルの添字が小さいほうを取る。これは torch の argmax の仕様に従った結果であり、そのドキュメントには次のようにある。「最大値が複数ある場合は、最初の最大値の添字が返される。」(torch 2.15.0+cpu のドキュメント)同点に対する規則を固定しておけば、出力を再現できる。

実践ルール: チームと確信度は1回の順伝播から読み取り、チームは確率が最も高い出力として取る。引き継ぎの判断と、それが保護するチームが同じ回答に由来するように、両者を1つの関数にまとめる。ヘッドの確信度を代役モデルの確信度と並べて、同じものを測っているかのように扱ってはならない。

この部分はまだ翻訳されていないため、英語で表示している。

Adapters train a small part of the model

最終変更:版2026.11.9

Full fine-tuning changes every weight in the base model. LoRA takes a different route. The paper that introduced LoRA, Hu et al. (2021), says it freezes the pre-trained weights and injects trainable low-rank matrices into the layers of the Transformer, and the trained LoRA matrices are the adapter. The base model stays as it was, and the adapter is the part this book stores, loads and versions.

The rank, r, is the inner size of each added matrix, and it is kept small. Peft scales the added update by lora_alpha divided by r (peft 0.21.3, src/peft/tuners/lora/layer.py, line 281: self.scaling[adapter_name] = lora_alpha / r), so lora_alpha sets how strongly the update counts. This book uses a rank of 8, with lora_alpha set to 16. The added matrices go in the projection layers named q_proj and v_proj in each attention block. The abstract does not name those layers, so this choice is the book's, not something the paper prescribes. We recommend it as a starting point, and the recorded adapter below is the test of that recommendation on this task. Other targets are a choice to measure, not a fact about the method.

The head is trained as well. Peft does that for this book's setup: a model built as a sequence classifier lists its classifier and score layers in modules_to_save (peft 0.21.3, src/peft/peft_model.py, line 1830: classifier_module_names = ["classifier", "score"]), so training moves the 77-output layer and the adapter together. Count only the adapter's matrices and you get a smaller number than the one the code trains, and the difference is the head. The next section's run counts the split from the loaded model: 460800 in the adapter and 44352 in the head, which together make 505152.

The adapter's manifest records the base model's revision, so a reader can check that revision against models.toml before scoring.

Working rule: Set the rank, the scaling and the target layers in one configuration, and count the trainable parameters from the loaded model before training starts. Print the total with the head in it. A count that leaves out the head reports part of what training changes, and it will not match what the optimizer updates.

この部分はまだ翻訳されていないため、英語で表示している。

Thirty steps are not enough

最終変更:版2026.11.2

Before the book uses a recording, it shows what a short run does with the same recipe. The run below takes 30 steps, at batch size 8 and seed 0, on the training rows outside dev, and then scores test_200, the first 200 entries of the fixed sample that chapter 2 drew. It is a failure, and the book shows it as one. The short run checks that the pipeline works from start to finish, and that is its only job here.

lora-thirty-steps.py Python 3.12.15 · peft 0.21.3 · torch 2.15.0+cpu · torchao 0.18.0+cpu · transformers 5.23.0 合格
"""Train for 30 steps on the recorded recipe, then score test_200 at the placeholder threshold of 0.5.Read the three step losses against the uniform-guess loss, then the hand-off line at that threshold. The recording runs 1,125 steps."""import mathimport torchtorch.set_num_threads(2)import router_lib  # noqa: E402router_lib.setup_runtime()REPO = "HuggingFaceTB/SmolLM2-135M-Instruct"STEPS, BATCH, SEED = 30, 8, 0train, order = router_lib.training_rows(SEED)  # the seed sets the shuffled order of the training rows, the one the recording usedtok, model = router_lib.new_classifier(REPO)  # SmolLM2 with a 77-way head, LoRA rank 8, lora_alpha 16, on q_proj and v_projlora, head = router_lib.parameter_split(model)  # LoRA tensors have "lora_" in their names; every other trainable tensor is the headprint(f"trainable parameters: {lora + head}")print(f"LoRA parameters: {lora}")print(f"head parameters: {head}")losses = router_lib.train_steps(model, tok, train, order, STEPS, BATCH)  # AdamW at learning rate 1e-3, router_lib's defaultprint(f"training steps: {STEPS}")print(f"batch size: {BATCH}")print(f"seed: {SEED}")for step in (10, 20, 30):    print(f"loss at step {step}: {losses[step - 1]:.2f}")  # train_steps returns one loss per step, from step 1 at index 0, so step 10 is index 9print(f"loss of a uniform guess over 77 teams: {math.log(77):.2f}")result = router_lib.score_test_sample(model, tok, "test_200", 0.5)  # 0.5 is chapter 1's placeholder; this run chooses no thresholdn = result["n"]print(f"messages on test_200: {n}")print(f"accuracy on test_200: {result['correct']}/{n} ({result['accuracy']:.1%})")print(f"handed off at placeholder 0.50: {result['handed_off']}/{n} ({result['handoff_rate']:.1%})")if result["accuracy_not_handed_off"] is None:  # None when no message is kept, so there is no accuracy to print    print("accuracy on messages not handed off: not defined (0 messages not handed off)")else:    m = result["not_handed_off"]    print(f"accuracy on messages not handed off: {result['correct_not_handed_off']}/{m} ({result['accuracy_not_handed_off']:.1%})")
出力python lora-thirty-steps.py
trainable parameters: 505152
LoRA parameters: 460800
head parameters: 44352
training steps: 30
batch size: 8
seed: 0
loss at step 10: 4.13
loss at step 20: 6.12
loss at step 30: 4.38
loss of a uniform guess over 77 teams: 4.34
messages on test_200: 200
accuracy on test_200: 5/200 (2.5%)
handed off at placeholder 0.50: 200/200 (100.0%)
accuracy on messages not handed off: not defined (0 messages not handed off)

Thirty steps are not enough to route with. The head this run trains gets 5/200 (2.5%) right on test_200, and at the placeholder threshold it hands every message to a person: 200/200 (100.0%). A router that hands off every message gives no message to a team, so the labels it predicts never reach a caller. Because no message is kept, the accuracy on messages not handed off is not defined, as the output says.

The loss does not fall steadily across the three printed steps: it is 4.13 at step 10, 6.12 at step 20, and 4.38 at step 30. Step 20 is higher than step 10, and step 30 is lower than step 20 but higher than step 10. Three points from 30 steps are not a learning curve. The loss at step 30 sits close to the uniform guess of 4.34, so at that point the head is still close to chance. A uniform guess gives each team the same probability, one in 77, so its loss is the natural log of 77. The recording used in the section on the recorded adapter runs the same recipe for far more steps, and its accuracy is the one this book reports.

Scoring test_200 here only reports the failure, and nothing is chosen from it: the recipe is fixed before the run, and the threshold is chosen later on dev. To see whether training works, read the loss and the dev measures, not the test sample, which is the rule chapter 2 set for every sample. Tuning a recipe against the test sample leaves no clean number to report, and the sample stops being a test.

Working rule: Run a short training to check that the pipeline works from start to finish, and do not route with its head. Judge a fine-tuned head on the dev split, with the measures set in chapter 2, after a run long enough to reach them. Do not read a loss curve of a few points as evidence that the head learns.

テスト行ではなく訓練行で訓練する

最終変更:版2026.11.2

訓練ファイルにはラベル付きのメッセージが入っている。第2章では、このファイルから固定のシードを用いてチームごとに dev 分割を切り出した。訓練には、dev のために取り分けられていない訓練行を用いる。テストファイルは訓練中には一切読み込まない。thirty steps are not enough の訓練順序は、dev を除いた後に残る行から作られ、シード 0 でシャッフルされるため、実行のたびに同じになる。

dev 分割は意思決定を担う。これは訓練ファイルである train.csv から取った 1003 件のメッセージから成る。どの訓練ステップもこれらを読まず、しきい値の選択と、最後の節での較正の確認にのみ用いる。

この手順はアダプタのマニフェストに書き込まれるため、読者はアダプタが何で訓練されたかを確認できる。記録されるのは、ベースモデルの固定されたリビジョン、データのコミット、バッチサイズ、シード、ステップ数である。訓練を再現するにはこれらの値が必要であり、結果がクリーンな分割から得られたことを確かめるにはデータのコミットが必要である。

このルールが最も重要になるのは、結果が良好に見えるときである。テストサンプルを読み込んだ訓練では、その後に採点されるメッセージをすでに見ていることになり、テスト精度は新しいメッセージについて何も測定しない。dev とテストを分けておくことで、次の節のテスト精度は公正な報告となる。

実践ルール: 訓練には、dev の外にある訓練行だけを用いる。シード、バッチサイズ、ステップ数、データのコミットをマニフェストに記録する。dev がしきい値を決めるには小さすぎる場合は、第2章に述べたとおり、テストファイルからではなく訓練ファイルからメッセージを追加で取る。

この部分はまだ翻訳されていないため、英語で表示している。

Use the recorded adapter

最終変更:版2026.11.2

The working router uses banking77-lora-v1: the adapter from the full recorded run, version 1, written by recordings/lora_full.py. That script trained the adapter once, on the recipe in the section on training rows, and wrote its files and a manifest. The manifest holds the base model's revision, the data commit, the threshold, the recipe's hash and the hashes of the output files. Offline, the adapter loads and scores test_200 at the threshold from its manifest, and nothing is trained.

Take the adapter as it was recorded. A different recipe becomes a new run, named v2; the book does not edit the adapter by hand. Keeping the recording fixed is what lets a reader check the numbers in this chapter against the files they downloaded.

lora-recorded-adapter.py Python 3.12.15 · peft 0.21.3 · torch 2.15.0+cpu · torchao 0.18.0+cpu · transformers 5.23.0 合格
"""Load the recorded adapter banking77-lora-v1 and score test_200 at the threshold in its manifest; no training runs here.Read the accuracy line with the two hand-off lines printed under it."""import osos.environ["HF_HUB_OFFLINE"] = "1"os.environ["TRANSFORMERS_OFFLINE"] = "1"import json  # noqa: E402import torch  # noqa: E402torch.set_num_threads(2)import router_lib  # noqa: E402router_lib.setup_runtime()RECORDED = router_lib.HERE / "data" / "recorded" / "lora-full"manifest = json.loads((RECORDED / "manifest.json").read_text())threshold = manifest["handoff_threshold"]  # the threshold the recording chose on dev; this script chooses nonetokenizer, model = router_lib.load_classifier(RECORDED / "adapter")  # the base model comes from the adapter's config, at its revision in models.tomltest = router_lib.read_rows("test")sample = router_lib.read_sample("test_200")golds = [test[i][1] for i in sample]preds, confs = router_lib.classify(model, tokenizer, [test[i][0] for i in sample])  # a tie goes to the lower label indexresult = router_lib.metrics(preds, golds, confs, threshold)  # a message is handed off when its confidence is below the thresholdn = result["n"]print(f"adapter: {manifest['adapter']}")print(f"handoff threshold from manifest: {threshold:.2f}")print(f"messages on test_200: {n}")print(f"accuracy on test_200: {result['correct']}/{n} ({result['accuracy']:.1%})")print(f"handed off: {result['handed_off']}/{n} ({result['handoff_rate']:.1%})")if result["accuracy_not_handed_off"] is None:  # None when no message is kept, so there is no accuracy to print    print("accuracy on messages not handed off: not defined (0 messages not handed off)")else:    m = result["not_handed_off"]    print(        f"accuracy on messages not handed off: {result['correct_not_handed_off']}/{m} "        f"({result['accuracy_not_handed_off']:.1%})"    )
出力python lora-recorded-adapter.py
adapter: banking77-lora-v1
handoff threshold from manifest: 0.63
messages on test_200: 200
accuracy on test_200: 172/200 (86.0%)
handed off: 33/200 (16.5%)
accuracy on messages not handed off: 156/167 (93.4%)

The recorded adapter is right on 172/200 (86.0%) of the messages, against 9/200 (4.5%) for the prompted 135M model that chapter 4 measured on the same 200. The 30-step run, at 5/200 (2.5%), falls below the prompted model. A handed-off message counts as wrong when its team is wrong. The output beside this paragraph gives the hand-off count and the accuracy on messages not handed off, each with its count and denominator, as chapter 2 requires.

The threshold is not chosen on this sample. It came from the manifest, which the section on choosing the threshold explains. It is the threshold the recorded adapter's hand-off counts on test_200 use: 0.63. Reading it from the manifest keeps the choice on dev, where the rule made it.

The recorded adapter is the router's model, and the stand-in is the baseline. The two were measured with different thresholds, so their hand-off counts are not the same kind of result. Compare them on the same messages, with each threshold named beside its count. The comparison below does that for test_200, reading the stand-in's recorded answers for the same messages.

compare-with-standin.py Python 3.12.15 · peft 0.21.3 · torch 2.15.0+cpu · torchao 0.18.0+cpu · transformers 5.23.0 合格
"""Set the stand-in's recorded answers beside the recorded adapter's live predictions on the same 200 test messages.The last two lines count where the models disagree."""import osos.environ["HF_HUB_OFFLINE"] = "1"os.environ["TRANSFORMERS_OFFLINE"] = "1"import json  # noqa: E402import math  # noqa: E402import torch  # noqa: E402torch.set_num_threads(2)import router_lib  # noqa: E402router_lib.setup_runtime()STANDIN_THRESHOLD = 0.5  # chapter 1's placeholder; the stand-in's own threshold is never chosen on devADAPTER = router_lib.HERE / "data" / "recorded" / "lora-full"with open(router_lib.HERE / "data" / "recorded" / "standin-baseline" / "answers.jsonl") as f:    answers = {row["index"]: row for row in map(json.loads, f)}  # keyed by the test-row index that read_sample returnsthreshold = json.loads((ADAPTER / "manifest.json").read_text())["handoff_threshold"]test = router_lib.read_rows("test")sample = router_lib.read_sample("test_200")golds = [test[i][1] for i in sample]standin_preds = [answers[i]["label"] for i in sample]standin_confs = [math.exp(answers[i]["logprob"]) for i in sample]  # the recording stores log-probabilities; exp turns one back into the probability its answer hadtokenizer, model = router_lib.load_classifier(ADAPTER / "adapter")adapter_preds, adapter_confs = router_lib.classify(model, tokenizer, [test[i][0] for i in sample])standin = router_lib.metrics(standin_preds, golds, standin_confs, STANDIN_THRESHOLD)adapter = router_lib.metrics(adapter_preds, golds, adapter_confs, threshold)n = standin["n"]s_right = [p == g for p, g in zip(standin_preds, golds)]a_right = [p == g for p, g in zip(adapter_preds, golds)]print(f"messages on test_200: {n}")print(f"stand-in correct: {standin['correct']}/{n} ({standin['accuracy']:.1%})")print(f"adapter banking77-lora-v1 correct: {adapter['correct']}/{n} ({adapter['accuracy']:.1%})")print(f"stand-in placeholder threshold: {STANDIN_THRESHOLD:.2f}")print(f"stand-in handed off: {standin['handed_off']}/{n} ({standin['handoff_rate']:.1%})")print(f"adapter threshold from manifest: {threshold:.2f}")print(f"adapter handed off: {adapter['handed_off']}/{n} ({adapter['handoff_rate']:.1%})")print(f"right for the adapter, wrong for the stand-in: {sum(a and not s for a, s in zip(a_right, s_right))}/{n}")print(f"right for the stand-in, wrong for the adapter: {sum(s and not a for a, s in zip(a_right, s_right))}/{n}")
出力python compare-with-standin.py
messages on test_200: 200
stand-in correct: 109/200 (54.5%)
adapter banking77-lora-v1 correct: 172/200 (86.0%)
stand-in placeholder threshold: 0.50
stand-in handed off: 9/200 (4.5%)
adapter threshold from manifest: 0.63
adapter handed off: 33/200 (16.5%)
right for the adapter, wrong for the stand-in: 69/200
right for the stand-in, wrong for the adapter: 6/200

Matching the two models message by message shows which messages each one misses. The stand-in's answers come from its recording, and the adapter runs live on the same 200 messages. The stand-in's confidence is the probability its recorded answer had, from the recording's log-probability. The stand-in's threshold is chapter 1's placeholder, 0.50, and the output labels it as one. Its hand-off count, 9/200 (4.5%), says what that placeholder does to the stand-in, and nothing about the stand-in's own threshold, which was never chosen on dev. The adapter hands off 33/200 (16.5%) at 0.63.

The adapter is right on 172/200 (86.0%) of these messages, the stand-in on 109/200 (54.5%). Where the two disagree, the adapter alone is right on 69/200, and the stand-in alone on 6/200. Two accuracies can be equal while the two models miss different messages, and the disagreement counts show where that happens.

The comparison is one sample of 200 messages. Chapter 1 said that its small sample can show that a router fails, but cannot tell two routers apart with confidence. Chapter 1's sample was smaller. The discordant counts here, 69/200 against 6/200, are stronger evidence than that sample could give. For a firmer claim, run the same comparison on the full test_1001 sample, which the stand-in's recording also covers.

Working rule: Compare two models only on the same messages, and name the threshold each one used beside its count. When one threshold is a placeholder, say so beside its count, and do not read its hand-off count as the model's own result.

dev で閾値を選ぶ

最終変更:版2026.11.2

閾値とは、メッセージを人に回すかどうかを分ける境界である。第 2 章でその測度を定め、第 1 章ではプレースホルダのままにしていた。本書の規則は、dev 分割のみで閾値を選ぶ。0.01 刻みの格子上で、人に引き継がれないメッセージの正解率が目標値 0.90 以上となる、最も低い信頼度閾値を採る。この規則は、その値とともにマニフェストに書かれている。そのため読者は、規則が出した数値だけでなく、規則そのものも確認できる。章 2 が求めるとおり、テスト標本はここでは一切用いない。

choose-threshold-on-dev.py Python 3.12.15 · peft 0.21.3 · torch 2.15.0+cpu · torchao 0.18.0+cpu · transformers 5.23.0 合格
"""Find the hand-off threshold on dev by the manifest's rule, then check it against the manifest's value.Read the chosen threshold beside the three threshold lines. test_200 is not read here."""import jsonimport torchtorch.set_num_threads(2)import router_lib  # noqa: E402router_lib.setup_runtime()RECORDED = router_lib.HERE / "data" / "recorded" / "lora-full"manifest_threshold = json.loads((RECORDED / "manifest.json").read_text())["handoff_threshold"]TARGET = 0.90  # the book's target accuracy on messages not handed off: a choice the book makes, not one the data setstokenizer, model = router_lib.load_classifier(RECORDED / "adapter")rows = router_lib.read_rows("train")dev = router_lib.read_sample("dev")golds = [rows[i][1] for i in dev]preds, confs = router_lib.classify_by_length(model, tokenizer, [rows[i][0] for i in dev])  # batches by length to pad less; results come back in dev ordern = len(dev)chosen = router_lib.choose_threshold(preds, golds, confs, TARGET)  # the rule lives in router_lib: the lowest 0.01 grid value that meets TARGET; None if no value meets it, and the prints below would then failprint(f"dev messages: {n}")print(f"target accuracy on messages not handed off: {TARGET:.2f}")print(f"chosen threshold: {chosen:.2f}")print(f"threshold in manifest: {manifest_threshold:.2f}")print(f"chosen threshold matches manifest: {'yes' if chosen == manifest_threshold else 'no'}")  # both come from the same 0.01 grid, so equal means the same thresholdfor t in sorted({0.50, chosen, 0.90}):  # 0.50 is chapter 1's placeholder; a set drops the chosen value if it is one of the other two    r = router_lib.metrics(preds, golds, confs, t)    print(f"threshold {t:.2f} handed off: {r['handed_off']}/{n} ({r['handoff_rate']:.1%})")    print(f"threshold {t:.2f} accuracy on messages not handed off: {r['correct_not_handed_off']}/{r['not_handed_off']} ({r['accuracy_not_handed_off']:.1%})")
出力python choose-threshold-on-dev.py
dev messages: 1003
target accuracy on messages not handed off: 0.90
chosen threshold: 0.63
threshold in manifest: 0.63
chosen threshold matches manifest: yes
threshold 0.50 handed off: 80/1003 (8.0%)
threshold 0.50 accuracy on messages not handed off: 811/923 (87.9%)
threshold 0.63 handed off: 148/1003 (14.8%)
threshold 0.63 accuracy on messages not handed off: 770/855 (90.1%)
threshold 0.90 handed off: 352/1003 (35.1%)
threshold 0.90 accuracy on messages not handed off: 620/651 (95.2%)

記録されたアダプタで dev を採点し、規則を適用すると、閾値は 0.63 となる。マニフェストの値との照合は yes と出力される。不一致であれば、マニフェストと規則が食い違っていることを意味する。

3 つの閾値でトレードオフを示す。下の表は、それぞれの件数と割合を並べたものである。閾値を上げても、人に引き継がれるメッセージが減ることはない。規則は、目標を満たす最も低い値を選ぶ。各行は同じ dev メッセージに対する同じアダプタの結果であり、変わるのは閾値だけである。

閾値 引き継がれた件数(dev) 引き継がれなかったメッセージの正解率(dev)
0.50 80/1003 (8.0%) 811/923 (87.9%)
0.63(選択値) 148/1003 (14.8%) 770/855 (90.1%)
0.90 352/1003 (35.1%) 620/651 (95.2%)

0.50 では、ルータはより多くのメッセージを自分で保持するが、保持したメッセージの正解率は低く、目標に届かない。0.90 では、保持したメッセージの正解率は 3 つのうち最も高いが、人に回される dev メッセージも最も多い。選ばれた値は、3 つの閾値のうち目標を満たす最も低いものなので、0.50 より多く、0.90 より少ないメッセージを引き継ぐ。表は、引き継ぎという代償と、それによって得られる正解率を示している。目標をどこに置くかは業務上の判断であり、規則が決めることはできない。本書では、保持したメッセージの正解率として 0.90 を用いる。自行のルータを運用する銀行であれば、このトレードオフから自らの目標を読み取ることになる。

本番でもアダプタは変わらないが、アダプタが目にするメッセージは変わる。たとえば、製品の障害により、ある 1 週間にあるチームに関するメッセージが大量に届いたとする。閾値は dev のメッセージ構成で選ばれたものなので、アダプタがまったく同じでも、引き継ぎ率は単独で動きうる。アダプタに変更がないのに引き継ぎが増えたときは、まずメッセージの構成を確認すべきである。引き継ぎ率が正しそうに見えるまで閾値を目分量で動かすと、規則が選ばれた理由である性質、すなわちルータが保持する dev メッセージで目標以上の正解率を保つという性質が失われる。

信頼度は、そのチームが正しい確率ではない。Guo et al. (2017) は、彼らのネットワークが「poorly calibrated」であると報告している。これは、信頼度が実際の正解の頻度と一致しないという意味である。本書では、自らのアダプタを dev で検査する。dev メッセージを 5 つの信頼度の帯に分け、各帯に件数、正解率、平均信頼度を付ける。後の 2 つは、Guo et al. が較正を測るときに比較する量である。dev を信頼度で分けてみれば、0.9 が 10 件中 9 件を意味するかどうかが分かる。

calibration-bands-on-dev.py Python 3.12.15 · peft 0.21.3 · torch 2.15.0+cpu · torchao 0.18.0+cpu · transformers 5.23.0 合格
"""Group the dev messages into five bands by the adapter's confidence, and print each band's count, accuracy and mean confidence.Read the top band's mean confidence against its accuracy. Only dev is read."""import osos.environ["HF_HUB_OFFLINE"] = "1"os.environ["TRANSFORMERS_OFFLINE"] = "1"import torch  # noqa: E402torch.set_num_threads(2)import router_lib  # noqa: E402router_lib.setup_runtime()RECORDED = router_lib.HERE / "data" / "recorded" / "lora-full"BANDS = [(0.0, 0.2), (0.2, 0.4), (0.4, 0.6), (0.6, 0.8), (0.8, 1.0)]tokenizer, model = router_lib.load_classifier(RECORDED / "adapter")rows = router_lib.read_rows("train")dev = router_lib.read_sample("dev")golds = [rows[i][1] for i in dev]preds, confs = router_lib.classify_by_length(model, tokenizer, [rows[i][0] for i in dev])  # results come back in dev order, so index i matches golds[i]print(f"dev messages: {len(dev)}")counted = 0for lo, hi in BANDS:    last = hi == 1.0    members = [i for i, c in enumerate(confs) if lo <= c < hi or (last and c == 1.0)]  # lower edges are in, upper edges out; the top band also takes 1.0, so each message is counted once    counted += len(members)    name = f"band {lo:.1f}-{hi:.1f}"    print(f"{name} messages: {len(members)}")    if members:        correct = sum(preds[i] == golds[i] for i in members)        print(f"{name} correct: {correct}/{len(members)} ({correct / len(members):.1%})")        print(f"{name} mean confidence: {sum(confs[i] for i in members) / len(members):.1%}")    else:        print(f"{name} correct: not defined (0 messages)")        print(f"{name} mean confidence: not defined (0 messages)")print(f"messages in bands: {counted}")
出力python calibration-bands-on-dev.py
dev messages: 1003
band 0.0-0.2 messages: 1
band 0.0-0.2 correct: 1/1 (100.0%)
band 0.0-0.2 mean confidence: 19.9%
band 0.2-0.4 messages: 41
band 0.2-0.4 correct: 10/41 (24.4%)
band 0.2-0.4 mean confidence: 32.9%
band 0.4-0.6 messages: 92
band 0.4-0.6 correct: 49/92 (53.3%)
band 0.4-0.6 mean confidence: 51.0%
band 0.6-0.8 messages: 123
band 0.6-0.8 correct: 84/123 (68.3%)
band 0.6-0.8 mean confidence: 70.6%
band 0.8-1.0 messages: 746
band 0.8-1.0 correct: 693/746 (92.9%)
band 0.8-1.0 mean confidence: 96.4%
messages in bands: 1003

dev メッセージの大半は、0.8 から 1.0 の最上位の帯に入り、その件数は 746 である。0.0 から 0.2 の最下位の帯は 1 で、少なすぎるため、その正解率から低い信頼度について何かを言うことはできない。

dev では、信頼度はメッセージを有用な順序に並べるが、上位では信頼度が正解率を上回る。最上位の帯の平均信頼度は 96.4% であるのに対し、正解率は 693/746 (92.9%) である。5 つの帯のうち 4 つは、正解率がその帯の範囲内に収まっており、例外は最下位の帯で、その 1 件のメッセージによるものである。2 番目の帯から上では、正解率は上昇する。中央の 2 つの帯では、正解率と平均信頼度が近い値になっているが、0.2 から 0.4 の帯では、平均信頼度が正解率を大きく上回る。

帯からこれ以上のことは読み取れない。0.2 から 0.4 の帯のメッセージは 41 件である。ここに示した数値はすべて、閾値を選んだものと同じ 1 つの dev 標本から得られている。したがって、新しいメッセージに対してアダプタがどの程度較正されているかは、どの数値からも分からない。

規則が選ぶルータは、dev 上の経験的な境界であり、その規則とデータとともに記録される。これは境界であって、メッセージのモデルではないため、その数値は dev の構成を表すものである。読者は、その引き継ぎ率と、保持したメッセージの正解率をルータの結果として受け取り、メッセージの構成が動いたときには dev の規則を再び確認する。

実践ルール: 閾値は、明示した規則に従って dev 分割で選び、その値と規則をアダプタのマニフェストに書く。引き継ぎ率は、保持したメッセージの正解率と並べて、それぞれ件数を付けて報告し、選んだ値の前後に少なくとも 1 つずつ設定を示す。信頼度を境界として信頼する前に、dev で較正を確認する。メッセージの構成が変わったときは、訓練ファイルから新たに抽出した dev で閾値を選び直す。

この版における本章

第2026.11.9版2026年11月20日時点で例が通過この章の5 例件のうち5件が合格

英語版の書籍(版2026.11.9)から翻訳した。

この節を引用する

形式

いずれの形式も、本訳書が従う英語版の書籍を出典として示す。

いずれの形式もこの版を明示している。そのリンクは現行版を開き、節の見出しには本文が最後に変更された日付が示される。アクセス日と取得日は、これを開いた日である。

このページの内容

全10章中の第5章: LoRAによる分類ヘッドのファインチューニング

  1. チームを採点するヘッド
  2. Adapters train a small part of the model
  3. Thirty steps are not enough
  4. テスト行ではなく訓練行で訓練する
  5. Use the recorded adapter
  6. dev で閾値を選ぶ

ページの先頭に戻るすべての章