ルータを CPU で提供する:ハンドオフをルートの内側に置く

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

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

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

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

この章を終えると、ルータを一つの POST /route エンドポイントとして提供できるようになる。このエンドポイントは、メッセージごとにチーム、確信度、ハンドオフのフラグを返す。また、ハンドオフしたメッセージに対して、ルートがチームを返すことが決してないことをテストできるようになる。

ハンドオフの規則が守られるか破られるかは、ルートで決まる。第1章ではチームを定めた。第5章では、1回の順伝播でチームと確信度を出すヘッドを構築し、メッセージを人に回す基準となるしきい値を選んだ。この章では、そのモデルを HTTP ルートの背後に置く。受信箱のソフトウェアは、このルートにメッセージを送り、チームまたはハンドオフを読み取る。

ルータがフラグを立てたメッセージについて、呼び出し側がルートからチームを得られるなら、第5章でしきい値をどれだけ慎重に選んでも、そのフラグは何の役にも立たない。そこでルートは、チームを出したのと同じ答えからフラグを自ら計算し、フラグが false のときに限ってチームを返す。この章のほかのどの内容も、この規則ほど重要ではない。

この章で提供するのは、第5章が記録からそのまま取り出した float32 のアダプタである。第7章では、重みのみを int8 にしたコピーである banking77-lora-v1-int8 を作り、そのコピーを測定する。この章ではそれを行わない。速度についても、この章では何も測定しない。その比較は第10章の記録から得られるものであり、この章の内容はその結果を何も予測しない。

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

One route that returns the hand-off

最終変更:版2026.11.8

A route is a function that a web framework calls when a request arrives at a path with a method. The framework here is FastAPI, pinned at 0.163.2 in examples/requirements.txt. The router has one route, POST /route. A caller sends a JSON object with one field, message, which holds the text of one inbox message. The route answers with a JSON object of five fields: team, confidence, handed_off, adapter and version.

Each field has one source, and that matters for the hand-off. The confidence is the softmax probability of the team the model chose, which is the meaning chapter 5 gave it. The handed_off flag is the result of handoff(confidence, threshold), which is true when the confidence is below the threshold. The comparison is written as not confidence >= threshold, so a confidence that is not a number, NaN included, is handed off too. The threshold is not typed into the route. The route reads it from the adapter's manifest, where chapter 5 wrote the value it chose on the dev split, so the route and the chapter cannot disagree about the number. The team is None when handed_off is true, and it is the team's label otherwise. The adapter and version fields tell the caller which model answered. The manifest has no field for the adapter's version, so the version is the suffix of the adapter's name: banking77-lora-v1 reports v1.

The route calls the classifier once per request. One forward pass gives the team and the confidence together, and the flag is computed from that same confidence. The two cannot come from two different calls and drift apart. A reader who opens the module will find one route of its own, and one path to a team, the answer the route builds after the flag is set. FastAPI adds its documentation pages, which return no team. We recommend that a router keep this shape: one route, one model call, one flag, and the team read only after the flag. A second route that skips the flag would be the quickest way to undo the work of chapter 5, and it would be hard to notice, because it would still return correct teams for the messages it does not hand off.

Each message of test_40, a fixed sample of 40 that the book uses for quick checks, goes to the route, and the test counts the flags and the teams. It prints counts and never the text of a message.

serve-route-testclient.py Python 3.12.15 · fastapi 0.163.2 · peft 0.21.3 · pydantic 2.14.4 · torch 2.15.0+cpu · torchao 0.18.0+cpu · transformers 5.23.0 合格
"""Send the test_40 messages to the one POST /route through TestClient, in process, and print counts that tie thehand-off flag to the team. The prose's point rests on the "handed off, team is None" line and the "not handed off,team is the gold label" line; the last checks show the route's answer to a body with no message."""import osos.environ["HF_HUB_OFFLINE"] = "1"os.environ["TRANSFORMERS_OFFLINE"] = "1"import torch  # noqa: E402torch.set_num_threads(2)from fastapi.testclient import TestClient  # noqa: E402import router_lib  # noqa: E402router_lib.setup_runtime()                  # seeds, deterministic algorithms and float32, so the counts repeatclient = TestClient(router_lib.make_app(router_lib.HERE / "data" / "recorded" / "lora-full"))  # checks the files, loads the model once, and reads the hand-off threshold from the adapter's manifesttest = router_lib.read_rows("test")         # each row is (message, gold label index)sample = router_lib.read_sample("test_40")  # row numbers of the committed samplereplies = [client.post("/route", json={"message": test[i][0]}) for i in sample]bodies = [r.json() for r in replies]gold = [test[i][1] for i in sample]         # gold label indexes; LABELS turns one into a team nameprint(f"responses: {len(replies)}")print(f"status codes: {sorted({r.status_code for r in replies})}")print(f"response keys: {sorted(bodies[0])}")print(f"handed off: {sum(b['handed_off'] for b in bodies)}/{len(bodies)}")print(f"team names outside the list: {sum(b['team'] is not None and b['team'] not in router_lib.LABELS for b in bodies)}")sure = [k for k, b in enumerate(bodies) if not b["handed_off"]]    # kept: the route returned a teamunsure = [k for k, b in enumerate(bodies) if b["handed_off"]]      # flagged: the route returned no teamprint(f"not handed off, team is the gold label: {sum(bodies[k]['team'] == router_lib.LABELS[gold[k]] for k in sure)}/{len(sure)}")print(f"handed off, team is None: {sum(bodies[k]['team'] is None for k in unsure)}/{len(unsure)}")print(f"adapter: {bodies[0]['adapter']}")print(f"version: {bodies[0]['version']}")bad = client.post("/route", json={})        # a body with no message field, which the route's body model requiresdetail_is_list = isinstance(bad.json()["detail"], list)assert detail_is_list, "a body with no message should get a 422 whose detail is a list"print(f"status on an empty body: {bad.status_code}")print(f"detail is a list: {'yes' if detail_is_list else 'no'}")
出力python serve-route-testclient.py
responses: 40
status codes: [200]
response keys: ['adapter', 'confidence', 'handed_off', 'team', 'version']
handed off: 8/40
team names outside the list: 0
not handed off, team is the gold label: 30/32
handed off, team is None: 8/8
adapter: banking77-lora-v1
version: v1
status on an empty body: 422
detail is a list: yes

The flag and the team agree in this sample. The route answered every request, and the hand-off count is 8/40. Every flagged message came back without a team: 8/8. Of the messages the route kept, 30/32 have the labelled team, the gold label this book scores against. That kept count is the measure chapter 2 calls accuracy on the messages not handed off: the correct messages among those the route did not flag. A handed-off message has no team to score, so it stays out of that count. The last count checks the label set: the number of team names outside the list is 0.

The output shows the rule's shape: a flagged message has no team, and a kept message has one. That holds for the 40 messages of the sample, which is evidence, not a proof about every request. The proof is in the code. The route test checks that the code does what the rule says, on a sample the reader can rerun.

Working rule: Compute the flag in the route, from the same confidence as the team, with handoff, and return a team only when the flag is false. Do not add a second route, a field or an option that returns a team for a message the flag has marked. If a caller needs a team for every message, the answer is a person for the messages the flag marks, not a team from the route.

モデルは起動時に一度だけ読み込む

最終変更:版2026.11.9

リクエストのたびにモデルを読み込むルートは、メッセージごとに同じ作業を繰り返すことになる。この章のルートはそうしない。その理由はコードの置かれた位置にある。関数make_appは、何かを読み込む前に、アダプタのファイルをそのマニフェストと照合し、さらにベースモデルのリビジョンを、マニフェストが記録しているピンと照合する。一致しないものが一つでもあれば、エラーを送出し、アプリを構築しない。この検証は第9章のものであり、本章はそれに依拠している。検証の後、make_appはマニフェストを読み、load_classifierでトークナイザとモデルを読み込み、そのあとで初めてルートを定義する。ルート関数自体は、classifyを呼び、続いてhandoffを呼ぶだけである。したがって、モデルはアプリの構築時に読み込まれ、各リクエストはすでにメモリ上にあるモデルを使う。

ルートのテストはアプリを一度だけ構築し、40件のメッセージをすべてその1つのアプリに送る。そのため、40件のリクエストは1回の読み込みを共有する。読み込みはアプリの構築に含まれており、呼び出し側が行う手順ではない。呼び出し側がリクエストを送ることで、ルートに2つ目のコピーを読み込ませることはできない。

スレッドも、起動時に属する設定である。make_appはスレッド数をthreads引数として受け取り、既定値は2である。そして、モデルを読み込む前に、その数でtorch.set_num_threadsを呼ぶ。このため、アプリを構築するどのプロセスも、最初のモデル呼び出しの前にスレッドを設定する。PyTorchのドキュメントによれば、この呼び出しはCPU上のintra-opスレッド数を設定し、その数を有効にするには「set_num_threads must be called before running eager, JIT or autograd code」(eager、JIT、autogradのコードを実行する前にset_num_threadsを呼ばなければならない)とされている(torch 2.15.0+cpuのドキュメント)。

set_num_threadsの設定が対象とするのは、1つの演算の内部で使われるスレッド、すなわちドキュメントが挙げるintra-opスレッドである。スレッド数を2とするのは本書の選択であり、測定して得た最適値ではない。本書の例には2 vCPUの予算があるため、本書は例のためにスレッドを2に設定している。別のマシンを使う読者は、数を選んだうえで測定すべきである。この選択を本書のものと明記するのは、本章のどの出力も、あるスレッド数を別のスレッド数と比較していないからである。

実践ルール: アプリはプロセスごとに一度、そのプロセスが使うべきスレッド数で、最初のリクエストより前に構築する。本書のように2 vCPUの予算であれば、既定の2スレッドを保つ。別の数を選ぶのは、自分のマシンを自分のメッセージで測定した後に限る。

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

Know what the route cannot score

最終変更:版2026.11.2

Two kinds of request cannot be scored, and the route handles them differently. The first is a request that lacks the field the route needs. The route declares its body as a model with one required field, message. A body without that field gets status 422. The route test ends by sending such a body, and the reply's detail field is a list, which the test asserts. A caller that receives a 422 has no answer to read, and it should not look for a team in that body.

The second kind of request is a message too long to read in full. The model reads a message as tokens, which are pieces of text, and a long message has more of them. The function classify calls the tokenizer with truncation on and max_length set to 128. A message longer than 128 tokens is cut at 128 before the model reads it. The route does not check the length, and its answer does not say that a cut happened. The same 128 was used in training: the script that recorded banking77-lora-v1, recordings/lora_full.py, trains with max_length set to 128. So the cut at serving is the cut the model was trained with, and that is the reason the route uses it.

A shorter cut, at 64 tokens, is a common choice, and the count below shows what it would touch on the test sample of 200 messages, the sample that chapter 5 compared models on. The example prints how many of the 200 messages are longer than each cut. Only the tokenizer loads here, and no model runs.

truncation-count.py Python 3.12.15 · torch 2.15.0+cpu · transformers 5.23.0 合格
"""Count the test_200 messages over 64 tokens and over the 128 that classify() cuts at, then show the cut on one longmessage. The prose's point rests on the 128-token line and the before and after lengths; only the tokenizer loads."""import osos.environ["HF_HUB_OFFLINE"] = "1"os.environ["TRANSFORMERS_OFFLINE"] = "1"import json  # noqa: E402import torch  # noqa: E402torch.set_num_threads(2)from transformers import AutoTokenizer  # noqa: E402import router_lib  # noqa: E402router_lib.setup_runtime()RECORDED = router_lib.HERE / "data" / "recorded" / "lora-full"repo = json.loads((RECORDED / "adapter" / "adapter_config.json").read_text())["base_model_name_or_path"]  # the adapter's base modeltokenizer = AutoTokenizer.from_pretrained(repo, revision=router_lib.pinned_revision(repo))  # the pinned revision the model usestest = router_lib.read_rows("test")         # each row is (message, gold label index)sample = router_lib.read_sample("test_200") # row numbers of the committed samplelengths = [len(tokenizer(test[i][0]).input_ids) for i in sample]  # full length in tokens, before any cutn = len(lengths)print(f"messages over 64 tokens: {sum(x > 64 for x in lengths)}/{n}")print(f"messages over 128 tokens where classify() cuts: {sum(x > 128 for x in lengths)}/{n}")# The cut itself: repeat the text of the first test_200 message until it is longer than 128 tokens,# then tokenize it with classify()'s settings (truncation on, max_length 128).long_text = test[sample[0]][0]while len(tokenizer(long_text).input_ids) <= 128:  # repeat the first message until it runs past the 128-token cut    long_text = long_text + " " + test[sample[0]][0]before = len(tokenizer(long_text).input_ids)after = len(tokenizer(long_text, truncation=True, max_length=128).input_ids)  # the settings classify() passesprint(f"repeated message tokens before the cut: {before}")print(f"repeated message tokens after the cut: {after}")print(f"truncation side: {tokenizer.truncation_side}")  # "right" cuts from the end of the text
出力python truncation-count.py
messages over 64 tokens: 1/200
messages over 128 tokens where classify() cuts: 0/200
repeated message tokens before the cut: 132
repeated message tokens after the cut: 128
truncation side: right

On this sample, a cut at 64 tokens would touch 1/200 messages, and the cut at 128 tokens, the one classify applies, would touch 0/200. Like the route test, this is one sample. It does not say how often long messages occur in a different inbox, and that rate has to be counted on the reader's own messages.

The example's second half shows what the cut does to a message that is long. It repeats the text of the first test_200 message until the text is longer than 128 tokens, then tokenizes it with the settings classify uses. The message reaches the model as 128 tokens, down from 132. The tokenizer's truncation side is right, so the cut drops the end of the text and keeps its start.

A reader whose messages run longer than this sample has to count them before serving, and the route will not count them for the reader. The route does not reject a long message. It cuts the message, scores what is left, and returns a team when the flag is false, and nothing in the answer shows that a cut happened. So the check belongs before the route, in the caller's hands. We recommend treating a message the route would cut as a message for a person, outside the route, and not as a message to guess. A guessed team would look like a routed message and carry no flag, so no one would know to check it. A message the cut touches is scored on its beginning only, and the caller is not told. That is a quiet failure, and the reader should decide what happens to such messages before the route takes them. The safe outcome, which this book recommends, is that a long message goes to a person, outside the route, with the count reported beside the rest of the results.

Working rule: Count the messages longer than the cut before you serve a set of messages, with the tokenizer of the adapter's base model and the same cut the route uses. The route cuts a longer message at 128 tokens and scores only what is left, so when the count is above zero, send those messages to a person outside the route, and report the count with the hand-off rate.

同じプロセス内でルートをテストする

最終変更:版2026.11.8

このルートの規則である「フラグが false の場合にのみチームを返す」は、実際の応答で確かめなければならない。FastAPI のテストクライアントを使えば、サーバを起動せずにそれができる。FastAPI のテストに関するチュートリアルによると、このテストクライアントは httpx と同じように使え、その呼び出しは await を伴わない通常の呼び出しである(FastAPI 0.163.2 のテストに関するチュートリアル)。したがって、テストは通常の Python のループであり、各呼び出しは読み取り可能な応答を返す。

ルートのテストはこのクライアントを使う。記録済みのフォルダからルートを構築し、test_40 の 40 件のメッセージを一件ずつ送り、すべての応答の JSON を読み戻す。uvicorn は起動せず、メッセージの本文も出力しない。すべての応答がステータス 200 で返り、テストは最初の応答のキーを出力する。そのキーは、最初の節に挙げた五つのフィールドである。出力される件数は、ルートの規則から予測される件数と一致する。その内訳は、引き継ぎ件数、フラグが立っているのにチームがないメッセージ、保持されたメッセージのうち正解のチームを持つもの、一覧に含まれないチーム名である。テストはまた、message を持たない本文を送り、その応答のステータスを出力し、detail フィールドがリストであることをアサートする。

テストがサーバを起動しないのは、意図した選択である。テスト内でサーバを起動すると、空きポート、起動の待機、正常な停止が必要になり、そのどれもが引き継ぎ規則とは無関係な理由で失敗しうる。稼働中のサーバに対する確認を望む読者は、同じ 40 件のメッセージをそのサーバに送り、その件数をここでの件数と比較すればよい。出力は実行のたびに同じになる。テストがルートの構築前に呼び出す setup_runtime が、シードを固定し、決定論的アルゴリズムを必須とし、既定の型を float32 に設定するからである。テストを再実行して異なる件数が得られた読者は、モデル、データ、環境のいずれかに変化があったことを見つけたのであり、ルートを信頼する前に、作業を止めてそのどれであるかを突き止めるべきである。

フラグとチームは、サンプル内のすべての応答について合わせて検査される。フラグが立った応答にはチームがなく、保持された応答にはチームがある。ステータスコードだけを検査するテストは、すべてのメッセージにチームを返すルートも通してしまい、フラグをまったく検査しないことになる。そのため、テストは両方の件数を出力する。

実践ルール: コミット済みのサンプルに対して、テストクライアントを通してルートをテストし、フラグとチームを結び付ける件数を出力する。その件数とは、引き継がれたメッセージの数、そのうちチームがないものの数、一覧に含まれないチーム名の数である。ステータスコードだけを検査するテストは、引き継ぎ規則が成り立つことを示さない。テストが主張する各事項には、その裏付けとなる出力行を一行ずつ用意すべきである。出力行は、本書が引用でき、読者が再実行できるものだからである。出力行のない主張は、読者が鵜呑みにするしかない主張である。

本番で何がうまくいかなくなるか

最終変更:版2026.11.2

テストを通過したルートでも、サーバの下で動かすと失敗することがあり、テストはその失敗を示さない。テストは、コミット済みのサンプルに対して、コードの現状のまま一度だけ実行される。本番は、サービスが動いている限り続き、誰もサンプリングしていないメッセージを処理し、しかも複数のプロセスで動くことが多い。以下の失敗はいずれも、サンプルは正しいのにサービスは誤っているという状況が生じる経路である。

第一は、モデルのコピーである。この章のルートが動かされることを想定しているサーバ uvicorn のデプロイページには、「Unlike gunicorn, uvicorn does not use pre-fork, but uses spawn」とある(uvicorn 0.54.0 deployment guide)。spawn されたワーカーは新しい Python プロセスである。以下のモジュールは uvicorn がインポートするときにアプリを構築するため、インポートした各ワーカーがそれぞれ自分用のモデルのコピーを読み込む。本書は spawn の引用をこの意味に読む。ただし、コピー1つが消費するメモリは、この章では測定していない。読者は、実行するワーカー数を決める前に、コピーの数を数えるべきである。つまり、ワーカープロセスの数に、自分のマシンでのモデルのフットプリントを掛けた値である。

router_lib と data がある examples フォルダから実行すると、uvicorn がインポートするモジュールは、設定の1行とアプリの1行からなる。

# serve_route.py
import router_lib

app = router_lib.make_app("data/recorded/lora-full", threads=2)

コマンドは uvicorn serve_route:app である。uvicorn はアプリケーションを "<module>:<attribute>" の形で受け取る。同じタグの設定ページも、APP をこの形式で示している。

第二は、2つのオプションの競合である。同じページには「The --reload and --workers arguments are mutually exclusive.」とある。自動リロードを使って開発する読者は、同じコマンドで複数のワーカーを実行できない。複数のワーカーを実行する読者はリロードなしで動かすことになるので、コードを変更したら再起動が必要になる。どちらの事実もサーバ自身のページに書かれており、どちらも読者の運用手順書に記しておくべきである。

第三は、スレッドである。各ワーカープロセスは、自身の make_app 呼び出しが求めるスレッド数を設定するので、スレッドの総数はワーカー数に応じて増える。本書が予算とする2 vCPU では、ワーカー1つにつき2スレッドなら、ワーカーは1つになる。ワーカーを増やす前にスレッドの総数を数え、その総数をマシンのコア数以下に保つことを勧める。これは経験則である。総数がコア数を超えたときに何が起きるかは、この章では測定しておらず、それについて数値を主張することもしない。

第四は、引き継ぎ率である。フラグは、5章が開発分割で選んだしきい値と、受信箱が送ってくるメッセージに左右される。ルートはすべての回答でフラグを返すので、フラグが立ったメッセージの割合は、ルート自身の出力から数えられる。この割合が動いても、ルートは理由を説明できない。受信箱のメッセージが変わったのか、モデルが変わったのか、しきい値が編集されたのかは、回答からは分からない。9章はこの割合を監視し、バージョンと、人へのフォールバックを追加する。

第五は、長いメッセージであり、ルートが採点できないものについての節で扱っている。128トークンでの切り詰めはそのことを知らせないので、上記の件数(切り詰められるメッセージの数)は、ルートが実際に受け取るメッセージで改めて数える必要がある。

第六は、記録がないことである。フラグを返しても、ログにはステータスコードしか残さないルートでは、変更の後に引き継ぎ率がどう動いたかを示せない。各回答を、フラグ、アダプタ、バージョンとともにログに記録し、テストからだけでなくログからも割合を数えられるようにすることを勧める。

この章で確定したこと:

  • ルートはすべての回答でフラグを返し、チームはフラグが偽のときに限って返す。
  • ルートは banking77-lora-v1 を float32 で提供し、しきい値はそのマニフェストから読み取る。
  • make_app は、モデルを読み込む前に、アダプタのファイルとそのベースのピンをマニフェストと照合し、不一致ならアプリを構築しない(9章)。
  • ルートは、モデルを学習したときの長さである128トークンで各メッセージを切り詰める。
  • 各ワーカープロセスはモデルを1つ保持し、2スレッドで構築する。これは2 vCPU の予算に対する本書の選択である。
  • ルートが報告するバージョンは、アダプタ名の接尾辞である。

引き継ぎが成立するか失敗するかはルートで決まるので、フラグはルートが計算する。

実践ルール: ワーカープロセスごとにモデルを1つ動かし、自分のマシンで測定したスレッド数で構築すること。自分の測定が別の結果を示すまでは、本書のとおりワーカーごとに2スレッドとする。マシン上のモデルのメモリを数える前に、ワーカープロセスの数を数え、--reload と --workers は併用しないこと。ルートがメッセージの処理を始めた初日から、エラーと並べて、ルートが返す引き継ぎ率を監視すること。

この版における本章

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

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

この節を引用する

形式

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

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

このページの内容

全10章中の第8章: ルータを CPU で提供する:ハンドオフをルートの内側に置く

  1. One route that returns the hand-off
  2. モデルは起動時に一度だけ読み込む
  3. Know what the route cannot score
  4. 同じプロセス内でルートをテストする
  5. 本番で何がうまくいかなくなるか

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