CPU에서 라우터 서비스하기: 인계를 라우트 안에 두기
읽는 데 약 32분분 걸린다, 5절에 2개 예제이(가) 있음.
AI로 번역함. 영어 원문을 사람이 검증함. 우리가 책을 만드는 방식
영어판 2026.11.9판을 번역한 것이다. 원문 읽기
이 장을 마치면 메시지마다 팀, 신뢰도, 인계 플래그를 반환하는 POST /route 엔드포인트 하나로 라우터를 서비스할 수 있다. 또한 라우트가 인계한 메시지에 대해서는 팀을 절대 반환하지 않는다는 것을 테스트할 수 있다.
인계 규칙이 지켜지는지 깨지는지는 라우트에서 결정된다. 1장에서 팀을 정했고, 5장에서는 한 번의 순전파로 팀과 신뢰도를 내는 헤드를 만들었으며, 메시지를 사람에게 넘길 시점을 정하는 임계값도 골랐다. 이 장에서는 그 모델을 HTTP 라우트 뒤에 둔다. 받은편지함의 소프트웨어는 이 라우트로 메시지를 보내고, 팀 또는 인계 결과를 돌려받는다.
라우터가 플래그를 세운 메시지에 대해 호출자가 라우트에서 팀을 받을 수 있다면, 5장에서 임계값을 아무리 신중하게 골랐더라도 그 플래그는 아무 역할도 하지 못한다. 그래서 라우트는 팀을 구한 것과 같은 답에서 플래그를 직접 계산하고, 플래그가 거짓일 때만 팀을 반환한다. 이 장에서 이 규칙보다 중요한 것은 없다.
이 장에서는 5장에서 녹화본으로부터 가져온 float32 어댑터를 그대로 서비스한다. 7장에서는 가중치만 int8로 만든 사본 banking77-lora-v1-int8을 만들고 그 사본을 측정한다. 이 장에서는 그 사본을 만들지도 측정하지도 않는다. 속도도 전혀 측정하지 않는다. 그 비교는 10장의 녹화본에서 나오며, 이 장의 어떤 내용도 그 결과를 예측하지 않는다.
이 부분은 아직 번역되지 않았으므로 영어로 표시된다.
One route that returns the hand-off
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.
1"""Send the test_40 messages to the one POST /route through TestClient, in process, and print counts that tie the2hand-off flag to the team. The prose's point rests on the "handed off, team is None" line and the "not handed off,3team is the gold label" line; the last checks show the route's answer to a body with no message."""45import os67os.environ["HF_HUB_OFFLINE"] = "1"8os.environ["TRANSFORMERS_OFFLINE"] = "1"910import torch # noqa: E4021112torch.set_num_threads(2)1314from fastapi.testclient import TestClient # noqa: E4021516import router_lib # noqa: E4021718router_lib.setup_runtime() # seeds, deterministic algorithms and float32, so the counts repeat19client = 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 manifest2021test = router_lib.read_rows("test") # each row is (message, gold label index)22sample = router_lib.read_sample("test_40") # row numbers of the committed sample23replies = [client.post("/route", json={"message": test[i][0]}) for i in sample]24bodies = [r.json() for r in replies]25gold = [test[i][1] for i in sample] # gold label indexes; LABELS turns one into a team name2627print(f"responses: {len(replies)}")28print(f"status codes: {sorted({r.status_code for r in replies})}")29print(f"response keys: {sorted(bodies[0])}")30print(f"handed off: {sum(b['handed_off'] for b in bodies)}/{len(bodies)}")31print(f"team names outside the list: {sum(b['team'] is not None and b['team'] not in router_lib.LABELS for b in bodies)}")3233sure = [k for k, b in enumerate(bodies) if not b["handed_off"]] # kept: the route returned a team34unsure = [k for k, b in enumerate(bodies) if b["handed_off"]] # flagged: the route returned no team35print(f"not handed off, team is the gold label: {sum(bodies[k]['team'] == router_lib.LABELS[gold[k]] for k in sure)}/{len(sure)}")36print(f"handed off, team is None: {sum(bodies[k]['team'] is None for k in unsure)}/{len(unsure)}")37print(f"adapter: {bodies[0]['adapter']}")38print(f"version: {bodies[0]['version']}")3940bad = client.post("/route", json={}) # a body with no message field, which the route's body model requires41detail_is_list = isinstance(bad.json()["detail"], list)42assert detail_is_list, "a body with no message should get a 422 whose detail is a list"43print(f"status on an empty body: {bad.status_code}")44print(f"detail is a list: {'yes' if detail_is_list else 'no'}")
python serve-route-testclient.pyresponses: 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.
이 부분은 아직 번역되지 않았으므로 영어로 표시된다.
Load the model once at startup
A route that loaded the model for each request would repeat the same work on every message. The route in this chapter does not, and the reason is where the code sits. Before it loads anything, the function make_app checks the adapter's files against its manifest, and it checks the base model's revision against the pin that the manifest records. It raises an error and builds no app on any mismatch. The check is chapter 9's, and this chapter relies on it. After the check, make_app reads the manifest, then loads the tokenizer and the model with load_classifier, and only then does it define the route. The route function itself only calls classify and then handoff. So the model is loaded when the app is built, and each request uses the model that is already in memory.
The route test builds the app once and sends all 40 messages to that one app, so the 40 requests share one load. Loading is part of building the app, not a step a caller takes, and a caller cannot make the route load a second copy by sending a request.
Threads are the other setting that belongs at startup. make_app takes the thread count as its threads argument, which defaults to two, and it calls torch.set_num_threads with that count before it loads the model. So every process that builds the app sets its threads before the first model call. The PyTorch documentation says the call sets the intra-op thread count on the CPU, and that "set_num_threads must be called before running eager, JIT or autograd code" if the count is to hold (torch 2.15.0+cpu documentation).
The set_num_threads setting covers the threads used inside one operation, the intra-op threads the documentation names. Two threads is the book's choice, not a measured best. The book's examples have a budget of two vCPUs, so the book sets two threads for them, and a reader on a different machine should choose a count and measure it. The choice is labelled as the book's, because no output in this chapter compares one thread count with another.
Working rule: Build the app once per process, with the thread count that process should use, and before the first request. On a two-vCPU budget, as this book uses, keep the default of two threads, and choose another count only after you have measured your own machine with your own messages.
이 부분은 아직 번역되지 않았으므로 영어로 표시된다.
Know what the route cannot score
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.
1"""Count the test_200 messages over 64 tokens and over the 128 that classify() cuts at, then show the cut on one long2message. The prose's point rests on the 128-token line and the before and after lengths; only the tokenizer loads."""34import os56os.environ["HF_HUB_OFFLINE"] = "1"7os.environ["TRANSFORMERS_OFFLINE"] = "1"89import json # noqa: E4021011import torch # noqa: E4021213torch.set_num_threads(2)1415from transformers import AutoTokenizer # noqa: E4021617import router_lib # noqa: E4021819router_lib.setup_runtime()20RECORDED = router_lib.HERE / "data" / "recorded" / "lora-full"21repo = json.loads((RECORDED / "adapter" / "adapter_config.json").read_text())["base_model_name_or_path"] # the adapter's base model22tokenizer = AutoTokenizer.from_pretrained(repo, revision=router_lib.pinned_revision(repo)) # the pinned revision the model uses2324test = router_lib.read_rows("test") # each row is (message, gold label index)25sample = router_lib.read_sample("test_200") # row numbers of the committed sample26lengths = [len(tokenizer(test[i][0]).input_ids) for i in sample] # full length in tokens, before any cut27n = len(lengths)28print(f"messages over 64 tokens: {sum(x > 64 for x in lengths)}/{n}")29print(f"messages over 128 tokens where classify() cuts: {sum(x > 128 for x in lengths)}/{n}")3031# The cut itself: repeat the text of the first test_200 message until it is longer than 128 tokens,32# then tokenize it with classify()'s settings (truncation on, max_length 128).33long_text = test[sample[0]][0]34while len(tokenizer(long_text).input_ids) <= 128: # repeat the first message until it runs past the 128-token cut35 long_text = long_text + " " + test[sample[0]][0]36before = len(tokenizer(long_text).input_ids)37after = len(tokenizer(long_text, truncation=True, max_length=128).input_ids) # the settings classify() passes38print(f"repeated message tokens before the cut: {before}")39print(f"repeated message tokens after the cut: {after}")40print(f"truncation side: {tokenizer.truncation_side}") # "right" cuts from the end of the text
python truncation-count.pymessages 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.
같은 프로세스에서 경로 테스트하기
경로의 규칙, 즉 플래그가 거짓일 때만 팀을 반환한다는 규칙은 실제 응답으로 확인해야 한다. FastAPI의 테스트 클라이언트를 쓰면 서버를 시작하지 않고도 테스트에서 이를 확인할 수 있다. FastAPI 테스트 튜토리얼에 따르면 이 테스트 클라이언트는 httpx처럼 사용하며, 클라이언트 호출은 await 없이 하는 일반 호출이다(FastAPI 0.163.2 테스트 튜토리얼). 따라서 테스트는 평범한 Python 반복문이며, 각 호출은 테스트가 읽을 수 있는 응답을 반환한다.
경로 테스트는 이 클라이언트를 사용한다. 기록해 둔 폴더로 경로를 만들고, test_40의 메시지 40개를 하나씩 보낸 뒤, 모든 응답의 JSON을 다시 읽는다. uvicorn은 시작하지 않으며, 메시지 본문도 출력하지 않는다. 모든 응답은 상태 코드 200으로 돌아왔고, 테스트는 첫 번째 응답의 키를 출력한다. 이 키는 첫 번째 절에 나열한 다섯 개의 필드이다. 테스트가 출력하는 개수는 경로의 규칙이 예측하는 값과 같다. 즉 넘겨진 메시지의 수, 팀이 없는 플래그 메시지의 수, 정답 팀을 가진 유지 메시지의 수, 목록에 없는 팀 이름의 수이다. 테스트는 message가 없는 본문도 보내 그 응답의 상태 코드를 출력하고, 그 응답의 detail 필드가 리스트임을 단언한다.
테스트가 서버를 시작하지 않는 것은 의도한 선택이다. 테스트 안에서 서버를 시작하려면 빈 포트, 시작 대기, 깨끗한 종료가 필요하며, 이들은 모두 넘기기 규칙과 무관한 이유로 실패할 수 있다. 실행 중인 서버에 대한 확인을 원하는 독자는 같은 메시지 40개를 그 서버에 보내 개수를 여기의 값과 비교하면 된다. 출력은 실행할 때마다 같다. 테스트가 경로를 만들기 전에 호출하는 setup_runtime가 시드를 고정하고, 결정적 알고리즘을 요구하며, 기본 타입을 float32로 설정하기 때문이다. 테스트를 다시 실행했는데 개수가 다르게 나온 독자는 모델, 데이터, 환경 중 어딘가에 변화가 있음을 발견한 것이므로, 경로를 신뢰하기 전에 멈추고 어느 것인지 찾아야 한다.
플래그와 팀은 표본의 모든 응답에 대해 함께 확인한다. 플래그가 있는 응답에는 팀이 없고, 유지된 응답에는 팀이 있다. 상태 코드만 확인하는 테스트는 모든 메시지에 팀을 반환하는 경로도 통과시키며, 플래그는 아예 놓친다. 그래서 테스트는 두 개수를 모두 출력한다.
작업 규칙: 커밋된 표본으로 테스트 클라이언트를 통해 경로를 테스트하고, 플래그를 팀과 연결하는 개수를 출력한다. 즉 넘겨진 메시지의 수, 그중 팀이 없는 메시지의 수, 목록에 없는 팀 이름의 수이다. 상태 코드만 확인하는 테스트는 넘기기 규칙이 지켜진다는 것을 보여 주지 못한다. 테스트가 내세우는 각 주장에는 출력된 줄이 뒷받침되어야 한다. 그 줄은 책이 인용할 수 있고 독자가 다시 실행할 수 있는 것이기 때문이다. 줄이 없는 주장은 독자가 그대로 믿어야 하는 주장이다.
운영 환경에서 무엇이 잘못되는가
테스트를 통과한 라우트도 서버 위에서 실행되면 실패할 수 있으며, 테스트는 이러한 실패를 보여 주지 않는다. 테스트는 커밋된 표본 하나를 대상으로, 코드가 현재 상태 그대로인 채 한 번 실행된다. 운영 환경은 서비스가 존재하는 한 계속 실행되며, 아무도 표본으로 뽑지 않은 메시지를 처리하고, 흔히 프로세스도 둘 이상이다. 아래의 실패는 모두 표본은 맞는데 서비스는 틀릴 수 있는 경우이다. 첫째는 모델의 사본이다. 이 장의 라우트를 실행하려는 서버인 uvicorn의 배포 문서는 "Unlike gunicorn, uvicorn does not use pre-fork, but uses spawn"이라고 설명한다(uvicorn 0.54.0 배포 안내서). spawn으로 생성된 워커는 새로운 Python 프로세스이다. 아래 모듈은 uvicorn이 가져올 때 앱을 만들므로, 이를 가져오는 워커마다 자기만의 모델 사본을 적재한다. 우리는 spawn에 관한 이 인용문을 그런 뜻으로 읽으며, 사본 하나가 차지하는 메모리는 이 장에서 측정하지 않는다. 독자는 몇 개의 워커를 실행할지 정하기 전에 사본의 수, 곧 워커 프로세스의 수에 자기 기기에서의 모델 점유량을 곱한 값을 계산해야 한다.
router_lib와 data가 있는 examples 폴더에서 실행하면, 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 토큰에서 자르는 일은 스스로 알리지 않으므로, 위의 개수는 라우트가 실제로 받는 메시지를 대상으로 다시 세어야 한다.
여섯째는 기록의 부재이다. 플래그는 돌려주지만 상태 코드만 로그에 남기는 라우트는 변경 후에 인계 비율이 어떻게 움직였는지 보여 줄 수 없다. 각 응답을 플래그, 어댑터, 버전과 함께 로그에 남겨, 테스트뿐 아니라 로그로도 그 비율을 셀 수 있게 하기를 권한다.
이 장에서 확정한 내용은 다음과 같다.
- 라우트는 모든 응답에 플래그를 담아 돌려주며, 플래그가 거짓일 때만 팀을 돌려준다.
- 라우트는
banking77-lora-v1를 float32로 서비스하며, 임계값은 매니페스트에서 읽는다. make_app는 모델을 적재하기 전에 어댑터의 파일과 기반 모델 고정값을 매니페스트와 대조하며, 일치하지 않으면 앱을 만들지 않는다(9장).- 라우트는 각 메시지를 모델이 학습된 길이인 128 토큰에서 자른다.
- 각 워커 프로세스는 모델 하나를 유지하며 스레드 두 개로 만든다. 이는 vCPU 두 개의 예산에 대해 이 책이 고른 값이다.
- 라우트가 보고하는 버전은 어댑터 이름의 접미사이다.
인계는 라우트에서 성립하거나 실패하므로, 플래그는 라우트가 계산한다.
작업 규칙: 워커 프로세스마다 모델 하나를 실행하고, 자기 기기에서 측정한 스레드 수로 만든다. 직접 측정한 결과가 달리 말해 주기 전까지는 이 책처럼 워커당 스레드를 둘로 유지한다. 기기에서 모델의 메모리를 세기 전에 워커 프로세스의 수를 먼저 세고, --reload와 --workers를 함께 쓰지 않는다. 라우트가 메시지를 처리하기 시작한 첫날부터, 라우트가 돌려주는 인계 비율을 오류와 나란히 관찰한다.
이 판의 이 장
2026.11.9판예제 통과 2026년 11월 20이 장에서 2개 예제개 중 2개가 통과한다
영어판 2026.11.9판을 번역한 것이다.