在 CPU 上部署路由器,把转人工的判断放进路由内部

阅读约需 36分钟 分钟,5节中含2个示例。

版次 2026.11.9 示例于 2026年11月20日 通过 36个示例中有36个通过 变化内容

AI 翻译。由人工以英文核验。 我们如何制作图书

译自英文版图书,版次 2026.11.9。 阅读原文

读完本章,你可以把路由器部署为一个 POST /route 端点,对每条消息返回团队、置信度和转人工标志。你还可以测试:对于已经转交人工的消息,该路由绝不会返回团队。

路由就是转人工规则成立或失效的地方。第 1 章界定了各个团队,第 5 章构建了一个能在一次前向传播中给出团队和置信度的分类头,并选定了决定消息何时交给人工的阈值。本章把这个模型放在一个 HTTP 路由之后,收件箱的软件通过该路由发送消息,并读回团队或转人工的结果。

如果调用方能从路由中为路由器已标记的消息取得团队,那么无论第 5 章如何仔细地选择阈值,这个标志都起不到任何作用。因此,路由自己计算该标志,所用的结果与团队来自同一个答案,并且只在标志为假时才返回团队。本章中没有任何内容比这条规则更重要。

本章部署的是 float32 适配器,即第 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 会对照清单检查适配器的文件,并对照清单中记录的固定版本检查基础模型的修订版本。只要有任何一处不一致,它就会抛出错误,不构建应用。这项检查来自第 9 章,本章依赖它。检查通过后,make_app 读取清单,再用 load_classifier 加载分词器和模型,然后才定义路由。路由函数本身只调用 classify,随后调用 handoff。因此,模型在构建应用时加载,每个请求使用的都是已经在内存中的模型。

路由测试只构建一次应用,并把全部 40 条消息发送给这同一个应用,所以这 40 个请求共用一次加载。加载是构建应用的一部分,而不是调用方要执行的步骤,调用方无法通过发送请求让路由再加载一份副本。

线程数是另一项应当在启动时确定的设置。make_app 通过 threads 参数接收线程数,默认值为二,并在加载模型之前以该数值调用 torch.set_num_threads。因此,每个构建应用的进程都会在第一次调用模型之前设置好线程数。PyTorch 文档指出,该调用设置的是 CPU 上的算子内线程数,并且若要使该数值生效,"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,即文本片段)为单位读取消息,消息越长,词元越多。函数 classify 调用分词器时开启了截断,并将 max_length 设为 128。超过 128 个词元的消息,在模型读取之前会在第 128 个词元处被截断。路由不检查长度,其返回结果也不会说明发生过截断。训练时使用的也是同样的 128:记录 banking77-lora-v1 的脚本 recordings/lora_full.py 在训练时将 max_length 设为 128。因此,服务时的截断与模型训练时的截断一致,这就是路由采用该设置的原因。

更短的截断长度,例如 64 个词元,是一种常见的选择。下面的统计显示它会影响 200 条消息的测试样本中的多少条,这一样本正是第 5 章用来比较模型的样本。该示例会输出 200 条消息中长于各截断长度的消息数量。这里只加载分词器,不运行任何模型。

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 个词元的截断会影响 1/200 条消息,而 classify 实际采用的 128 个词元的截断会影响 0/200 条。与路由测试一样,这只是一个样本。它并不能说明在另一个收件箱中长消息出现的频率,该比例需要读者在自己的消息上统计。

示例的后半部分展示了截断对长消息的影响。它把第一条 test_200 消息的文本反复拼接,直到文本超过 128 个词元,然后用 classify 所用的设置对其分词。这条消息到达模型时为 128 个词元,而截断前为 132 个。分词器的截断方向是 right,因此截断会丢弃文本的末尾,保留开头。

消息比这一样本更长的读者,必须在服务之前先统计,路由不会代为统计。路由不会拒绝长消息。它会截断消息,对剩余部分评分,并在标志为 false 时返回一个团队,而返回结果中没有任何迹象表明发生过截断。因此,检查应当放在路由之前,由调用方负责。我们建议,把路由会截断的消息当作应在路由之外交给人处理的消息,而不要去猜测。猜出的团队看起来就像已路由的消息,又不带标志,没有人会想到去检查。被截断影响的消息只依据其开头部分评分,而调用方并不知情。这是一种悄无声息的失败,读者应当在路由接收这些消息之前,决定如何处理它们。本书推荐的安全做法是:长消息在路由之外交给人处理,并将其数量与其余结果一并报告。

工作准则: 在对一批消息提供服务之前,使用适配器基础模型的分词器和路由所用的同一截断长度,统计长于截断长度的消息数量。路由会在 128 个词元处截断更长的消息,并只对剩余部分评分,因此当数量大于零时,应把这些消息在路由之外交给人处理,并将该数量与移交率一并报告。

在同一进程中测试路由

最近一次修改见于版次 2026.11.8

路由的规则是:只有标记为假时才给出团队。这条规则必须用真实的响应来检验,而 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)出的工作进程是一个新的 Python 进程。下面的模块在 uvicorn 导入它时构建应用,因此每个导入它的工作进程都会加载自己的一份模型副本。我们把这句关于 spawn 的引文理解为上述含义,本章并未测量一份副本占用多少内存。读者应当先数清副本的数量,即工作进程的数量乘以模型在自己机器上的占用,然后再决定运行多少个工作进程。

在示例文件夹中运行,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.”开发时使用自动重载的读者,无法在同一条命令中运行多个工作进程。运行多个工作进程的读者,则是在不带重载的状态下运行,因此修改代码后需要重启。这两个事实都出自服务器自己的页面,都应当写进读者的运维手册。

第三种是线程。每个工作进程会按其 make_app 调用所要求的数量设置线程数,因此线程总数随工作进程的数量增长。本书预算的是两个 vCPU,每个工作进程两个线程,意味着只能有一个工作进程。我们建议读者在增加工作进程之前先数一数线程总数,并使总数不超过机器的核数。这是一条经验法则。本章没有测量总数超过核数时会发生什么,也不对此给出任何数字。

第四种是转交率。该标志取决于第 5 章在开发集上选定的阈值,也取决于收件箱发来的消息。路由在每次回答中都返回该标志,因此被标记消息的比率可以由路由自己的输出统计出来。如果这个比率发生变化,路由无法说明原因。它的回答不能表明是收件箱的消息变了、模型变了,还是阈值被改动了。第 9 章会监测这个比率,并加入版本和转交给人的后备机制。

第五种是长消息,关于路由无法评分的内容的那一节讨论了这一问题。在 128 个词元处的截断不会自行提示,因此上面的计数必须在路由实际收到的消息上重新进行。

第六种是缺少记录。一条返回了标志却只记录状态码的路由,在变更之后无法说明转交率是如何变化的。我们建议每次回答都连同其标志、适配器和版本一起记录,这样转交率既可以由测试统计,也可以由日志统计。

本章确定的内容:

  • 路由在每次回答中都返回该标志,只有当标志为假时才转交给团队。
  • 路由以 float32 提供 banking77-lora-v1,阈值从其清单中读取。
  • 在加载模型之前,make_app 会对照清单检查适配器的文件及其基座版本固定值,不匹配时不构建任何应用(第 9 章)。
  • 路由将每条消息截断为 128 个词元,即模型训练时所用的长度。
  • 每个工作进程持有一个模型,并以两个线程构建它,这是本书针对两个 vCPU 预算所做的选择。
  • 路由报告的版本是适配器名称的后缀。

转交成败取决于路由,因此由路由计算该标志。

工作准则: 每个工作进程运行一个模型,并按你在自己机器上测得的线程数构建。在你自己的测量另有结论之前,沿用本书的做法,每个工作进程两个线程。先数工作进程的数量,再计算模型在机器上占用的内存,并且不要同时使用 --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. 生产环境中会出什么问题

返回顶部全部章节