在 CPU 上提供路由器服務,並將轉人工處理的判斷放在路由內

閱讀約需 37 分鐘 分鐘,5 節 中共有 2 個範例。

版次 2026.11.9 範例於 2026年11 月 20 通過測試 36 個範例中有 36 個通過 變更內容

由 AI 翻譯。經人工以英文驗證。 我們如何製作書籍

譯自英文書,版次 2026.11.9。 閱讀原文

讀完本章後,你能把路由器以單一的 POST /route 端點提供服務,針對每則訊息回傳團隊、信心值與轉人工處理的旗標。你也能測試:對於已轉人工處理的訊息,這個路由絕不會回傳團隊。

轉人工處理的規則,是否能成立,取決於路由這一層。第 1 章說明了各個團隊,第 5 章建立了一個只需一次前向傳遞就能給出團隊與信心值的分類頭,並選定了決定訊息何時交給人處理的門檻。本章把這個模型放在 HTTP 路由之後,收件匣的軟體會把訊息送到這個路由,並讀回團隊或轉人工處理的結果。

如果呼叫端能針對路由器已標記的訊息,從路由取得團隊,那麼無論第 5 章多謹慎地選定門檻,這個旗標都不會發揮作用。因此,路由會自行根據與團隊相同的答案計算旗標,而且只有在旗標為 false 時才回傳團隊。本章中沒有任何其他內容比這條規則更重要。

本章提供服務的是 float32 的介接器(adapter),也就是第 5 章從記錄中原樣取得的那一個。第 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 會先對照清單檔(manifest)檢查轉接器(adapter)的檔案,並對照清單檔所記錄的固定版本,檢查基礎模型的修訂版本。只要有任何不符,它就會拋出錯誤,不建立應用程式。這項檢查出自第 9 章,本章仰賴它。檢查通過後,make_app 會讀取清單檔,接著以 load_classifier 載入分詞器與模型,最後才定義路由。路由函式本身只呼叫 classify,再呼叫 handoff。因此模型是在建立應用程式時載入的,每次請求使用的都是已在記憶體中的模型。

路由測試只建立一次應用程式,並把全部 40 則訊息送給這同一個應用程式,所以這 40 次請求共用同一次載入。載入屬於建立應用程式的一部分,不是呼叫端所採取的步驟,呼叫端也無法藉由送出請求,讓路由再載入第二份模型。

執行緒數量是另一項應在啟動時設定的項目。make_app 以 threads 引數接收執行緒數量,預設為二,並在載入模型之前,以該數量呼叫 torch.set_num_threads。因此每個建立應用程式的行程,都會在第一次呼叫模型之前設定好執行緒。PyTorch 文件指出,這個呼叫設定的是 CPU 上的運算元內(intra-op)執行緒數量,而且若要讓該數量生效,「set_num_threads must be called before running eager, JIT or autograd code」(torch 2.15.0+cpu 文件)。

set_num_threads 設定涵蓋的是單一運算內部所用的執行緒,也就是文件所稱的運算元內執行緒。兩個執行緒是本書的選擇,並非實測得出的最佳值。本書範例的預算是兩個 vCPU,因此書中為它們設定兩個執行緒;使用不同機器的讀者,應自行選定數量並加以量測。這項選擇標示為本書的選擇,因為本章沒有任何輸出比較過不同的執行緒數量。

實用原則: 每個行程只建立一次應用程式,使用該行程應採用的執行緒數量,並在第一次請求之前完成。如同本書所採用的兩個 vCPU 預算,維持預設的兩個執行緒,只有在以自己的機器與自己的訊息量測之後,才選用其他數量。

認識路由無法評分的情況

最近一次變動於第 2026.11.2 版

有兩種請求無法評分,路由對它們的處理方式也不同。第一種是缺少路由所需欄位的請求。路由將請求主體宣告為一個模型,其中只有一個必要欄位 message。缺少該欄位的主體會得到狀態碼 422。路由測試的最後會送出這樣的主體,而回覆中的 detail 欄位是一個清單,測試會對此加以斷言。收到 422 的呼叫端沒有可讀取的答案,也不應在該主體中尋找團隊。

第二種是訊息太長而無法完整讀取的請求。模型以 token(文字片段)來讀取訊息,訊息越長,token 越多。函式 classify 呼叫 tokenizer 時開啟截斷,並將 max_length 設為 128。長度超過 128 個 token 的訊息,會在模型讀取之前於第 128 個 token 處被截斷。路由不會檢查長度,其回答也不會說明是否發生截斷。訓練時使用的也是同樣的 128:錄製 banking77-lora-v1 的指令稿 recordings/lora_full.py,在訓練時將 max_length 設為 128。因此服務時的截斷方式與模型訓練時相同,這也是路由採用此設定的原因。

在 64 個 token 處截斷是常見的選擇,以下的計數顯示在 200 則訊息的測試樣本上,這樣的截斷會影響到哪些訊息;第 5 章就是以這個樣本比較各個模型。此範例會印出 200 則訊息中,長度超過各個截斷點的數量。這裡只載入 tokenizer,不執行任何模型。

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

在這個樣本上,於 64 個 token 處截斷會影響 1/200 則訊息,而 classify 實際採用的 128 個 token 截斷點會影響 0/200 則。如同路由測試,這只是一個樣本。它無法說明在不同的收件匣中長訊息出現的頻率,這個比率必須由讀者針對自己的訊息來計算。

此範例的後半段展示截斷對長訊息造成的影響。它重複第一則 test_200 訊息的文字,直到文字超過 128 個 token,再以 classify 使用的設定進行 tokenize。訊息送達模型時為 128 個 token,原本是 132 個。tokenizer 的截斷方向是 right,因此截斷會捨棄文字的結尾,保留其開頭。

訊息比此樣本更長的讀者,必須在服務之前自行計數,路由不會代為計數。路由不會拒絕長訊息。它會截斷訊息,對剩下的部分評分,並在旗標為 false 時回傳一個團隊,而回答中沒有任何跡象顯示發生過截斷。因此檢查應放在路由之前,由呼叫端負責。我們建議將路由會截斷的訊息,視為應在路由之外交給人員處理的訊息,而不是用來猜測的訊息。猜出的團隊看起來會像已經過路由的訊息,卻沒有旗標,因此沒有人會知道需要檢查。受截斷影響的訊息只依其開頭評分,而呼叫端並未得到通知。這是一種無聲的失敗,讀者應在路由接手這些訊息之前,先決定如何處理它們。本書建議的安全做法是:長訊息在路由之外交給人員處理,並在其餘結果旁一併報告其數量。

實用原則: 在服務一組訊息之前,使用轉接器(adapter)基礎模型的 tokenizer 與路由所用的同一個截斷點,計算長度超過截斷點的訊息數量。路由會在 128 個 token 處截斷較長的訊息,並只對剩下的部分評分,因此當數量大於零時,應將這些訊息在路由之外交給人員處理,並將該數量與轉交率一併報告。

在同一個行程中測試路由

最近一次變動於第 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 部署指南)。以 spawn 產生的 worker 是一個新的 Python 行程。下方的模組在 uvicorn 匯入時建立應用程式,因此每個匯入它的 worker 都會載入自己的一份模型。我們把這段 spawn 的引文解讀為上述意思,本章並未量測一份副本所耗用的記憶體。讀者在決定要執行多少個 worker 之前,應先計算副本數:worker 行程的數量,乘上模型在自己機器上的記憶體占用。

從放有 router_lib 與 data 的範例資料夾執行時,uvicorn 所匯入的模組是一行設定加一行應用程式:

# 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。

第二種是兩個選項之間的衝突。同一頁面寫道:「The --reload and --workers arguments are mutually exclusive.」開發時使用自動重新載入的讀者,無法在同一個指令中執行多個 worker。執行多個 worker 的讀者,則是在不重新載入的情況下執行,因此修改程式碼後需要重新啟動。這兩項事實都出自伺服器自己的頁面,都應該寫進讀者的維運手冊。

第三種是執行緒。每個 worker 行程都會依其 make_app 呼叫的要求設定執行緒數,所以執行緒總數會隨 worker 數量增加。在本書預算的兩個 vCPU 上,每個 worker 兩條執行緒,就表示只能有一個 worker。我們建議讀者在增加 worker 之前先計算執行緒總數,並使總數不超過機器的核心數。這是經驗法則。本章並未量測總數超過核心數時會發生什麼事,也不對此宣稱任何數字。

第四種是交接率。旗標取決於第 5 章在開發分割上選定的門檻,也取決於收件匣送來的訊息。路由在每個回答中都會回傳旗標,因此被標記訊息的比率可以由路由自己的輸出算出。若這個比率改變,路由無法說明原因。它的回答看不出是收件匣的訊息變了、模型變了,還是門檻被修改了。第 9 章會監看這個比率,並為人工交接加上版本與備援機制。

第五種是長訊息,關於路由無法評分之內容的一節對此有所說明。在 128 個 token 處的截斷不會自行提示,所以上述的計數必須在路由實際收到的訊息上重新進行。

第六種是缺少紀錄。若路由回傳旗標,卻只記錄狀態碼,那麼在變更之後,就無法顯示交接率如何變動。我們建議每個回答都連同其旗標、其 adapter 與其版本一併記錄,使這個比率除了從測試得出,也能從日誌算出。

本章已確定的事項:

  • 路由在每個回答中回傳旗標,且只有在旗標為 false 時才交給團隊。
  • 路由以 float32 提供 banking77-lora-v1,門檻則從其 manifest 讀取。
  • 在載入模型之前,make_app 會對照 manifest 檢查 adapter 的檔案及其基礎模型的固定版本,若不相符便不建立任何應用程式(第 9 章)。
  • 路由將每則訊息截斷在 128 個 token,也就是模型訓練時所用的長度。
  • 每個 worker 行程只持有一個模型,並以兩條執行緒建立,這是本書針對兩個 vCPU 預算所做的選擇。
  • 路由回報的版本,是 adapter 名稱的後綴。

交接成敗取決於路由,所以由路由計算旗標。

實用原則: 每個 worker 行程執行一個模型,並以你針對自己機器量測出的執行緒數建立。在你自己的量測另有結論之前,沿用本書的做法,每個 worker 使用兩條執行緒。在計算模型於機器上的記憶體之前,先計算 worker 行程的數量,並避免同時使用 --reload 與 --workers。從路由開始處理訊息的第一天起,除了錯誤之外,也要監看路由回傳的交接率。

本章,於本版次中

版次 2026.11.9範例於 2026年11 月 20 通過測試本章 2 個範例 個範例中有 2 個通過

譯自英文書,版次 2026.11.9。

引用本節

格式

各種格式皆引用英文原書,本譯本即依循該原書。

每種格式都會標示本版。其連結會開啟目前版次,節標題會說明該節內文最後一次變動的時間。存取日期與擷取日期即為你開啟此頁的當日。

本頁內容

第 8 章,共 10 章: 在 CPU 上提供路由器服務,並將轉人工處理的判斷放在路由內

  1. One route that returns the hand-off
  2. 啟動時載入一次模型
  3. 認識路由無法評分的情況
  4. 在同一個行程中測試路由
  5. 正式環境中會出什麼問題

返回頂端所有章節