1通のメッセージのコストを数えてベースモデルを選ぶ

読了まで約31 分分、5 節 節の 3 例 例。

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

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

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

この章を終えると、本書が使い続ける2つのベースモデルの名前を挙げ、それぞれを固定されたリビジョンで読み込み、モデルを決める前に、1通のメッセージをルーティングするコストをトークン数とパラメータ数で数えられるようになる。

銀行のサポート受信箱に届くメッセージは、どれも振り分けるのにコストがかかる。モデルがメッセージを読んで担当チームを選ぶのであり、そのコストは、ルーターが出発点とするモデルによって決まる。ルーターとは、第1章で構築するシステム全体のことであり、この章ではその土台となる小さなオープンモデルを選ぶ。第2章では、ルーターを評価するサンプルを固定した。この章ではまずコストを基準に選ぶ。銀行は、モデルの周りに何かを構築する前に、メッセージ1通のコストを数えることができるからである。

残す候補

最終変更:版2026.11.2

ベースモデルとは、大量のテキストで事前学習済みのモデルであり、これを一つの仕事に適応させて使う。以降のどの章も、プロンプト、学習、蒸留、サービングを通じて、この選択の上に成り立っている。そのため、この選択は根拠に基づいて行う価値がある。公開されているオープンモデルは数多くあるので、本書は二つの問いで候補を絞る。モデルは銀行の持つハードウェアで動かせるか。銀行はそのライセンスを利用できるか。

実際には、ライセンスが先に来る。ライセンスは、銀行が自社のシステムでそのモデルを使って何をしてよいかを決める。銀行が動かすことのできないモデルは、大きさにかかわらず候補にならない。本書は各モデルのライセンスをそのピンの横に記録しており、読者は本書が用いたものと同じ記録を確認できる。

最初の候補は SmolLM2 である。これは Hugging Face で公開されているモデルのファミリーである。本書がピン留めしているコミットにおける 135M モデルのモデルカードには、このファミリーの三つのサイズが一文で示されている。パラメータ数は 135M、360M、1.7B である。同じカードはライセンスを license: apache-2.0 と記載しており、本書のピンは、本書が採用する二つのモデルの両方についてこれを記録している。カードには、135M モデルの学習データが 2 兆トークンであることも記載されている。これらの数値は 135M モデルのカードのみに基づいている。

本書は三つのサイズのうち二つを残す。以下のリストでその二つを示し、続く表で三つすべてを、各ピンが記録するライセンスとともに並べる。

  • SmolLM2-135M-Instruct は中核となるモデルである。本書の以降の部分では、このモデルを学習し、サービングする。
  • SmolLM2-360M-Instruct は比較用のモデルである。本書はこれを読み込み、パラメータ数と層数を数え、本章および第4章で中核モデルと並べて用いる。本書はこのモデルを学習しない。
モデル 本書での役割 models.toml でのピン留め ライセンス
SmolLM2-135M-Instruct 中核モデル。本書の以降の部分で学習しサービングする あり Apache-2.0
SmolLM2-360M-Instruct 中核モデルと並べる比較用 あり Apache-2.0
SmolLM2 1.7B ピン留めせず、実行もしない なし 記録なし

1.7B モデルは本書の models.toml ファイルにピン留めされておらず、本書はこれを実行しない。本書の例では CPU のスレッド数を 2 に設定しているので、各候補はこの予算の範囲内で読み込まれ、動作しなければならない。この予算を持つ銀行には、本章の以降で述べる理由から、135M モデルを出発点として推奨する。

本書の基準点は別のモデルである。事例では、現在、ホスト型のモデルが銀行のメッセージを振り分けており、本書はそのようなモデルを一度も呼び出さない。その代役となるのが Qwen3-4B-Instruct-2507 である。これはより大きなオープンモデルで、テストメッセージに対する回答を一度だけ記録し、その後はオフラインで読み取る。この代役は、候補を測る際の基準となるベースラインであり、ルーターの候補ではない。これについては第1章で紹介する。

実践ルール: dev 分割、すなわちモデルを選ぶために取り分けておいた学習用メッセージ(第2章)で、自分で定めた指標を満たすファミリー内の最小のモデルから始める。小さいモデルが指標を満たさない場合にのみ、一段階大きなサイズに進み、その際は同じサンプルで大きいモデルを測定してからにする。これは経験則である。自分の測定結果が異なる結論を示すまでは、この規則が成り立つ。

固定したリビジョンで各モデルを読み込む

最終変更:版2026.11.4

前の節では二つのモデルを挙げた。名前だけでは、読み込むモデルのファイルがどのバージョンのものかは決まらない。モデルはコミットを持つリポジトリに保存されており、main のようなブランチは新しいコミットへ移ることがあるからである。完全なコミットハッシュで固定したリビジョンは、ファイルの一つのスナップショットを指す。固定ファイルである examples/models.toml は、そのスナップショットに含まれるすべてのファイルの SHA-256 を記録しており、ランタイムはそれを検査する。共有ローダーは、本書が 5.23.0 に固定している transformers ライブラリにそのコミットを渡す。ローダーは、各モデルのコミットをこのファイルから調べる。

このファイルには、モデルごとに、リポジトリ、コミット、ライセンス、そしてそのモデルが必要とするすべてのファイルの SHA-256 が記されている。ヘッダーには、ランタイムが各モデルを一度だけ取得し、ファイルごとに検査したうえで、オフラインで読み込むと書かれている。このファイルは re-check models --pin によって生成され、ヘッダーには手で編集しないよう書かれている。したがって、固定を変更したい読者は、新しいコミットをファイルに直接書き込むのではなく、このコマンドを実行する。固定のないモデルには調べるコミットがないため、共有ローダーはそのモデルを読み込まない。

例では、ライブラリをインポートする前にそのオフラインフラグを設定する。これにより、読み込みはランタイムがすでに保持しているものだけを読む。ローダーは重みを float32 に設定し、アテンションをライブラリの素の eager 形式で実行する。本書の決定性の規則がこの二つを定めているので、例を実行するたびに同じ数値が得られる。読者のマシンでオフラインの読み込みが失敗した場合は、ほかの何かを変更する前に、ディスク上のファイルを固定ファイルの一覧と比較する。

この例は、出力の側からも固定を監視する。各モデルのパラメータ数を出力するので、モデルの大きさが変われば、本書自身の出力の行の変化として現れ、章がその行から引用するすべての数値も一緒に変わる。異なる数を見た読者は、どの固定を最初に比較すればよいかがわかる。大きさが同じままコミットだけが変わった場合は、ここには現れないので、記録の役目は固定そのものが担い続ける。

一つの例が、保持している両方のモデルを、ランタイムが取得して固定と照合したファイルから、ネットワークなしで読み込み、本書で最初の大きさの数を出力する。

load-both-models-offline.py Python 3.12.15 · torch 2.15.0+cpu · torchao 0.18.0+cpu · transformers 5.23.0 合格
"""Load the 135M and 360M SmolLM2 models at their pins, offline, and print each one's parameter count and layer count. The chapter's size claims rest on both lines; the parameter line is rounded to whole millions."""import osos.environ["HF_HUB_OFFLINE"] = "1"os.environ["TRANSFORMERS_OFFLINE"] = "1"import torch  # noqa: E402torch.set_num_threads(2)import router_lib  # noqa: E402# Seeds, deterministic algorithms and float32, set before either model loads.router_lib.setup_runtime()SMALL = "HuggingFaceTB/SmolLM2-135M-Instruct"MEDIUM = "HuggingFaceTB/SmolLM2-360M-Instruct"def size(model):    """Return (parameter count in millions, rounded to a whole number) and the layer count."""    # parameters() yields a shared tensor once, so the tied embedding and output head count once.    total = sum(p.numel() for p in model.parameters())    return round(total / 1e6), model.config.num_hidden_layers# load_model returns (tokenizer, model). This example needs only the models._, small = router_lib.load_model(SMALL)_, medium = router_lib.load_model(MEDIUM)small_millions, small_layers = size(small)medium_millions, medium_layers = size(medium)print(f"parameters, millions, rounded: {small_millions} and {medium_millions}")print(f"layers: {small_layers} and {medium_layers}")
出力python load-both-models-offline.py
parameters, millions, rounded: 135 and 362
layers: 30 and 32

パラメータとは、モデルが訓練中に学習する数値の一つであり、層とは、トークンが通過する積み重ねられたブロックの一つである。パラメータと層が、この章で使う大きさのすべてである。360M は二つのうち大きいほうである。出力の最初の行は、各モデルのパラメータ数を百万単位に丸めた値、135 and 362 を示す。二行目は同じ順序で層の数、30 and 32 を示す。速度はここに含まれない。時間はマシンに依存するからである。throughput の記録は、名前を挙げたマシン上で、分類器とその int8 コピーを代替モデルと比較して測定する(方法は第7章で述べ、比率は第10章で報告する)。この記録は 360M を測定しない。

これらの数は、モデルカードからではなく、ここでモデルを読み込んで得たものである。

本番環境では、結果が変わったときに最初に尋ねる問い、つまりどのファイルがその結果を生んだのかに、固定が答える。モデルの変更は、コミットとファイルのハッシュが置かれている models.toml の差分として現れる。読者の手元のモデルが本書と異なる出力を返すときは、まずコミットを比較する。

実践ルール: すべてのモデルを examples/models.toml のコミットで固定し、そのコミットとオフラインフラグを使って読み込む。パラメータ数と層の数を固定の横に記録する。そうすれば、モデルの大きさの変化は、後の章での予想外の出来事ではなく、出力の行の変化として現れる。

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

Measure what one message costs

最終変更:版2026.11.9

The previous section showed what the two models are. This section shows what one message costs them. A message's cost comes from what the model reads and what it writes. The router's prompt holds the 77 team names, the message and a request for the team, and the team list is the same in every call, so every message pays for it.

The prompt opens with the sentence "Route this customer message from an online bank to one support team." It asks for the team name only, lists the teams, then gives the message and ends with the word "Team:". Everything in that text is the same from one message to the next except the message itself, so the cost of a message is the fixed text plus the message's own length.

The tokenizer turns the prompt's text into tokens, the units a model reads. The count is in tokens rather than characters because a model reads tokens. Counting needs the tokenizer's rules but no weights, so the count is the first cost you can take before you choose a design. A classifier reads the message once and returns a score for each team. A generative model reads the prompt once and then writes its answer one token at a time, and each token it writes is one more pass through the network. The later chapters use both designs.

One example counts the forward passes, each one call of the network, for a single test message under each design. It uses the 135M model with no adapter. The classifier's head is untrained here, so only the pass count matters.

count-forward-passes.py Python 3.12.15 · torch 2.15.0+cpu · torchao 0.18.0+cpu · transformers 5.23.0 合格
"""Count the forward passes one test_40 message costs a classifier and a generative model, with the 135M model and no adapter. The point rests on the generative line: the model makes one pass for each token it writes, plus one for the end token."""import osos.environ["HF_HUB_OFFLINE"] = "1"os.environ["TRANSFORMERS_OFFLINE"] = "1"import torch  # noqa: E402torch.set_num_threads(2)import router_lib  # noqa: E402from transformers import AutoModelForSequenceClassification  # noqa: E402router_lib.setup_runtime()SMALL = "HuggingFaceTB/SmolLM2-135M-Instruct"texts = [text for text, _ in router_lib.read_rows("test")]# read_sample gives row indices into the test split; index 0 is the sample's first message.message = texts[router_lib.read_sample("test_40")[0]]def count_passes(model, run):    """Return how many forward calls the model makes while run() executes."""    calls = []    # A forward hook on the whole model fires once per call to its forward, so each generation step counts.    handle = model.register_forward_hook(lambda module, args, output: calls.append(1))    run()    handle.remove()    return len(calls)tokenizer, causal = router_lib.load_model(SMALL)# SmolLM2's tokenizer sets a pad token; this line keeps the example working with one that doesn't.tokenizer.pad_token = tokenizer.pad_token or tokenizer.eos_token# The trie holds each team name's tokens, so constrained_team can write only a team name, one token per pass, then the end token.trie = router_lib.build_trie(tokenizer)# The pinned commit from models.toml, and the float32 weights and eager attention that load_model also sets.# The head is new, with one score per team (77), and untrained here; only the pass count matters.classifier = AutoModelForSequenceClassification.from_pretrained(    SMALL, revision=router_lib._pins()[SMALL], num_labels=len(router_lib.LABELS),    dtype=torch.float32, attn_implementation="eager",).eval()# The classification head finds each message's last token through this id, so the config needs it too.classifier.config.pad_token_id = tokenizer.pad_token_idclassifier_passes = count_passes(classifier, lambda: router_lib.classify(classifier, tokenizer, [message]))answers = []generative_passes = count_passes(causal, lambda: answers.append(router_lib.constrained_team(tokenizer, causal, trie, message)))# answers[0] holds (label index, label text). The text is encoded with a leading space, as the model writes it after "Team:".answer_tokens = len(tokenizer.encode(" " + answers[0][1], add_special_tokens=False))print(f"classifier forward passes: {classifier_passes}")print(f"generative forward passes: {generative_passes}")print(f"answer tokens, end token not counted: {answer_tokens}")
出力python count-forward-passes.py
classifier forward passes: 1
generative forward passes: 8
answer tokens, end token not counted: 7

A generative model's cost grows with its answer, and a classifier's does not. For this message the classifier makes 1 pass. The generative model makes 8 passes, one for each of the 7 tokens in its answer and one for the end token.

A second example counts the router prompt's tokens for each of the 40 messages in the fixed test sample, using the 135M model's tokenizer. It runs no model.

count-prompt-tokens.py Python 3.12.15 · torch 2.15.0+cpu · transformers 5.23.0 合格
"""Count the router prompt's tokens for each message in test_40, with the 135M model's tokenizer. No model runs. The point rests on the mean line: a day's prompt cost is the mean, not the median, times the number of messages."""import osos.environ["HF_HUB_OFFLINE"] = "1"os.environ["TRANSFORMERS_OFFLINE"] = "1"import torch  # noqa: E402torch.set_num_threads(2)import router_lib  # noqa: E402from transformers import AutoTokenizer  # noqa: E402router_lib.setup_runtime()SMALL = "HuggingFaceTB/SmolLM2-135M-Instruct"# Only the tokenizer is read from the pinned commit; no weights load.tokenizer = AutoTokenizer.from_pretrained(SMALL, revision=router_lib._pins()[SMALL])texts = [text for text, _ in router_lib.read_rows("test")]# read_sample gives row indices into the test split, in the order the sample lists them.messages = [texts[i] for i in router_lib.read_sample("test_40")]# router_prompt builds the same prompt the router sends. encode keeps its default, so any special tokens are counted too.counts = sorted(len(tokenizer.encode(router_lib.router_prompt(message))) for message in messages)# The median of an even count is the lower of the two middle values, so it is a whole number of tokens.median = counts[(len(counts) - 1) // 2]total = sum(counts)mean = round(total / len(counts))print(f"messages: {len(counts)}")print(f"prompt tokens min: {counts[0]}")print(f"prompt tokens median: {median}")print(f"prompt tokens max: {counts[-1]}")print(f"prompt tokens total: {total}")print(f"prompt tokens mean, rounded: {mean}")
出力python count-prompt-tokens.py
messages: 40
prompt tokens min: 580
prompt tokens median: 585
prompt tokens max: 614
prompt tokens total: 23493
prompt tokens mean, rounded: 587

The prompts differ only in their messages, because the team list is the same text in every prompt. So the spread runs from 580 tokens for the shortest prompt to 614 for the longest, with a median of 585 tokens. The median is the lower of the two middle values, so it is a whole number of tokens.

In production, the count moves when the team list moves. Adding a team adds its name to every prompt, so every message costs more from that day on. Rerun the count after each change to the list, and keep the list in the same order, so that the rest of the prompt does not change with it.

To turn the count into a figure for a day, use the mean, not the median, because a day's prompt tokens are the sum of its prompts. The 40 sample messages total 23493 tokens, a mean of 587 tokens each. The mean is above the median here, so the median times the count would undercount the prompt tokens. Multiply the mean by the number of messages the router handles that day to get the prompt tokens it reads, before any output is counted. The output side depends on the design, and the designs come in later chapters.

This section gives counts only. The time a message takes is the recording's job, as the load step noted.

Working rule: Count the prompt's tokens with the tokenizer of the model you will run, before you choose a design, and count again whenever the prompt changes. The count belongs to that tokenizer, so a count from another model's tokenizer answers a different question.

135M を中核とする理由

最終変更:版2026.11.2

前の節では、135M モデルの位置づけを示した。このモデルはより小さく、本書の以降の部分で訓練し、運用するモデルである。本節では、この選択の理由を述べ、選択がまだ実証されていない点を示す。

小さなモデルにメッセージを振り分けさせる方法は、大きく二つある。一つは、どのチームを選ぶかをプロンプトでモデルに尋ねる方法である。もう一つは、ラベル付きメッセージでモデルを訓練する方法である。Bucher と Martini は、2024 年のプレプリントで、ファインチューニングした BERT 系モデルと、ChatGPT や Claude Opus のような大規模なホスト型モデルをゼロショットでプロンプトした場合とを比較した。その要旨は、ファインチューニングした小さなモデルが、プロンプトした大きなモデルを一貫して、かつ有意に上回ったと報告している(arXiv:2406.08660v2)。この比較は、ファインチューニングした小さなモデルとプロンプトした大きなモデルを対比したものであり、小さなモデル同士の比較ではない。また、一つのプレプリントに基づくものである。本書はこれを、ファインチューニングした小さなモデルを最初に測定する理由として採用する。ファインチューニングしたモデルが受信箱で勝つことの証明とは見なさない。

二つの設計は失敗の仕方も異なり、コストの数値からはそれが分からない。生成モデルは答えをテキストとして書くので、そのテキストが 77 のチームのいずれでもない文字列になることがある。分類器は 77 のチームのそれぞれにスコアを付けるので、答えは常にそのいずれかであり、そのスコアは、確信の持てないメッセージを人に回す引き継ぎルールが読み取る値でもある。第 4 章では生成モデルの答えを 77 の名前に制約し、第 5 章では分類器を訓練する。

コストに関する理由は、ロード手順の数値に基づく。出力された二つの数値のどちらでも、135M モデルのほうが小さい。パラメータ数は 135 and 362 百万、層数は 30 and 32 であり、各組の最初の値が 135M の値である。135M モデルのモデルカードは、このモデルをデバイス上で動かせるほど軽量で、幅広いタスクをこなせると説明している。数値の根拠は本書の例であり、この説明の根拠はモデルカードである。

モデルカードは、モデルにさせるべきことも制限している。「これらのモデルは、決定的な情報源としてではなく、補助的なツールとして使うべきである。」この注意書きは、ルーターの設計と合致する。この規模のモデルはサポート担当者のアシスタントであり、確信の持てないメッセージは人に回される。この引き継ぎは第 1 章で紹介した。

本章は、135M モデルが各指標を満たすことを示すものではない。第 4 章では、両方のモデルを同じメッセージで実行する。これが本節に欠けている比較である。第 5 章では、135M モデルをラベル付きメッセージで訓練し、第 2 章で定めた指標に照らして dev 分割で測定する。それまでは、この選択はコストの数値と上記の研究に基づいている。

この選択を変えうる事柄は三つあり、いずれも議論ではなく測定によって決着する。ファインチューニング後に 135M モデルが dev の指標を満たさなければ、次の手順は、同じ訓練行から 360M を訓練し、同じ方法で測定し、dev 分割で二つを比較することである。135M モデルが dev の指標を満たしても、サポート担当者が引き受けられる数を超えるメッセージを引き継ぐ場合は、引き継ぎのしきい値が調整の手段になる。第 5 章では、そのしきい値を、それに伴う引き継ぎ率とともに dev 分割で設定する。銀行が別のメッセージ群を振り分ける場合は、選択を最初からやり直す。本章の指標は銀行のメッセージを対象としたものであり、それ以外のメッセージを対象としないからである。

この選択にはコストがあり、読者は検討すべきだが、本章はそれを測定していない。どちらのモデルについても、ロード時間も実行時間も示していない。最初の節の実践ルールは、選択を確定する前にその測定を求めている。本章はこの選択を暫定的に行うものであり、以降の章が同じ指標でそれを確認するか、置き換える。

実践ルール: まず小さいほうのモデルをファインチューニングし、テスト分割を見る前に定めた指標に照らして dev 分割で測定する。小さいほうのモデルが dev 分割で指標を満たさなかった時点までは、大きいほうのモデルを比較用に残す。テスト分割を根拠にモデルを切り替えてはならない。

より大きなモデルに必要なもの

最終変更:版2026.11.2

前の節では小さい方のモデルを選び、より大きなモデルである SmolLM2-360M-Instruct の問題は未解決のまま残した。本節では、その問題に何が必要かを示し、本書がそれについて何を把握していて何を把握していないかを述べる。

より大きなモデルが、限定されたタスクでも自動的に優れているとは限らない。2024 年に最初に公開され、EMNLP 2025 に採択されたある研究は、8 つの言語モデルと 8 つのテキスト分類タスクにわたって、ファインチューニング、指示チューニング、プロンプティング、文脈内学習を比較している。その要旨は、より大きなモデルが一貫して高い性能や低い分散をもたらすわけではないと結論づけている(arXiv:2402.12819v4)。これは 1 件の研究であり、本書はこれを、大きなモデルを除外する根拠としてではなく、大きなモデルを測定することの根拠として用いる。

未解決の問題は、135M と同じレシピで学習した 360M が、追加のコストに見合うだけの差で dev の指標を通過するかどうかである。本書は 360M を学習していないため、その答えを知らない。本書の例が使う 2 つの CPU スレッドで 360M の学習を行った場合の学習時間とメモリも、測定していない。第 4 章では、同じプロンプトでの比較対象として 360M を用いる。

その答えを得たい読者は、本書と同じ手順をたどればよい。360M はすでに固定されており、ロード手順が示すとおりオフラインでロードできる。ルータープロンプトのトークン数を 360M のトークナイザーで数え、135M と同じ学習用の行で学習させる。各ステップは個別の変更であり、比較は同じデータの上にとどまるので、2 つの結果を dev 分割で並べて比べられる。

このファミリーで最大のモデルである 1.7B には、さらに多くが必要になる。本書はこれを固定しておらず、これについては何も主張しない。

大きなモデルのメッセージ当たりのコストは、処理するメッセージごとに発生するが、本書は 360M についてそのコストを測定していない。ロード手順は、誰かが学習を行う前の時点で、360M がどれだけ大きいかをすでに示している。パラメーター数は 135 and 362 百万、層数は 30 and 32 であり、各組では 135M の値が先に来る。第 7 章の throughput の記録は、名前を挙げたマシン上で、分類器とその int8 コピーを代替物に対して測定しているが、360M はその中に含まれていない。

本章で下した決定を、読者が自分の銀行の要件と照らして確認できるよう、以下に挙げる。

  • 中核のモデルは SmolLM2-135M-Instruct であり、比較対象は SmolLM2-360M-Instruct である。
  • 両モデルとも、共有ローダーを通じて、オフラインで examples/models.toml のコミットでロードされる。
  • ルータープロンプトのコストは 135M モデルのトークナイザーを用いてトークン数で数え、数えるためにモデルは実行しない。
  • 本章には時間やメモリの数値は現れない。それらは、名前を挙げたマシン上での測定から後で得られる。
  • 360M は本書では学習しない。

次に引き継ぐべき教訓は、公表された研究が大きなモデルは役に立たないかもしれないと述べうる一方で、役に立つかどうかは、自分のサンプルでの自分自身の測定だけが示すということである。

実践ルール: より大きなモデルを選ぶ前に、小さい方に用いたのと同じレシピでそれを学習させ、自分のマシン上で、同じ dev と test のサンプルで測定すること。公表されたスコアではなく、その指標と、そのマシンで実行するコストによって判断すること。

この版における本章

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

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

この節を引用する

形式

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

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

このページの内容

全10章中の第3章: 1通のメッセージのコストを数えてベースモデルを選ぶ

  1. 残す候補
  2. 固定したリビジョンで各モデルを読み込む
  3. Measure what one message costs
  4. 135M を中核とする理由
  5. より大きなモデルに必要なもの

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