라우터의 버전을 관리하고, 인계를 지켜보고, 사람에게 되돌린다
읽는 데 약 31분분 걸린다, 8절에 4개 예제이(가) 있음.
AI로 번역함. 영어 원문을 사람이 검증함. 우리가 책을 만드는 방식
영어판 2026.11.9판을 번역한 것이다. 원문 읽기
이 장을 마치면 라우터의 답을 만드는 구성 요소로 라우터를 식별하고, 경로가 구성 요소를 불러오기 전에 그것을 검사하고, 메시지 구간마다 인계율을 정해진 기준선과 비교하여 세고, 인계된 각 메시지가 어디로 가는지 말할 수 있다.
8장에서는 라우터를 경로 뒤에 두었고, 각 답에는 메시지를 사람에게 보내는 팀이나 플래그가 담긴다. 경로가 은행의 지원 메시지를 몇 달 동안 받으면 경로 혼자서는 답할 수 없는 질문이 세 가지 생긴다. 어느 모델이 답하고 있는가? 그 모델의 파일은 검사를 거친 파일인가? 라우터가 인계하는 메시지는 늘고 있는가, 줄고 있는가? 이 장은 각 질문에 통제 수단 하나와 출력되는 집계 하나를 붙인다. 이 통제 수단은 이 책이 직접 만든 것이다.
이 장은 자체 모델을 운영할 때 추가로 생기는 일, 곧 버전, 사람에게 넘기는 대체 처리, 재학습을 다룬다. 대시보드, 로그, 경보를 갖춘 서비스 전반의 감시는 프로덕션 모니터링을 다루는 책에서 다룰 내용이다. 이 장은 그 내용을 되풀이하지 않는다.
라우터를 구성 요소로 명명하기
라우터는 모델 하나만을 뜻하지 않는다. 라우터는 기반 모델, 그 기반 위에서 학습한 어댑터, 메시지를 사람에게 넘기는 임곗값, 그리고 어댑터를 만든 데이터와 레시피로 이루어진다. 이 가운데 하나라도 다른 두 라우터는 같은 메시지에 다르게 답할 수 있다. "라우터"라고만 적힌 로그 한 줄로는 둘을 구별할 수 없다.
어댑터 파일에는 기반 모델이 들어 있지 않다. PEFT 체크포인트 가이드는 저장된 가중치에 어댑터 모듈의 매개변수만 들어 있고 기반 모델의 것은 하나도 없다고 설명한다. 따라서 어댑터는 자신이 학습된 기반 모델을 이름으로 밝혀야 하며, 그 이름은 정확해야 한다. 이 책은 짧은 커밋 해시로는 충분하지 않으므로 examples/models.toml의 핀, 곧 커밋으로 기반 모델을 지정한다. Hugging Face 다운로드 가이드(v2.4.0)는 커밋을 지정할 때 전체 길이의 해시를 요구한다. 리비전을 지정하지 않으면 다운로드는 main 브랜치가 가리키는 내용을 그대로 가져온다. 브랜치 이름은 브랜치를 따라 움직이므로 핀이 아니다. 5장은 기반 모델의 리비전을 어댑터의 매니페스트에 임곗값, 데이터 커밋, 레시피 해시와 나란히 기록했다.
버전은 이름에 적는다. banking77-lora-v1는 기록된 LoRA 어댑터로, 개발 분할에 속하지 않는 학습 행으로 한 에폭 학습했으며 버전은 1이다. 같은 레시피를 새로 기록하면 v2가 되고, 이것은 고유한 이름과 고유한 매니페스트를 가진다. 매니페스트에는 별도의 버전 필드가 없다. 이름이 곧 버전이며, 8장의 라우트는 어댑터 이름의 접미사를 버전으로 보고한다. banking77-lora-v1의 접미사는 v1이다. 7장의 int8 사본은 별개의 모델인 banking77-lora-v1-int8이며, 이 라우트는 그것을 서빙하지 않는다. 그 접미사는 int8로 읽힐 것이므로, 이름으로 서빙하는 사본에는 자체 버전 필드가 필요하다.
첫 번째 점검은 매니페스트를 읽어 그 기반 리비전을 핀과 비교한다. 먼저 어댑터의 이름을 출력하고, 이어서 비교 결과를 출력한다.
1"""Show what the adapter check does before a route loads an adapter, and what it does to two edited copies.2The point rests on the "route may load" line and on the two "refused by make_app" lines."""3import os45os.environ["HF_HUB_OFFLINE"] = "1"6os.environ["TRANSFORMERS_OFFLINE"] = "1"7import tempfile # noqa: E4028import warnings # noqa: E4029from pathlib import Path # noqa: E4021011import torch # noqa: E4021213torch.set_num_threads(2)1415import router_lib # noqa: E4021617router_lib.setup_runtime()18RECORDED = router_lib.HERE / "data" / "recorded" / "lora-full"19# check_adapter hashes the manifest, the outputs and the LoRA settings; pinned is the manifest's digest matching its pin20manifest, s_ok, s_n, f_ok, f_n, pinned = router_lib.check_adapter(RECORDED)21# the base pin in models.toml, compared with the manifest's base revision22base = router_lib.pinned_revision(manifest["model"]) == manifest["model_version"]23print(f"adapter: {manifest['adapter']}")24print(f"base revision matches pin: {'yes' if base else 'no'}")25print(f"manifest matches pin: {'yes' if pinned else 'no'}")26print(f"settings matching: {s_ok}/{s_n}")27print(f"files matching: {f_ok}/{f_n}")28print("route may load: " + ("yes" if base and pinned and s_ok == s_n and f_ok == f_n else "no"))29with tempfile.TemporaryDirectory() as tmp:30 # changes a manifest field that is neither a LoRA setting nor an output file, so only the manifest digest sees it31 threshold = router_lib.edited_copy(RECORDED, Path(tmp) / "threshold", "manifest.json", "handoff_threshold", 0.0)32 # adds a key that LoraConfig does not know, to the config the settings are read from33 extra = router_lib.edited_copy(RECORDED, Path(tmp) / "extra", "adapter/adapter_config.json", "future_key", 1)34 for label, folder in [("threshold copy", threshold), ("extra-key copy", extra)]:35 _, s_ok, s_n, f_ok, f_n, pinned = router_lib.check_adapter(folder)36 print(f"{label}: manifest matches pin {'yes' if pinned else 'no'}, settings {s_ok}/{s_n}, files {f_ok}/{f_n}")37 print(f"{label} refused by make_app: {'yes' if router_lib.refused_by_make_app(folder) else 'no'}")38 with warnings.catch_warnings(record=True) as caught:39 warnings.simplefilter("always")40 router_lib.load_classifier(extra / "adapter")41 named = [w for w in caught if "future_key" in str(w.message)] # only the warning about the extra key42 print(f"warnings naming the extra key while PEFT loads the copy: {len(named)}")43 # the warning's first sentence: the text up to the first ". " in its message44 print(f"that warning: {named[0].category.__name__}: {str(named[0].message).split('. ')[0]}.")
python adapter-manifest-check.pyadapter: banking77-lora-v1
base revision matches pin: yes
manifest matches pin: yes
settings matching: 3/3
files matching: 3/3
route may load: yes
threshold copy: manifest matches pin no, settings 3/3, files 3/3
threshold copy refused by make_app: yes
extra-key copy: manifest matches pin yes, settings 3/3, files 2/3
extra-key copy refused by make_app: yes
warnings naming the extra key while PEFT loads the copy: 1
that warning: UserWarning: Unexpected keyword arguments ['future_key'] for class LoraConfig, these are ignored.
이름에는 버전이 들어 있고(banking77-lora-v1), 기반 리비전은 핀과 일치한다(yes). 이 두 가지는 파일을 하나도 읽기 전에 독자가 핀과 대조해 확인할 수 있는 구성 요소다.
작업 규칙: 라우터는 기반 리비전, 버전이 들어 있는 어댑터 이름, 데이터 커밋, 임곗값, 레시피 해시로 명명하고, 라우트가 서빙하기 전에 이 다섯 가지를 모두 어댑터의 매니페스트에 기록한다. 어댑터를 불러올 때마다 매니페스트의 기반 리비전을 examples/models.toml의 핀과 비교한다. 핀이 움직였다면 기반 모델이 달라졌다는 뜻이므로, 어댑터는 서빙하기 전에 새로 점검해야 한다.
어댑터의 파일을 매니페스트와 대조하여 확인한다
로드는 버전 확인이 아니다. PEFT 체크포인트 가이드에 따르면 LoRA 설정의 항목 대부분은 모델을 로드하는 데 필요하지 않으므로, 누군가 손으로 바꾼 설정으로도 로드가 성공할 수 있다. 로드가 성공했다고 해서 그 어댑터가 고정된 어댑터라는 것이 입증되지는 않는다. 아래의 추가 키 사본도 여전히 로드되며, 이때 로드는 추가된 키를 지목하는 경고를 발생시킨다. 기반 모델이 일치하지 않으면 연구용 탐침에서는 상태 사전 오류와 함께 로드 자체가 실패한다. 이 예제는 그 경우를 출력하지 않는다.
그래서 이 검사는 어댑터를 매니페스트와 세 부분으로 비교한다. 먼저 manifest.json의 SHA-256을 직접 계산하고, 이를 examples/adapter-pins.json에서 어댑터 이름에 대해 고정된 다이제스트와 비교한다. 이 고정값은 임계값, 기반 리비전, 출력 다이제스트를 포함하여 매니페스트가 담은 모든 필드를 포괄한다. 다음으로 매니페스트에 나열된 각 출력 파일의 SHA-256을 계산하고, 매니페스트에 기록된 다이제스트와 비교한다. 또한 설정에 있는 세 가지 LoRA 설정, 즉 랭크, 스케일링을 정하는 알파, 대상 계층을 읽어 매니페스트와 비교한다. 출력되는 줄은 각 항목이 몇 개 일치하는지, 그리고 라우트가 해당 폴더를 로드해도 되는지를 알려 준다.
기록된 어댑터의 경우 매니페스트는 고정값과 일치하고(yes), 설정 3/3개와 파일 3/3개가 일치하므로 라우트는 이를 로드해도 된다.
검사는 편집된 사본 두 개에도 실행되며, 각각 자기 줄을 얻는다. 첫 번째 사본은 매니페스트에서 handoff_threshold를 0으로 바꾼 것이며, 그 줄은 manifest matches pin no, settings 3/3, files 3/3이다. 임계값은 설정이 아니고 바뀐 출력 파일도 없으므로, 이 사본의 설정과 파일은 여전히 일치한다. 변경을 알아차리는 것은 매니페스트 자체의 다이제스트뿐이며, 그래서 이 사본은 거부된다. 두 번째 사본은 설정에 추가 키를 하나 넣은 것이며, 그 줄은 manifest matches pin yes, settings 3/3, files 2/3이다. 설정은 여전히 일치하지만, 설정 파일의 해시가 더 이상 맞지 않으므로 파일 검사가 이 사본을 거부한다. PEFT는 그래도 이 사본을 로드하며, 로드가 발생시키는 경고 중 1이 추가된 키를 지목한다. 전문은 다음과 같다. UserWarning: Unexpected keyword arguments ['future_key'] for class LoraConfig, these are ignored. 로드는 그 키를 무시한 모델을 반환하며, 그 키에 대해 PEFT가 알려 주는 것은 이 경고뿐이다. 경고는 거부가 아니다. 사본을 거부하는 것은 이 검사다.
8장의 라우트가 이 검사를 실행한다. 그 make_app는 모델을 로드하기 전에 check_adapter를 호출하고, 매니페스트의 기반 리비전도 고정값과 비교한다. 하나라도 일치하지 않으면 오류를 발생시키므로, 실패한 사본은 모델이 메모리에 올라가기 전에 거부된다. 임계값 사본은 make_app에 의해 거부되고(yes), 추가 키 사본도 마찬가지다(yes). 이 검사는 저장소를 신뢰한다. 고정된 다이제스트는 코드 옆의 examples/adapter-pins.json에 있으므로, 폴더만 수정하고 고정 파일은 수정하지 않은 독자는 거부되지만, 둘 다 수정한 독자는 거부되지 않는다. 따라서 고정 파일은 다른 코드와 똑같이 검토해야 한다.
작업 규칙: 어떤 라우트든 어댑터를 로드하기 전에 검사를 실행한다. 매니페스트의 SHA-256을 코드와 함께 고정하고, 일치하는 설정과 파일의 수를 세고, 각 수를 전체 수와 함께 출력하며, 어느 한 수라도 모자라거나 매니페스트 다이제스트가 일치하지 않으면 로드를 거부한다. 해시는 디스크에 있는 파일에서 가져오고, 검사와 로드는 같은 파일로 하되 그 사이에 아무것도 그 파일에 쓰지 않게 한다.
인계율 지켜보기
인계율은 한 구간의 전체 메시지 중 임곗값 아래에 있는 메시지의 수를 그 구간의 전체 메시지 수로 나눈 값이다. 2장에서 이를 정의했고, 이 장에서는 시간에 따른 변화를 지켜본다. 지켜보려면 구간, 기준선, 그리고 한 구간이 기준선에서 너무 멀어졌을 때를 정하는 규칙, 이 세 가지가 필요하다.
기준선은 어댑터의 임곗값을 적용했을 때 dev 분할에서 나타나는 인계율이다. dev_handed_off는 dev 메시지 전체를 한 번 라우팅하고 인계된 수를 세어 이 값을 계산하며, 결과는 148/1003 (14.8%)이다. 5장의 임곗값 예제도 같은 수인 148/1003 (14.8%)을 출력한다. 두 값이 일치하므로 이 기준선은 그 장에서 임곗값을 고른 바로 그 기준선이다.
dev의 기준선은 받은 메시지함에 대한 예측이 아니다. dev 분할은 훈련 행에서 팀별로 뽑은 것이다. 테스트 표본은 테스트 분할에서 뽑은 것이다. 둘 다 받은 메시지함의 트래픽에서 뽑은 표본이 아니며, 실제 메시지에서 팀들이 어떤 비율로 섞여 있는지도 알려져 있지 않다. 따라서 한 구간과 기준선의 차이는 던져야 할 질문일 뿐, 그 자체가 질문에 대한 답은 아니다.
드리프트 규칙은 어떤 출처에서 가져온 수치가 아니라 이 책이 정한 것이다. 한 구간의 인계율이 기준선에서 어느 방향으로든 정해진 포인트 수보다 더 멀어지면 그 구간은 드리프트한 것이다. 출력된 규칙은 more than 10 points from the baseline이다. 지켜보는 일을 맡은 사람은 구간을 읽기 전에 자신의 수치를 정해 적어 두어야 한다.
커밋된 테스트 표본 test_1001에는 날짜가 없으므로, 구간은 앞의 100개 메시지에서 자른다. 처음 두 구간은 각각 25개의 메시지로 이루어지며, 표본 순서대로 앞에서부터 가져온 메시지이다. 3주차와 4주차는 새로운 트래픽이 아니라 재생이다. 이 두 주에 대해 예제는 표본의 그다음 메시지들을 가져와 라우터의 신뢰도가 낮은 것부터 높은 것 순으로 정렬한 뒤, 정렬된 목록을 둘로 나눈다. 예제는 출력한 줄 simulated replay of sample messages 51 to 100에서 이 재생이 모의 데이터임을 표시한다. 재생은 신뢰도가 넓게 퍼지도록 만들어졌으므로 치우친 구간에 규칙이 어떻게 반응하는지 보여 주지만, 기준선과 마찬가지로 받은 메시지함에 대해서는 아무것도 말해 주지 않는다.
1"""Watch the router's hand-off rate week by week on a fixed, ordered sample of test_1001, against the dev baseline.2The point rests on the "drift" lines and on the "lowest confidence" and "right" lines of weeks 3 and 4, which the output3labels as a simulated replay."""45import os67os.environ["HF_HUB_OFFLINE"] = "1"8os.environ["TRANSFORMERS_OFFLINE"] = "1"910import json # noqa: E4021112import torch # noqa: E4021314torch.set_num_threads(2)1516import router_lib # noqa: E4021718router_lib.setup_runtime()19RECORDED = router_lib.HERE / "data" / "recorded" / "lora-full"20# the threshold is read from the manifest, not typed here21threshold = json.loads((RECORDED / "manifest.json").read_text())["handoff_threshold"]22tokenizer, model = router_lib.load_classifier(RECORDED / "adapter")2324handed_dev, n_dev = router_lib.dev_handed_off(model, tokenizer, threshold)25base = 100 * handed_dev / n_dev26print(f"dev hand-off rate (baseline): {handed_dev}/{n_dev} ({base:.1f}%)")27print(f"drift rule: more than {router_lib.DRIFT_POINTS:.0f} points from the baseline")28print("weeks 3 and 4: simulated replay of sample messages 51 to 100")29test = router_lib.read_rows("test")30# simulated=True (the default) adds weeks 3 and 4: messages 51 to 100, lowest confidence first, ties by position31for w, (rows, preds, confs) in enumerate(router_lib.watch_weeks(model, tokenizer, threshold), 1):32 n = len(rows)33 handed = sum(router_lib.handoff(c, threshold) for c in confs)34 rate = 100 * handed / n35 # the messages the router keeps, each with its gold team: test row i holds (text, gold team)36 kept = [(p, test[i][1]) for i, p, c in zip(rows, preds, confs) if not router_lib.handoff(c, threshold)]37 right = sum(p == g for p, g in kept)38 print(f"week {w} messages: {n}")39 print(f"week {w} handed off: {handed}/{n} ({rate:.1f}%)")40 # abs makes the rule two-sided, so a fall in the rate drifts as a rise does41 print(f"week {w} drift: {'yes' if abs(rate - base) > router_lib.DRIFT_POINTS else 'no'}")42 print(f"week {w} lowest confidence: {min(confs):.3f}")43 print(f"week {w} right among messages not handed off: {right}/{len(kept)}")
python handoff-windows.pydev hand-off rate (baseline): 148/1003 (14.8%)
drift rule: more than 10 points from the baseline
weeks 3 and 4: simulated replay of sample messages 51 to 100
week 1 messages: 25
week 1 handed off: 6/25 (24.0%)
week 1 drift: no
week 1 lowest confidence: 0.479
week 1 right among messages not handed off: 17/19
week 2 messages: 25
week 2 handed off: 4/25 (16.0%)
week 2 drift: no
week 2 lowest confidence: 0.378
week 2 right among messages not handed off: 19/21
week 3 messages: 25
week 3 handed off: 9/25 (36.0%)
week 3 drift: yes
week 3 lowest confidence: 0.246
week 3 right among messages not handed off: 16/16
week 4 messages: 25
week 4 handed off: 0/25 (0.0%)
week 4 drift: yes
week 4 lowest confidence: 0.981
week 4 right among messages not handed off: 25/25
표본이 작기 때문에 구간도 작아서, 구간 네 개는 각각 25개의 메시지로 이루어진다. 이 크기의 구간에서는 메시지 하나가 인계율의 4포인트에 해당하므로, 메시지 하나만으로도 구간이 규칙의 경계선을 넘을 수 있다. 실제 받은 메시지함을 지켜보려면 메시지 하나가 표시 여부를 좌우하지 않을 만큼 큰 구간이 필요하다. 구간의 크기는 구간을 읽기 전에 정해 보고서에 적어야 한다.
1주차와 2주차는 규칙 안에 머물고, 재생 구간은 양쪽 방향으로 드리프트한다. 네 구간의 결과는 다음과 같으며, 각각 인계 수와 표시를 함께 적는다.
- 1주차의 인계는 6/25 (24.0%)이고, 드리프트 표시는 no이다.
- 2주차의 인계는 4/25 (16.0%)이고, 드리프트 표시는 no이다.
- 3주차의 인계는 9/25 (36.0%)이고, 드리프트 표시는 yes이다.
- 4주차의 인계는 0/25 (0.0%)이고, 드리프트 표시는 yes이다.
4주차는 독자가 자세히 살펴봐야 할 경우이다. 이 규칙은 하락도 상승과 똑같이 변화로 취급하므로, 인계율이 0으로 떨어지는 것도 드리프트로 판정된다. 인계율이 0인 이유는 4주차의 가장 낮은 신뢰도가 0.981으로 임곗값보다 높아서, 이 구간에서는 인계되는 메시지가 하나도 없기 때문이다. 라우터는 인계하지 않고 남긴 메시지 중 25/25에서 맞혔다. 이 구간은 확신에 차 있고 정확한 답으로 이루어진 구간이며, 드리프트 표시는 인계율이 달라졌다는 사실을 알릴 뿐 라우터가 실수했다는 사실을 알리는 것이 아니다.
3주차는 다른 종류의 구간이다. 가장 낮은 신뢰도는 0.246이고, 인계는 9/25 (36.0%)으로 늘어나며, 라우터는 인계하지 않고 남긴 메시지 중 16/16에서 맞힌다. 인계가 늘었다는 것은 더 많은 메시지가 사람에게 도달한다는 뜻이다. 그것만으로는 상승을 일으킨 원인이 메시지의 변화인지, 등장하는 팀의 변화인지, 모델의 변화인지 알 수 없다. 라우트의 답에는 메시지에 대한 기록이 담겨 있지 않으므로 라우트는 어느 쪽인지 말할 수 없으며, 8장도 라우트가 반환하는 인계율에 대해 같은 말을 한다.
작업 규칙: 같은 크기의 구간마다 인계 수를 세고, 각 수를 분모와 함께 출력하며, 각 인계율을 어댑터의 임곗값에서의 dev 기준선과 비교한다. 구간을 읽기 전에 드리프트 규칙과 그 포인트 수를 정하고 보고서에 적는다. 드리프트한 구간은 라우터에 대한 판정이 아니라, 그 구간의 메시지와 팀을 읽어 봐야 할 이유로 다룬다.
사람에게 넘긴 메시지의 표본
인계 감시는 사람에게 넘어가는 메시지가 몇 건인지를 센다. 이 감시는 두 가지 질문을 열어 둔다. 하나는 라우터가 넘긴 메시지에서 옳았는지이고, 다른 하나는 라우터가 직접 처리한 메시지에서 옳았는지이다. 이 절은 그중 첫째 질문에 어떻게 답할 수 있는지를 설명한다. 이는 다음 단계의 일이다. 이 장은 표본을 추출하지 않고, 레이블을 보고하지 않으며, 이에 대한 수치도 제시하지 않는다.
사람이 고정된 시드로 추출한 인계 메시지의 표본에 레이블을 붙인다. 그 레이블은 사람이 각 메시지에 대해 어느 팀을 고르는지를 나타낸다. 라우터의 모델이 골랐을 팀과 대조하면, 라우터가 확신하지 못한 메시지에서 두 선택이 얼마나 자주 다른지 알 수 있다. 메시지에 확신이 없는 라우터는 그 선택을 사람이 가장 많이 확인해야 하는 라우터이므로, 이 표본을 가장 먼저 추출해야 한다. 이 표본을 만드는 독자는 사람의 레이블 대신 공개 데이터셋의 정답 레이블을 대용으로 쓸 수 있으며, 그 사실을 보고서에 밝혀야 한다.
인계 메시지의 표본은 라우터가 직접 처리한 메시지에서 어떤 성과를 내는지는 알려 주지 않는다. 직접 처리한 메시지는 경로가 답을 돌려준 메시지이며, 인계는 이를 사람에게 보내지 않는다. 이 메시지의 정확도는 경로가 이미 답한 뒤에 사람이 그중 일부도 확인할 때에만 추정할 수 있다. 직접 처리한 메시지의 확인은 같은 방식으로 추출하는 두 번째 표본이며, 인계 메시지 표본의 부산물이 아니다. 측정값은 5장에서 정한 대로, 건수와 분모를 갖춘, 인계하지 않은 메시지에 대한 정확도이다.
작업 규칙: 표본을 만들 때는 고정된 시드로 추출하고, 레이블을 붙인 메시지가 몇 건인지 출력하고, 라우터의 팀과 사람의 팀이 얼마나 자주 일치하는지를 건수와 함께 보고한다. 직접 처리한 메시지의 표본에도 같은 일정으로 레이블을 붙이고, 직접 처리한 메시지에 대한 라우터의 정확도는 오직 그 표본에서만 읽는다. 직접 처리한 비율을 인계 메시지 표본에서 읽어서는 안 된다.
이 부분은 아직 번역되지 않았으므로 영어로 표시된다.
Fall back to a person
The route returns a flag and no team for a handed-off message, as chapter 8 built it. Something must still happen to that message. The rule in this chapter is that a handed-off message always goes to a person. The recorded answer of the stand-in, Qwen3-4B-Instruct-2507, may travel with a handed-off message as a suggestion, labelled as the stand-in's, and the person decides whether to use it. The stand-in's answers on test_1001 are recorded in standin-baseline (chapter 2). The router's team is never returned for a handed-off message.
The route's JSON has team, confidence, handed_off, adapter and version, and it has no field that says who answered. A fallback answer must therefore never go out in that shape. A reader who wants a suggestion in the response adds a field of their own, on purpose, and says in the response what the field is.
The book does not teach a call to a hosted model as the fallback, and it sets no threshold for the stand-in. Its answers come from a recording, which the fallback script reads. That script measures how often the suggestion is right, and it does not decide anything from that measure.
1"""Hand each handed-off message to a person, with the stand-in's recorded answer as a labelled suggestion.2The point rests on the "team returned for a handed-off message" line and the "suggestions right" line."""34import os56os.environ["HF_HUB_OFFLINE"] = "1"7os.environ["TRANSFORMERS_OFFLINE"] = "1"89import json # noqa: E4021011import torch # noqa: E4021213torch.set_num_threads(2)1415import router_lib # noqa: E4021617router_lib.setup_runtime()18RECORDED = router_lib.HERE / "data" / "recorded" / "lora-full"19# the threshold is read from the manifest, not typed here20threshold = json.loads((RECORDED / "manifest.json").read_text())["handoff_threshold"]21tokenizer, model = router_lib.load_classifier(RECORDED / "adapter")22test = router_lib.read_rows("test")23standin = router_lib.standin_rows() # a dict from test row index to the stand-in's answer, for the rows it answered24rows, handed = [], []25# simulated=False keeps weeks 1 and 2 only: the replay belongs to the watch, not to this example26for weekly_rows, _, confs in router_lib.watch_weeks(model, tokenizer, threshold, simulated=False):27 rows += weekly_rows28 handed += [i for i, c in zip(weekly_rows, confs) if router_lib.handoff(c, threshold)]2930# the list of records stands in for the person's queue, which the book does not build31# the suggestion is None where the stand-in has no recorded answer, and the team is always None32queue = [{"index": i, "team": None, "suggestion": standin[i]["label"] if i in standin else None} for i in handed]33suggested = [r for r in queue if r["suggestion"] is not None]34right = sum(r["suggestion"] == test[r["index"]][1] for r in suggested) # index 1 of a test row is its gold team3536print(f"messages routed: {len(rows)}")37print(f"handed off by the router: {len(handed)}/{len(rows)} ({100 * len(handed) / len(rows):.1f}%)")38print(f"sent to a person: {len(queue)}/{len(handed)}")39print(f"suggestions attached: {len(suggested)}/{len(handed)}")40print(f"suggestions right: {right}/{len(suggested)}")41print(f"team returned for a handed-off message: {sum(r['team'] is not None for r in queue)}")
python fallback-to-larger-model.pymessages routed: 50
handed off by the router: 10/50 (20.0%)
sent to a person: 10/10
suggestions attached: 10/10
suggestions right: 4/10
team returned for a handed-off message: 0
The example routes the first two windows, 50 messages in all, and the router hands off 10/50 (20.0%) of them. Each handed-off message gets one record, and the output counts the records sent to a person. Where the stand-in has a recorded answer, the record carries it as a suggestion. Of the records, 10/10 carry a suggestion, and the count of teams returned for a handed-off message is 0. The list of records stands in for the person's queue. The book does not build that queue, and a reader who builds one should keep each record with its message.
The suggestions are right on 4/10 of the handed-off messages that carry one. That is fewer than half, and it is the reason the suggestion is shown to a person and never used as the answer. The fallback script does not measure the stand-in on messages the router keeps. Every handed-off message in this sample carries a suggestion, and the chapter does not claim the same for the inbox.
Working rule: Send each handed-off message to a person. A recorded answer from the stand-in may come with it, labelled as a suggestion. Never return a team for it, and never put a suggestion in the route's response shape without a field that says who answered. Count the suggestions that are right, with the count and its denominator, before a reader decides how much weight to give them.
이 부분은 아직 번역되지 않았으므로 영어로 표시된다.
Retrain on a trigger
A drifting window is a signal to look, and it does not on its own start a retraining. The book sets three triggers, and this section states each one. The first is drift, the rule in this chapter's watch applied to consecutive windows. The book retrains when two consecutive windows drift, a number no source gives, and you may choose another, provided you state it in advance. The second trigger is a team added to the 77 the router returns. The router has no training rows for it, and people's labels would show it as a team outside the 77. The third is a rise in wrong teams on messages the router keeps, confirmed in the kept-message sample from the previous section. It is not the sample of handed-off messages, whose teams are never returned, so wrong teams there are expected and do no harm. The retrain script below exercises only the first. The recorded data holds no added team and no person's labels, so the second and third are rules without a test here.
1"""Decide whether to retrain, as a rule over the weekly drift flags from handoff-windows. The rule is the book's choice,2not a sourced threshold: retrain when two consecutive weeks drift, that is, their hand-off rate is more than3router_lib.DRIFT_POINTS from the dev baseline. The point rests on the "retrain trigger" line."""45import os67os.environ["HF_HUB_OFFLINE"] = "1"8os.environ["TRANSFORMERS_OFFLINE"] = "1"910import json # noqa: E4021112import torch # noqa: E4021314torch.set_num_threads(2)1516import router_lib # noqa: E4021718router_lib.setup_runtime()19RECORDED = router_lib.HERE / "data" / "recorded" / "lora-full"20# the threshold is read from the manifest, not typed here21threshold = json.loads((RECORDED / "manifest.json").read_text())["handoff_threshold"]22tokenizer, model = router_lib.load_classifier(RECORDED / "adapter")23handed_dev, n_dev = router_lib.dev_handed_off(model, tokenizer, threshold)24base = 100 * handed_dev / n_dev2526drifting, run, longest = [], 0, 027# the default simulated=True: weeks 3 and 4 are the replay, the same four windows the watch reads28for rows, _, confs in router_lib.watch_weeks(model, tokenizer, threshold):29 rate = 100 * sum(router_lib.handoff(c, threshold) for c in confs) / len(rows)30 flag = abs(rate - base) > router_lib.DRIFT_POINTS # two-sided, as in the watch31 drifting.append(flag)32 run = run + 1 if flag else 033 longest = max(longest, run)34 print(f"week {len(drifting)} drift: {'yes' if flag else 'no'}")3536print(f"weeks drifting: {sum(drifting)}/{len(drifting)}")37print(f"longest run of drifting weeks: {longest}")38print("rule: retrain when two consecutive weeks drift")39print("retrain trigger: " + ("fired" if longest >= 2 else "not fired"))
python retrain-trigger.pyweek 1 drift: no
week 2 drift: no
week 3 drift: yes
week 4 drift: yes
weeks drifting: 2/4
longest run of drifting weeks: 2
rule: retrain when two consecutive weeks drift
retrain trigger: fired
The retrain script applies the drift rule to the same four windows as the watch, in order, and finds 2/4 windows that drift, with a longest run of 2. Weeks 3 and 4 drive that result, since they are the replay from the watch. The trigger fired because of how the replay was built, so the run shows the rule working as stated, not anything the inbox did.
When a retraining does start, it follows the same path as the first adapter. It is a recording in recordings/, as banking77-lora-v1 was, written by a script there, and it writes a manifest with the same fields. It is named as the next version of the same recipe, so the retrained adapter is v2. Its threshold is chosen again on the dev split by the rule in chapter 5, never on the test sample. The retrained folder then needs its manifest's digest added to examples/adapter-pins.json, as a change to the repository that someone reviews. Until then, make_app refuses to build the app from it. The old adapter stays in place until make_app builds an app from the new folder.
Working rule: Retrain when the trigger you stated is met, and not on one drifting window. Write the trigger, its number and the rule beside the windows that met it. A retrained adapter is a recording named as the next version, with its manifest digest pinned and its threshold chosen again on dev. Keep the previous adapter until the new one passes the check in make_app.
운영 환경에서 무엇이 잘못되는가
- 매니페스트를 손으로 수정한다. 매니페스트의 다이제스트가 고정되어 있으므로 검사가 이를 거부한다. 저장소를 신뢰하는 검사는 핀 파일까지 함께 수정해야만 무력화할 수 있으며, 이는 누군가가 검토하는 변경이다.
- 핀이 움직인다.
examples/models.toml의 기본 핀은 매니페스트가 여전히 이전 리비전을 가리키는 어댑터 아래에서 바뀔 수 있다.make_app는 두 값을 비교하여 빌드를 거부한다. - 폴백이 잘못된 척도로 라우팅한다. 임계값에 맞춰 보정된 적이 없는 모델의 신뢰도는 관문이 될 수 없다. 따라서 이 책의 폴백은 라우팅을 전혀 하지 않으며, 제안은 사람의 메시지에만 함께 전달된다.
- 윈도가 너무 작다. 메시지 25개의 윈도에서는 메시지 하나가 4포인트이다. 그러면 플래그는 한두 개의 메시지를 반영할 뿐이며, 이를 근거로 행동하는 독자는 잡음에 따라 행동한 것이 된다.
- 비율이 움직이는데 아무것도 이를 설명하지 못한다. 해당 경로의 응답에는 메시지에 대한 기록이 남지 않으므로, 비율의 변동은 메시지와 해당 팀을 바탕으로 답해야 할 질문이 된다. 이때 이 장에서 다음 단계로 설명하는 표본을 사용한다.
첫 번째 유형의 실패는 앱을 빌드할 때 알 수 있다. 거부된 폴더는 시작 시점에 오류를 일으키므로, 앱을 시작할 때 빌드하는 배포 환경에서는 어떤 메시지도 실패하기 전에 잘못된 폴더가 드러난다. 나머지 실패는 집계 수치에 나타난다. 이관 비율의 변동은 윈도의 집계에 나타나며 드리프트 규칙이 이를 보고한다. 엉뚱한 메시지에 응답하는 폴백은 제안 수에 나타나고, 사람이 붙인 레이블의 표본이 나머지를 보여 준다.
작업 규칙: 각 통제의 집계를 시작 시점과 각 윈도에서 독자가 볼 수 있는 곳에 출력하고, 실패를 드러낼 수 있는 집계는 그것이 설명하는 비율과 같은 보고서에 둔다.
이 장이 내린 결정
- 이관된 메시지는 항상 사람에게 간다. 대역 모델의 답이 있을 때 그 답은 표시를 붙인 제안일 뿐이며, 이 장은 그 답이 얼마나 자주 맞는지 센다.
- 버전 검사는 각 어댑터의
manifest.json에 대한 SHA-256을examples/adapter-pins.json에 고정한다.make_app는 해시가 하나라도 일치하지 않거나 기반 모델의 고정값이 바뀌어 있으면 빌드를 거부한다. - 드리프트 규칙은 25개 메시지로 이루어진 구간에서 개발 기준선과의 차이가 어느 방향으로든 10포인트인 경우를 가리킨다.
- 연속한 두 구간에서 드리프트가 나타나면 재학습할 시점이다. 두 번째와 세 번째 트리거는 명시된 규칙이며, 여기서는 검증하지 않는다.
10장은 이 장과 같은 측정값을 사용한다.
네 가지 모두 이 책이 정한 선택이다. 드리프트 규칙을 참고한다. 이 통제 장치들은 함께 작동하여 어느 모델이 답하는지 확인하고, 이관되는 메시지의 수를 세며, 이관된 메시지를 각각 사람에게 보낸다. 대체 규칙은 1장에서 정한, 표시된 메시지는 사람에게 간다는 규칙을 따른다. 고정 규칙은 저장소 검토를 포기하는 대신, 로드만으로는 할 수 없는 검사를 얻는 교환이다.
작업 규칙: 위의 결정을 각각 보고서에 쓰되, 그 수치와 함께 이 책의 선택인지 출처가 있는 수치인지를 밝힌다. 결정을 바꿀 때는 그 결정이 가리키는 규칙을 바꾸는 방식으로만 바꾸고, 해당 개수를 출력하는 예제를 다시 실행한다.
이 판의 이 장
2026.11.9판예제 통과 2026년 11월 20이 장에서 4개 예제개 중 4개가 통과한다
영어판 2026.11.9판을 번역한 것이다.