小さなモデルにプロンプトを与え、答えをチームに限定する

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

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

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

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

この章を終えるまでに、小さなオープンモデル向けのルータープロンプトを書き、答えがチーム名にしかならないように制約し、その答えのうち正しいものがいくつあるかを測定できるようになる。また、有効な答えが正しい答えとは限らない理由も確認する。そのため、次の章ではモデルにより良い問いを投げるのではなく、モデルを訓練する。

ルーターには、すべての答えがチーム名であることが求められる。第1章で小さなモデルに自由記述で答えさせたとき、モデルはチームを返さなかった。この章ではまず、答えが構造上必ずチームになるようにする。次に、第3章の2つのオープンモデル、SmolLM2-135M-Instruct と SmolLM2-360M-Instruct を、1つのプロンプトと1つの制約で実行し、返ってくる答えを測定する。135M のモデルは第5章で訓練するモデルであり、ここで得られる件数は、その訓練が上回るべき数である。

この章には2種類の数が現れ、両者を区別して扱う。実際に動かす例は、test_40の先頭6件のメッセージ、すなわち固定サンプルの先頭40件のメッセージのうちの6件で実行し、2つのモデルに同じ6件を用いる。これらは仕組みを示すものである。6件のメッセージでは2つのモデルを区別できないため、比較には記録を用いる。各モデルとプロンプトは、そのサンプルの先頭200件であり先の6件を含むtest_200の200件すべてのメッセージに1回ずつ答え、その答えを保存した。記録を読み込むときにモデルは読み込まず、その件数は保存された答えのみから得られる。

記録の前に確定するプロンプト

最終変更:版2026.11.9

この章のすべての例は、1つのルータープロンプトを用いる。このプロンプトは、メッセージがオンライン銀行から届いたものであることをモデルに伝え、サポートチームを1つだけ、チーム名のみで答えるよう求め、77のチームを列挙し、最後をTeam:で終える。そのため、モデルが次に書く語がそのまま答えになる。このタスクのために訓練されていない素のモデルには、これ以外の手がかりが与えられないので、文言は結果に影響する。この章ではプロンプトの調整を行わない。プロンプトはあらゆる記録に先立って固定されており、記録のマニフェストにはそのプロンプトのハッシュが保存されている。プロンプトを変えれば別の記録になり、その件数をここに示した件数と並べて比べることはできない。

プロンプトに含まれるチームの一覧は、制約に用いる一覧と同じものである。次の節で作るトライ木も、同じラベル名を同じ順序で並べて構築するので、どのチームが存在するかについてプロンプトと制約が食い違うことはない。この依存は逆向きにも働く。チームを追加したり名前を変えたりすると、プロンプトが変わり、したがって記録のハッシュも変わる。その場合、この章の件数はもはやそのプロンプトを表しておらず、読者は比較の前に記録し直さなければならない。

素の形式では、ルータープロンプトのテキストをそのままモデルに渡す。チャット形式では、ルータープロンプトのテキストをモデルのチャットテンプレートで包み、既定のシステムプロンプトが加わる。テンプレートが何を変えるかを確かめるために、同じ6件のメッセージに対してチャット形式を実行する。

constrained-decode-135m-chat.py Python 3.12.15 · torch 2.15.0+cpu · torchao 0.18.0+cpu · transformers 5.23.0 合格
"""Route the first 6 messages of test_40 with the 135M model through its chat template, decoding only team names.The template adds the model's default system prompt. The prose quotes this run's accuracy line next to the raw form's, and the messages are never printed."""import os# no network: the pinned model must already be in the local cacheos.environ["HF_HUB_OFFLINE"] = "1"os.environ["TRANSFORMERS_OFFLINE"] = "1"import collections  # noqa: E402import torch  # noqa: E402# two threads, so the sums add in the same order on every runtorch.set_num_threads(2)import router_lib  # noqa: E402# seeds 0 for random and torch, deterministic algorithms and float32, so greedy decoding repeatsrouter_lib.setup_runtime()SMALL = "HuggingFaceTB/SmolLM2-135M-Instruct"tokenizer, model = router_lib.load_model(SMALL)trie = router_lib.build_trie(tokenizer)# (text, label index) for every test row, in file order; the index is the gold teamrows = router_lib.read_rows("test")# row numbers of the first six messages of the fixed 40-message samplesample = router_lib.read_sample("test_40", 6)teams = set(router_lib.LABELS)results = []for i in sample:    # the chat template wraps the message in the model's chat format, with its default system prompt    text = router_lib.chat_prompt(tokenizer, rows[i][0])    # the template has already written the special tokens, so the tokenizer adds none    results.append(router_lib.constrained_team_text(tokenizer, model, trie, text, add_special_tokens=False))valid = [text in teams for _, text in results]# the walk's index, never the decoded text, is what countsright = [index == rows[i][1] for (index, _), i in zip(results, sample)]given = collections.Counter(text for _, text in results)# most given team; a tie in count goes to the team listed firsttop = min(given, key=lambda team: (-given[team], router_lib.LABELS.index(team)))print(f"messages: {len(sample)}")print(f"answers that are a team: {sum(valid)}/{len(sample)}")print(f"accuracy: {sum(right)}/{len(sample)} ({100 * sum(right) / len(sample):.1f}%)")print(f"distinct teams given: {len(given)}")print(f"most given team: {top}, {given[top]}/{len(sample)}")
出力python constrained-decode-135m-chat.py
messages: 6
answers that are a team: 6/6
accuracy: 0/6 (0.0%)
distinct teams given: 3
most given team: cancel_transfer, 3/6

本書では素の形式を既定とする。この選択は、どの記録を読むよりも前に行った。比較対象の2つのモデルはどちらも素の形式で測定されるので、この比較はプロンプトの間ではなくモデルの間の比較になる。チャット形式は後から観察として記録した。200件のメッセージに対して、チャット形式は11/200 (5.5%)件に正解し、素の形式は9/200 (4.5%)件に正解した。200件中2件の差は、この標本ではどちらの向きにも示すことのできない差である。したがって、チャット形式が有利に働くことも、素の形式が不利に働くことも示されておらず、この件数を理由に既定を変えることはしない。トライ木の名前は空白で始まる。この空白は、素の形式ではTeam:の後に続くが、チャットテンプレートで答えを始める改行の後に続くものではない。そのため、チャット形式の件数は、テンプレートだけでなくこのトライ木にも関わるものである。この結果は、小さなモデルでは一般に素のプロンプトがチャットテンプレートに勝つことの証拠ではない。200件のメッセージという1つの標本でそれを決めることもできない。

実践ルール: 比較するすべてのモデルに、比較が必要とする形式で、同じ1つのプロンプトを用いる。チャットテンプレートを採用する前に、素の形式と同じ標本で測定し、小さな差は小さな差として報告する。

自由記述が失敗する理由

第1章では、制約を与えない生のモデルにチームを1つ答えさせた。このときモデルは自由にデコードしている。本章と同じく貪欲法で、各ステップで最もスコアの高いトークンを選ぶが、選べるトークンにマスクをかけていない。その例では回答を数えた。チーム名だった回答は 0/20 であり、ルーターが先へ送れるものはなかった。

モデル自身のデコードには、回答が文になること、一覧にないチームになること、あるいは一覧にあるチーム名に近い綴り誤りになることを防ぐ仕組みがない。デコーダは各ステップで語彙内のどのトークンでも選べるため、回答はどこへでも逸れうる。第1章の代役はこの失敗を示さなかった。記録された回答が、チーム名だけを許す文法から得られたものだったからである。ルーターの中で動くモデルには、デコーダ自身による同じ保証が必要である。

もっともらしい修復は、モデルが書いたものを最も近いチーム名に対応づけることである。しかしこの修復は推測にすぎない。綴りの近い誤りは正しいチームに対応することもあれば、文字が近い別のチームに対応することもある。その場合、ルーターはモデルが一度も挙げなかったチームへメッセージを送ってしまう。第1章が示した対処は別のものである。チームでない回答はエラーとして扱い、サンプル上で数え、メッセージは人に回す。制約を課すと、そのような回答の大半は書き出される前に取り除かれる。それでも数は記録し続ける。制約が効かなくなったときに、振り分けが静かに変わるのではなく、数値として現れるようにするためである。

実践ルール: チームでない回答は、振り分けの失敗として扱う。モデルに何かを振り分けさせる前に、固定したサンプルでそのような回答を数え、綴りの近いものを最も近いチームに対応づけてはならない。回答はデコード時に制約し、数も記録し続ける。そうすれば、制約が破れたときに数値として現れる。

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

A token trie allows only team names

最終変更:版2026.11.9

A model writes tokens, not words, and a team name is a short run of them. build_trie in router_lib, the book's shared module, stores the 77 names as a trie: a tree whose paths spell out each team's tokens, with the team's index at the node where its path ends. The function asserts that no two teams end at the same node, so each path names one team.

The decoder walks this tree as it writes. At the start, the allowed tokens are the first token of each team name. After each token, the allowed set narrows to the children of the node the decoder has reached. Where a path has ended on a team, the end-of-answer token joins the allowed set, so the answer can stop there. No one of the 77 names is the start of another, so every path ends at a leaf. The code would still handle a name that was: at that node the decoder could stop, or continue along the longer name. A walk of this kind cannot leave the list, because every token it may choose leads toward a team.

Greedy decoding then takes the highest-scoring of the allowed tokens at each step. Transformers applies the rule through a callback, prefix_allowed_tokens_fn, which returns the allowed tokens for each position. The processor starts from a mask of minus infinity for every token, sets the allowed tokens' entries to zero, and adds the mask to the scores with scores_processed = scores + mask. Every token that is not allowed keeps minus infinity, so greedy decoding cannot pick it (transformers 5.23.0, src/transformers/generation/logits_process.py).

Chapter 1's stand-in got the same guarantee from its library. recordings/common.py builds a grammar, root ::= "card_arrival" | ..., that lists the 77 names as literal strings, and the recordings applied it through the chat template. llama-cpp-python adds a grammar to its sampler before the greedy step. In llama_cpp/llama.py the line sampler.add_grammar(self._model, grammar) runs under if grammar is not None:, and sampler.add_greedy() runs after it, under elif temp == 0.0: (llama-cpp-python v0.3.36, llama_cpp/llama.py). So the stand-in's answers were limited to the names by the library, where this chapter's callback does the same job in the decoder.

Two details of that code shape the callback. The processor calls it as self._prefix_allowed_tokens_fn(batch_id, sent), so the batch index comes first. And an empty list is an error: the processor raises ValueError when the callback returns no tokens. The book's callback therefore never returns an empty list. When no path can continue, it returns the end-of-answer token, and the answer stops there. The end-of-answer token is the model's <|im_end|>, which is also its pad token (id 2). The decoder stops after 32 new tokens (max_new_tokens=32). Every one of the 600 recorded answers ended on a team. A node with no children always holds a team, so the empty-list case is a guard and not a case the 77 names produce.

First, the 135M model with the trie, on those six messages.

constrained-decode-135m.py Python 3.12.15 · torch 2.15.0+cpu · torchao 0.18.0+cpu · transformers 5.23.0 合格
"""Route the first 6 messages of test_40 with the 135M model, decoding only team names, and count how many right answers that gives.The point rests on the count of answers that are team names, which the trie guarantees, and on the accuracy line, which the measurement section reads. The messages are read from the test split and are never printed."""import os# no network: the pinned model must already be in the local cacheos.environ["HF_HUB_OFFLINE"] = "1"os.environ["TRANSFORMERS_OFFLINE"] = "1"import collections  # noqa: E402import torch  # noqa: E402# two threads, so the sums add in the same order on every runtorch.set_num_threads(2)import router_lib  # noqa: E402# seeds 0 for random and torch, deterministic algorithms and float32, so greedy decoding repeatsrouter_lib.setup_runtime()SMALL = "HuggingFaceTB/SmolLM2-135M-Instruct"tokenizer, model = router_lib.load_model(SMALL)trie = router_lib.build_trie(tokenizer)# (text, label index) for every test row, in file order; the index is the gold teamrows = router_lib.read_rows("test")# row numbers of the first six messages of the fixed 40-message samplesample = router_lib.read_sample("test_40", 6)teams = set(router_lib.LABELS)# (label index, team text); the index comes from the trie walk, not from parsing the textresults = [router_lib.constrained_team(tokenizer, model, trie, rows[i][0]) for i in sample]valid = [text in teams for _, text in results]# the walk's index, never the decoded text, is what countsright = [index == rows[i][1] for (index, _), i in zip(results, sample)]given = collections.Counter(text for _, text in results)# most given team; a tie in count goes to the team listed firsttop = min(given, key=lambda team: (-given[team], router_lib.LABELS.index(team)))print(f"messages: {len(sample)}")print(f"answers that are a team: {sum(valid)}/{len(sample)}")print(f"accuracy: {sum(right)}/{len(sample)} ({100 * sum(right) / len(sample):.1f}%)")print(f"distinct teams given: {len(given)}")print(f"most given team: {top}, {given[top]}/{len(sample)}")
出力python constrained-decode-135m.py
messages: 6
answers that are a team: 6/6
accuracy: 1/6 (16.7%)
distinct teams given: 3
most given team: card_arrival, 4/6

Run on 6 messages, the model's answers are team names in every case, 6/6, which is the guarantee the trie gives. The accuracy on the same messages is 1/6 (16.7%). The measurement section takes that second number apart.

The router does not read the team out of the text. constrained_team returns the index stored at the node where the walk ended, and the text is decoded only so that a reader can see it. The index is fixed by the trie and not by a parser that runs after the model. That is the reason the constraint is worth the code: a parser that matches text to teams can fail in ways the trie cannot. These examples return the team only so that it can be counted. Nothing in this chapter routes a message. A route returns a team only through handoff, which sends an uncertain answer to a person, and the examples here do not call it.

Working rule: Constrain the answer to the labels with a token trie built from the label names, and count the answers that are labels on a fixed sample. The constraint makes every answer a team. It does not make any answer right, so count the right answers as a separate measure.

貪欲デコーディングですべての件数を再現可能にする

最終変更:版2026.11.2

本書のすべての例は貪欲デコーディングを用いる。最も高いスコアのものが選ばれ、サンプリングは行われない。このことは件数にとって重要である。サンプリングされた答えは実行のたびに異なり、その場合、表示された件数を記録と照合して確認することができなくなる。例は router_lib.setup_runtime によってシードと float32 を固定し、スレッド数を 2 に設定するので、一台のマシン上では実行のたびに同じ答えが繰り返される。各例は先頭で自ら torch.set_num_threads(2) を呼び出す。これは、例が実行環境の起動方法に左右されないようにするためである。各例の表示された出力は、実行のたびに記録された出力と比較され、1 行でも変わっていれば検査は失敗する。

一台のマシンで再現できることは、どこでも再現できることと同じではない。PyTorch 2.15.0+cpu のランダム性に関する注記には、完全に再現可能な結果は、リリース間、個々のコミット間、プラットフォーム間では保証されないと書かれている。そのため本書が再現性を主張するのは、examples/requirements.txt で固定されたバージョンと、本書を実行した種類のマシンに限られる。別のプラットフォームの読者は、記録された行を改めて照合することになると考えておくべきである。そこで記録された行が一致しない場合は、例に手を加える前に、変わった行を読むこと。正解の件数が変わる原因は、マシンの違い、ライブラリのバージョンの違い、プロンプトの変更のいずれもありうる。それぞれ対処が異なる。

同点にも固定された規則が必要である。前の節のラベルスコアリングは、ソートキー (score, -index) により、スコアが同点の場合はチーム番号の小さいほうを選ぶ。最も多く与えられたチームの件数は、件数が同点の場合はチーム名で決める。制約付きデコーディングにはチームのスコアがない。その貪欲な各ステップは、許可されたトークンのうち最初の最大値を取るので、同点の場合はトークン ID の小さいほうになる。

実践ルール: 貪欲デコーディングを用い、シードとスレッド数を固定し、実行のたびに表示された各行を記録された写しと比較すること。結果が再現可能であると述べるのは、実行したバージョンとマシンの種類の範囲内にとどめること。

制約付きの回答を測定する

最終変更:版2026.11.2

ライブ例は六つのメッセージを扱っている。生のプロンプトを使った135Mモデルの正解は1/6 (16.7%)、360Mモデルの正解は0/6 (0.0%)であった。六つのメッセージではこれらのモデルに順位を付けられない。この二つの数の差は、正解一つ分にすぎないからである。135Mモデルの最も多い回答はcard_arrival, 4/6であり、同じ六つのメッセージでチャット形式を用いた場合の結果は0/6 (0.0%)であった。

360Mの実行は、より大きなモデルを使うだけで、プログラムは同じである。

constrained-decode-360m.py Python 3.12.15 · torch 2.15.0+cpu · torchao 0.18.0+cpu · transformers 5.23.0 合格
"""Decode team names for the first 6 messages of test_40 with the 360M model, and count how many of them are right.The prose sets its accuracy line against the 135M model's, on the same six messages. The messages are read from the test split and are never printed."""import os# no network: the pinned model must already be in the local cacheos.environ["HF_HUB_OFFLINE"] = "1"os.environ["TRANSFORMERS_OFFLINE"] = "1"import collections  # noqa: E402import torch  # noqa: E402# two threads, so the sums add in the same order on every runtorch.set_num_threads(2)import router_lib  # noqa: E402# seeds 0 for random and torch, deterministic algorithms and float32, so greedy decoding repeatsrouter_lib.setup_runtime()MEDIUM = "HuggingFaceTB/SmolLM2-360M-Instruct"tokenizer, model = router_lib.load_model(MEDIUM)trie = router_lib.build_trie(tokenizer)# (text, label index) for every test row, in file order; the index is the gold teamrows = router_lib.read_rows("test")# row numbers of the first six messages of the fixed 40-message samplesample = router_lib.read_sample("test_40", 6)teams = set(router_lib.LABELS)# (label index, team text); the index comes from the trie walk, not from parsing the textresults = [router_lib.constrained_team(tokenizer, model, trie, rows[i][0]) for i in sample]valid = [text in teams for _, text in results]# the walk's index, never the decoded text, is what countsright = [index == rows[i][1] for (index, _), i in zip(results, sample)]given = collections.Counter(text for _, text in results)# most given team; a tie in count goes to the team listed firsttop = min(given, key=lambda team: (-given[team], router_lib.LABELS.index(team)))print(f"messages: {len(sample)}")print(f"answers that are a team: {sum(valid)}/{len(sample)}")print(f"accuracy: {sum(right)}/{len(sample)} ({100 * sum(right) / len(sample):.1f}%)")print(f"distinct teams given: {len(given)}")print(f"most given team: {top}, {given[top]}/{len(sample)}")
出力python constrained-decode-360m.py
messages: 6
answers that are a team: 6/6
accuracy: 0/6 (0.0%)
distinct teams given: 4
most given team: card_payment_wrong_exchange_rate, 3/6

比較のために、各バリアントに200件のメッセージを回答させた。記録に残っている件数を表に示す。どの行も同じメッセージを使っている。

test_200 でのバリアント チームリスト外の回答 正解 回答に現れた異なるチーム数
135M、生のプロンプト 0/200 9/200 (4.5%) 18
135M、チャットテンプレート 0/200 11/200 (5.5%) 17
360M、生のプロンプト 0/200 12/200 (6.0%) 8

この例は、表の件数を記録から読み取る。

prompting-on-test-200.py Python 3.12.15 · torch 2.15.0+cpu · transformers 5.23.0 合格
"""Compare the three prompting variants on test_200, from the recording only. No model is loaded.The chapter's table takes its three columns from the first three lines printed for each variant, and the point rests on the correct count.recordings/prompting_eval.py wrote one answer per variant and message to examples/data/recorded/prompting-eval/answers.jsonl."""import collectionsimport jsonfrom pathlib import Pathimport torch# two threads, as in the other examplestorch.set_num_threads(2)import router_lib  # noqa: E402# seeds 0 for random and torch, deterministic algorithms and float32, as in the other examplesrouter_lib.setup_runtime()ANSWERS = Path(__file__).resolve().parent / "data" / "recorded" / "prompting-eval" / "answers.jsonl"teams = set(router_lib.LABELS)# (text, label index) for every test row, in file order; the index is the gold teamrows = router_lib.read_rows("test")# the 200 messages of the fixed sample; every variant answers all of themtotal = len(router_lib.read_sample("test_200"))by_variant = collections.defaultdict(list)with open(ANSWERS) as f:    for line in f:        answer = json.loads(line)        by_variant[answer["variant"]].append(answer)for variant in sorted(by_variant):    answers = by_variant[variant]    outside = sum(answer["team"] not in teams for answer in answers)    # answer["label"] is the team index the variant chose; rows[...][1] is the message's gold index    right = sum(answer["label"] == rows[answer["index"]][1] for answer in answers)    given = collections.Counter(answer["team"] for answer in answers)    # most given team; a tie in count goes to the team name that sorts first, not to the index    top = min(given, key=lambda team: (-given[team], team))    # the gold index becomes a team name, to compare with the most given team    gold_top = sum(router_lib.LABELS[rows[answer["index"]][1]] == top for answer in answers)    print(f"{variant} answers outside the team list: {outside}/{total}")    print(f"{variant} correct: {right}/{total} ({100 * right / total:.1f}%)")    print(f"{variant} distinct teams given: {len(given)}")    print(f"{variant} most given team: {top}, {given[top]}/{total}")    print(f"{variant} gold for most given team: {gold_top}/{total}")
出力python prompting-on-test-200.py
135m-chat answers outside the team list: 0/200
135m-chat correct: 11/200 (5.5%)
135m-chat distinct teams given: 17
135m-chat most given team: topping_up_by_card, 55/200
135m-chat gold for most given team: 1/200
135m-raw answers outside the team list: 0/200
135m-raw correct: 9/200 (4.5%)
135m-raw distinct teams given: 18
135m-raw most given team: card_arrival, 165/200
135m-raw gold for most given team: 0/200
360m-raw answers outside the team list: 0/200
360m-raw correct: 12/200 (6.0%)
360m-raw distinct teams given: 8
360m-raw most given team: card_payment_wrong_exchange_rate, 94/200
360m-raw gold for most given team: 4/200

制約はどの行でも守られている。どの行にもチームリスト外の回答はない。しかし、ルーターと呼べるほどの行は一つもない。正解が最も多いのは360Mの生のプロンプトの行で12/200 (6.0%)件であり、ほかの行を上回る差は、どの行についても数メッセージを超えない。

異なるチーム数だけを見ると誤解する。135Mの生のプロンプトの行は異なるチームを18個挙げており、360Mの生のプロンプトの行の8個と比べて多い。しかし135Mの行の回答の大半は一つのチームcard_arrival, 165/200に集中している。一方、360Mの生のプロンプトの行で最も多く挙げられたチームの回答数はcard_payment_wrong_exchange_rate, 94/200にとどまる。

行を読むには、まず第1列を見る。これがゼロでなければ制約が守られていないのであり、それを直すまで、残りの2列には意味がない。ルーティングにとって重要なのは第2列である。この列は、チームが正解ラベルと一致したメッセージを標本全体に対して数えたものであり、誤った回答は誤りとして数える。第3列は、そのバリアントがそもそもいくつのチームを使っているかを表す。少数のチームしか挙げないバリアントは、人気のある少数のチームを当てずっぽうに選んでいるか、狭い範囲の何かを学習しているかのどちらかであり、この数からはどちらなのかは分からない。数が大きくても集中していないとは限らない。135Mの生のプロンプトの行がその例である。読者が自分のメッセージの標本で同じ三つの数を求めれば、各列が同じ意味を持つ、自分のデータでの比較が得られる。

360Mモデルは二つのうち大きいほうであり、どれだけ大きいかは第3章で数えた。この表は、このプロンプトとこの制約において、その代価で何が得られるかを示している。360Mモデルの正解は12/200 (6.0%)件であり、同じ生の形式での135Mモデルは9/200 (4.5%)件である。大きなモデルで数メッセージ増えただけであり、本章は、これを余分なサイズに対価を払う理由とは見なさない。

本書はこれらの件数に区間を計算していない。200件中数メッセージの差は標本に由来する可能性がある。したがって、この表が支持する主張は一つだけである。三つのバリアントは互いに近く、そのどれもルーターではない。二つのプロンプトのどちらかを選びたい読者は、自分のメッセージの標本で両方を実行し、同じ三つの数を数えるべきである。

トライが検査するのは回答の形だけである。プロンプトより先のメッセージは読まず、どのチームが正しいかも知らない。リスト上のチームは、その名前がまだ書ける段階のすべてで許される。したがって、それらの中からデコーダーが選ぶのはモデルの選択であり、マスクが決めるのは、どのチームがそもそも書けるかだけである。

ここで、有効だが誤っている回答を一つ、チームだけで説明する。本書ではメッセージを引用しない。正解のチームがcard_not_workingであるテスト用メッセージが一つあり、135Mの生のプロンプトの行はこれにcard_arrivalを返した。これはリスト上のチームであるから、制約はこれを通し、リスト外の回答の数はゼロのままである。

出力が裏付ける教訓は、制約付きデコーディングによってすべての回答がチームになるが、有効な回答が正しい回答とは限らないということである。制約が取り除くのは、チームではない回答だけである。より良いチームを選ぶわけではなく、プロンプトの変更もそうしなかった。第5章が次の段階である。そこでは、ラベル付きメッセージでヘッドを訓練し、訓練したモデルが同じ標本でより良くルーティングするかどうかを測定する。

本番では、この失敗はエラーとして現れない。チームではない回答の数はゼロのままなので、その数だけを監視する検査は正常を示し続ける。問題を示すのは、固定したラベル付きの標本での正解数だけである。

その代価を負うのは、メッセージを受け取る人々である。有効だが誤ったチームは、メッセージを誤った宛先に送る。そこでサポート担当者は自分たちのものではない依頼を目にし、正しいチームを探して転送しなければならない。これは引き継ぎが生む作業と同じであり、メッセージには誤ってルーティングされたことを示すものがない。自信がないときにそう言えないルーターは、これらの人々に行動の手がかりを何も与えない。また、制約付きデコーディングは他の76チームのスコアを返さないので、これを土台にした引き継ぎのルールには、比較できるチームごとのスコアがない。

実践ルール: 比較するすべてのバリアントについて、一つの固定した標本で、有効な回答の数と並べて正解の数を報告すること。回答がすべて有効なルーターでも、大半のメッセージで誤りうる。それを示すのは後者の数だけである。

事前分布はルーターではない

最終変更:版2026.11.9

制約付きデコーディングは1つの答えを返すだけで、スコアは返さない。ラベルスコアリングは、すべてのチームにスコアを与える。ラベルスコアリングは各チームについて、プロンプトの後に続くそのチームのトークンの対数確率を合計する。ここで対数確率とは、モデルがトークンに与える確率の対数である。合計が最も高いチームが、そのメッセージに対するモデルの第1位のチームである。

3件のメッセージで実行し、それぞれの第1位のチームを読む。

label-scoring-prior.py Python 3.12.15 · torch 2.15.0+cpu · torchao 0.18.0+cpu · transformers 5.23.0 合格
"""Score every team for the first 3 messages of test_40 with the 135M model, by the summed log-probability of its tokens.This shows the model's prior, the team it favours before any fine-tuning. The point rests on the most frequent top team and how many messages it tops. The messages are never printed."""import os# no network: the pinned model must already be in the local cacheos.environ["HF_HUB_OFFLINE"] = "1"os.environ["TRANSFORMERS_OFFLINE"] = "1"import collections  # noqa: E402import torch  # noqa: E402# two threads, so the sums add in the same order on every runtorch.set_num_threads(2)import router_lib  # noqa: E402# seeds 0 for random and torch, deterministic algorithms and float32, so greedy decoding repeatsrouter_lib.setup_runtime()SMALL = "HuggingFaceTB/SmolLM2-135M-Instruct"tokenizer, model = router_lib.load_model(SMALL)rows = router_lib.read_rows("test")# row numbers of the first three messages of the fixed 40-message samplesample = router_lib.read_sample("test_40", 3)# each team's token ids, padded to the longest name, built once for all messagestable = router_lib.label_token_table(tokenizer)tops = []for i in sample:    scores = router_lib.label_scores(tokenizer, model, table, rows[i][0])    # index of the highest-scoring team; a tie goes to the lower index    tops.append(max(range(len(scores)), key=lambda k: (scores[k], -k)))counts = collections.Counter(tops)# most frequent top team; a tie in count goes to the lower indexbest = min(counts, key=lambda k: (-counts[k], k))print(f"messages: {len(sample)}")print(f"distinct top teams: {len(counts)}")print(f"most frequent top team name: {router_lib.LABELS[best]}")print(f"most frequent top team: {counts[best]} of {len(sample)}")
出力python label-scoring-prior.py
messages: 3
distinct top teams: 1
most frequent top team name: card_arrival
most frequent top team: 3 of 3

訓練の前の時点で、モデルはどのメッセージに対しても同じ1つのチームを1位に置く。card_arrivalが3 of 3のメッセージで1位になっている。このチームがモデルの事前分布であり、3件ではそれ以上のことは言えない。

第1位のチームがすべてのメッセージで同じであれば、そのスコアはモデルの事前分布であり、個々のメッセージについてはほとんど何も語らない。200件のメッセージの記録でも、制約付きデコーディングに同じ事前分布が現れている。135Mの生モデルの行が最も多く選ぶcard_arrival, 165/200は、サンプル中の0/200件のメッセージの正解チームである。

合計は短い名前に有利に働く。チーム名の各トークンは対数確率を加え、その値は決して0を超えないので、トークン数の多いチームほど合計を引き下げる項が多くなる。この例は長さで割らずに項を加えており、本章はこれを補正するとは主張しない。ラベルスコアリングを使う読者は、第1位のチームを信頼する前に、正解ラベル付きのサンプルと照らして確認するべきである。

ラベルスコアリングは各チームにスコアを与えるが、これは引き継ぎの規則が必要とするものである。各メッセージは77のチーム名すべてに対してスコアが付けられ、コードはプロンプトを1回実行した後に、これを1つのバッチでまとめて計算する。第5章では、ラベル付きメッセージで訓練したヘッドを通る1回のフォワードパスから、各チームのスコアを得る。ラベルスコアリングは本章からその章への橋渡しである。モデルがすでにチームごとのスコアを持っていること、そして訓練の前にはそれらがメッセージについてほとんど何も語らないことを示している。

実践ルール: ラベルスコアリングは、訓練の前にモデルがどのチームを好むかを見るために使い、ルーティングには使わない。このタスクで、この規模のプロンプト指定モデルでメッセージをルーティングしてはならない。根拠は200件のメッセージの記録である。代わりに、第5章のように、ラベル付きメッセージでヘッドを訓練する。

この章で決めたこと

最終変更:版2026.11.2

この章の規則は、この2つのモデル、このプロンプト、この制約に限られ、対象は録画された200件のメッセージである。より大きなモデル、別のプロンプト、より長い標本によって件数が変わる可能性があるが、本書はそのいずれも、この標本では検証していない。この章が確立するのは、より限定された事実である。生のプロンプトとトライを用いると、この規模のモデルは有効なチームを返すものの、正しいチームを返すことは少ない。注視すべき数値は、正しい回答の件数である。

各決定は、それぞれの節で検証している。プロンプトは最初の節、トライはその節、貪欲デコーディングはその節、2つの件数は測定の節で扱う。最初の節で述べたとおり、これらのいずれかを変更した読者は、比較の前に記録し直さなければならない。制約はすべての回答を有効にするが、正しくできるのは学習だけである。

この章では、次の決定を行った。

  • ルータープロンプトは生の形式とし、比較する両方のモデルがこれを用いる。
  • 制約付きデコーディングでは、77個のチーム名に対するトークントライを用い、貪欲デコーディングと固定したシードを併用する。
  • どの変種も、有効な回答の件数と正しい回答の件数を、固定した1つの標本について報告する。
  • ライブの例は各部分がどう働くかを示し、モデルの比較は200件のメッセージの録画だけで行う。

この版における本章

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

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

この節を引用する

形式

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

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

このページの内容

全10章中の第4章: 小さなモデルにプロンプトを与え、答えをチームに限定する

  1. 記録の前に確定するプロンプト
  2. 自由記述が失敗する理由
  3. A token trie allows only team names
  4. 貪欲デコーディングですべての件数を再現可能にする
  5. 制約付きの回答を測定する
  6. 事前分布はルーターではない
  7. この章で決めたこと

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