작은 모델에 프롬프트를 주고 답을 팀으로 제한하기
읽는 데 약 33분분 걸린다, 7절에 5개 예제이(가) 있음.
AI로 번역함. 영어 원문을 사람이 검증함. 우리가 책을 만드는 방식
영어판 2026.11.9판을 번역한 것이다. 원문 읽기
이 장을 마치면 작은 오픈 모델을 위한 라우터 프롬프트를 작성하고, 모델의 답이 팀 이름만 될 수 있도록 제한하고, 그 답 가운데 몇 개가 맞는지 측정할 수 있다. 또한 유효한 답이 곧 올바른 답은 아니라는 점도 확인하게 된다. 그래서 다음 장에서는 모델에 더 나은 질문을 하는 대신 모델을 학습시킨다.
라우터는 모든 답이 팀 이름이어야 한다. 1장에서 작은 모델이 자유 형식의 글로 답하도록 했을 때 모델은 팀을 반환하지 않았다. 이 장은 먼저 구조적으로 답이 팀이 되도록 만든다. 그런 다음 3장의 두 오픈 모델인 SmolLM2-135M-Instruct와 SmolLM2-360M-Instruct를 하나의 프롬프트와 하나의 제약으로 실행하여 무엇을 반환하는지 측정한다. 135M 모델은 5장에서 학습시키는 모델이므로, 여기서 얻은 개수는 그 학습이 넘어서야 할 기준이다.
두 종류의 수치가 나오며, 이 장은 둘을 구분해 다룬다. 실시간 예시는 test_40의 처음 메시지 여섯 개, 즉 고정 표본의 처음 40개 메시지 가운데 처음 여섯 개에서 실행하며, 두 모델에 같은 여섯 개를 사용한다. 이 예시는 동작 방식을 보여 준다. 메시지 여섯 개로는 두 모델을 구별할 수 없으므로 비교에는 기록을 사용한다. 각 모델과 프롬프트가 test_200의 메시지 200개 전체, 즉 그 표본의 처음 200개(앞의 여섯 개를 포함한다)에 한 번씩 답했고, 그 답을 저장했다. 기록을 읽을 때는 모델을 불러오지 않으며, 그 개수는 저장된 답에서만 나온다.
이 부분은 아직 번역되지 않았으므로 영어로 표시된다.
The prompt, settled before any recording
Every example in this chapter uses one router prompt. It tells the model that the message comes from an online bank, asks for one support team and the team name only, lists the 77 teams, and ends with Team:, so the model's next words are the answer. A raw model that has not been trained for the task gets nothing else, so the wording matters. This chapter does not tune it. The prompt was fixed before any recording, and the recording's manifest holds the prompt's hash. A changed prompt is a different recording, and its counts cannot be set beside the ones here.
The list of teams in the prompt is the same list the constraint uses. The trie in the next section is built from the same label names in the same order, so the prompt and the constraint cannot disagree about which teams exist. The same dependency works the other way. A reader who adds or renames a team changes the prompt, and so changes the recording's hash. The counts in this chapter then no longer describe that prompt, and the reader must record again before comparing.
The raw form passes the router prompt's text to the model as it stands. The chat form wraps the router prompt's text in the model's chat template, which adds a default system prompt. To see what the template changes, run the chat form on the same six messages:
1"""Route the first 6 messages of test_40 with the 135M model through its chat template, decoding only team names.2The template adds the model's default system prompt. The prose quotes this run's accuracy line next to the raw form's, and the messages are never printed."""34import os56# no network: the pinned model must already be in the local cache7os.environ["HF_HUB_OFFLINE"] = "1"8os.environ["TRANSFORMERS_OFFLINE"] = "1"910import collections # noqa: E4021112import torch # noqa: E4021314# two threads, so the sums add in the same order on every run15torch.set_num_threads(2)1617import router_lib # noqa: E4021819# seeds 0 for random and torch, deterministic algorithms and float32, so greedy decoding repeats20router_lib.setup_runtime()2122SMALL = "HuggingFaceTB/SmolLM2-135M-Instruct"2324tokenizer, model = router_lib.load_model(SMALL)25trie = router_lib.build_trie(tokenizer)26# (text, label index) for every test row, in file order; the index is the gold team27rows = router_lib.read_rows("test")28# row numbers of the first six messages of the fixed 40-message sample29sample = router_lib.read_sample("test_40", 6)30teams = set(router_lib.LABELS)3132results = []33for i in sample:34 # the chat template wraps the message in the model's chat format, with its default system prompt35 text = router_lib.chat_prompt(tokenizer, rows[i][0])36 # the template has already written the special tokens, so the tokenizer adds none37 results.append(router_lib.constrained_team_text(tokenizer, model, trie, text, add_special_tokens=False))38valid = [text in teams for _, text in results]39# the walk's index, never the decoded text, is what counts40right = [index == rows[i][1] for (index, _), i in zip(results, sample)]41given = collections.Counter(text for _, text in results)42# most given team; a tie in count goes to the team listed first43top = min(given, key=lambda team: (-given[team], router_lib.LABELS.index(team)))4445print(f"messages: {len(sample)}")46print(f"answers that are a team: {sum(valid)}/{len(sample)}")47print(f"accuracy: {sum(right)}/{len(sample)} ({100 * sum(right) / len(sample):.1f}%)")48print(f"distinct teams given: {len(given)}")49print(f"most given team: {top}, {given[top]}/{len(sample)}")
python constrained-decode-135m-chat.pymessages: 6
answers that are a team: 6/6
accuracy: 0/6 (0.0%)
distinct teams given: 3
most given team: cancel_transfer, 3/6
The book uses the raw form as its default. The choice was made before any recording was read: both models in the comparison are measured on it, so the comparison is between models, not between prompts. The chat form was recorded afterwards, as an observation. On the 200 messages it got 11/200 (5.5%) right, and the raw form got 9/200 (4.5%). A gap of two messages in 200 is not a difference this sample can show in either direction, so the chat form is not shown to help, and the raw form is not shown to hurt, and the default is not changed because of this count. The trie's names begin with a space, which follows Team: in the raw form but not the new line that opens the answer in the chat template. The chat count is therefore for this trie as well as for the template. The result is not evidence that raw prompts beat chat templates for small models in general, and one sample of 200 messages does not settle that.
Working rule: Use one prompt for every model you compare, in the form the comparison needs. Before you adopt a chat template, measure it on the same sample as the raw form, and report a small gap as a small gap.
자유 텍스트가 실패하는 이유
1장에서는 제약 없이 원시 모델에 팀 하나를 물었고, 모델은 자유롭게 디코딩했다. 이 장에서와 마찬가지로 매 단계에서 점수가 가장 높은 토큰을 고르는 그리디 방식이었지만, 고를 수 있는 토큰에 마스크는 없었다. 그 예제는 답변의 수를 세었다. 팀 이름인 답변은 0/20개였으므로, 라우터가 다음으로 넘길 것이 없었다.
모델 자체의 디코딩에는 답이 문장이 되는 것, 목록에 없는 팀이 되는 것, 팀 이름과 철자가 비슷하게 틀린 것이 되는 것을 막는 장치가 없다. 디코더는 매 단계에서 어휘에 있는 어떤 토큰이든 고를 수 있으므로 답은 어디로든 흘러갈 수 있다. 1장의 대역(代役)은 이 실패를 보여 주지 못했다. 기록된 답변이 팀 이름만 허용하는 문법에서 나왔기 때문이다. 라우터 안에서 돌아가는 모델에는 디코더 자체에서 같은 보장이 필요하다.
솔깃한 해결책은 모델이 쓴 것을 가장 가까운 팀 이름에 맞추는 것이다. 이 방법은 추측이다. 철자가 비슷하게 틀린 답은 올바른 팀과 맞을 수도 있고 글자가 비슷한 엉뚱한 팀과 맞을 수도 있으며, 그러면 라우터는 모델이 지명한 적 없는 팀으로 메시지를 보내게 된다. 1장은 대신 무엇을 할지 말했다. 팀이 아닌 답변은 오류로 간주하고, 표본에서 그 수를 세고, 메시지는 사람에게 보낸다. 제약은 그런 답변의 대부분을 쓰이기 전에 없앤다. 그래도 수는 계속 센다. 제약이 지켜지지 않을 때 라우팅이 조용히 바뀌는 대신 숫자로 드러나게 하기 위해서다.
작업 규칙: 팀이 아닌 답변은 실패한 라우팅으로 취급한다. 모델이 무엇이든 라우팅하기 전에 고정된 표본에서 그런 답변의 수를 세고, 철자가 비슷하게 틀린 답을 가장 가까운 팀에 맞추지 않는다. 디코딩 시점에 답을 제약하고 그 수를 계속 세어, 제약이 깨지면 숫자로 드러나게 한다.
이 부분은 아직 번역되지 않았으므로 영어로 표시된다.
A token trie allows only team names
A model writes tokens, not words, and a team name is a short run of them. build_trie in router_lib, the book's shared module, stores the 77 names as a trie: a tree whose paths spell out each team's tokens, with the team's index at the node where its path ends. The function asserts that no two teams end at the same node, so each path names one team.
The decoder walks this tree as it writes. At the start, the allowed tokens are the first token of each team name. After each token, the allowed set narrows to the children of the node the decoder has reached. Where a path has ended on a team, the end-of-answer token joins the allowed set, so the answer can stop there. No one of the 77 names is the start of another, so every path ends at a leaf. The code would still handle a name that was: at that node the decoder could stop, or continue along the longer name. A walk of this kind cannot leave the list, because every token it may choose leads toward a team.
Greedy decoding then takes the highest-scoring of the allowed tokens at each step. Transformers applies the rule through a callback, prefix_allowed_tokens_fn, which returns the allowed tokens for each position. The processor starts from a mask of minus infinity for every token, sets the allowed tokens' entries to zero, and adds the mask to the scores with scores_processed = scores + mask. Every token that is not allowed keeps minus infinity, so greedy decoding cannot pick it (transformers 5.23.0, src/transformers/generation/logits_process.py).
Chapter 1's stand-in got the same guarantee from its library. recordings/common.py builds a grammar, root ::= "card_arrival" | ..., that lists the 77 names as literal strings, and the recordings applied it through the chat template. llama-cpp-python adds a grammar to its sampler before the greedy step. In llama_cpp/llama.py the line sampler.add_grammar(self._model, grammar) runs under if grammar is not None:, and sampler.add_greedy() runs after it, under elif temp == 0.0: (llama-cpp-python v0.3.36, llama_cpp/llama.py). So the stand-in's answers were limited to the names by the library, where this chapter's callback does the same job in the decoder.
Two details of that code shape the callback. The processor calls it as self._prefix_allowed_tokens_fn(batch_id, sent), so the batch index comes first. And an empty list is an error: the processor raises ValueError when the callback returns no tokens. The book's callback therefore never returns an empty list. When no path can continue, it returns the end-of-answer token, and the answer stops there. The end-of-answer token is the model's <|im_end|>, which is also its pad token (id 2). The decoder stops after 32 new tokens (max_new_tokens=32). Every one of the 600 recorded answers ended on a team. A node with no children always holds a team, so the empty-list case is a guard and not a case the 77 names produce.
First, the 135M model with the trie, on those six messages.
1"""Route the first 6 messages of test_40 with the 135M model, decoding only team names, and count how many right answers that gives.2The point rests on the count of answers that are team names, which the trie guarantees, and on the accuracy line, which the measurement section reads. The messages are read from the test split and are never printed."""34import os56# no network: the pinned model must already be in the local cache7os.environ["HF_HUB_OFFLINE"] = "1"8os.environ["TRANSFORMERS_OFFLINE"] = "1"910import collections # noqa: E4021112import torch # noqa: E4021314# two threads, so the sums add in the same order on every run15torch.set_num_threads(2)1617import router_lib # noqa: E4021819# seeds 0 for random and torch, deterministic algorithms and float32, so greedy decoding repeats20router_lib.setup_runtime()2122SMALL = "HuggingFaceTB/SmolLM2-135M-Instruct"2324tokenizer, model = router_lib.load_model(SMALL)25trie = router_lib.build_trie(tokenizer)26# (text, label index) for every test row, in file order; the index is the gold team27rows = router_lib.read_rows("test")28# row numbers of the first six messages of the fixed 40-message sample29sample = router_lib.read_sample("test_40", 6)30teams = set(router_lib.LABELS)3132# (label index, team text); the index comes from the trie walk, not from parsing the text33results = [router_lib.constrained_team(tokenizer, model, trie, rows[i][0]) for i in sample]34valid = [text in teams for _, text in results]35# the walk's index, never the decoded text, is what counts36right = [index == rows[i][1] for (index, _), i in zip(results, sample)]37given = collections.Counter(text for _, text in results)38# most given team; a tie in count goes to the team listed first39top = min(given, key=lambda team: (-given[team], router_lib.LABELS.index(team)))4041print(f"messages: {len(sample)}")42print(f"answers that are a team: {sum(valid)}/{len(sample)}")43print(f"accuracy: {sum(right)}/{len(sample)} ({100 * sum(right) / len(sample):.1f}%)")44print(f"distinct teams given: {len(given)}")45print(f"most given team: {top}, {given[top]}/{len(sample)}")
python constrained-decode-135m.pymessages: 6
answers that are a team: 6/6
accuracy: 1/6 (16.7%)
distinct teams given: 3
most given team: card_arrival, 4/6
Run on 6 messages, the model's answers are team names in every case, 6/6, which is the guarantee the trie gives. The accuracy on the same messages is 1/6 (16.7%). The measurement section takes that second number apart.
The router does not read the team out of the text. constrained_team returns the index stored at the node where the walk ended, and the text is decoded only so that a reader can see it. The index is fixed by the trie and not by a parser that runs after the model. That is the reason the constraint is worth the code: a parser that matches text to teams can fail in ways the trie cannot. These examples return the team only so that it can be counted. Nothing in this chapter routes a message. A route returns a team only through handoff, which sends an uncertain answer to a person, and the examples here do not call it.
Working rule: Constrain the answer to the labels with a token trie built from the label names, and count the answers that are labels on a fixed sample. The constraint makes every answer a team. It does not make any answer right, so count the right answers as a separate measure.
모든 횟수가 반복되도록 탐욕적으로 디코딩한다
여기에 나오는 모든 예제는 탐욕적 디코딩을 사용한다. 점수가 가장 높은 것이 선택되고, 표본 추출은 하지 않는다. 이 점은 횟수에서 중요하다. 표본으로 추출한 답은 실행할 때마다 달라질 수 있고, 그러면 출력된 어떤 횟수도 기록과 대조해 확인할 수 없다. 예제는 router_lib.setup_runtime를 통해 시드와 float32를 고정하고 스레드를 두 개로 설정하므로, 한 대의 기계에서는 실행해도 같은 답이 반복된다. 각 예제는 실행기가 어떻게 시작되었는지에 의존하지 않도록 맨 위에서 torch.set_num_threads(2)를 직접 호출한다. 각 예제가 출력한 내용은 실행할 때마다 기록된 출력과 비교하며, 한 줄이라도 달라지면 검사에 실패한다.
한 기계에서 반복할 수 있다고 해서 어디에서나 반복할 수 있는 것은 아니다. PyTorch 2.15.0+cpu의 무작위성 관련 문서에 따르면, 완전히 재현 가능한 결과는 릴리스, 개별 커밋, 플랫폼 사이에서 보장되지 않는다. 그래서 이 책은 examples/requirements.txt에 고정된 버전과, 이 책을 실행한 종류의 기계에 한해서만 반복성을 주장한다. 다른 플랫폼을 쓰는 독자는 기록된 줄을 다시 확인하게 될 것으로 예상해야 한다. 그곳에서 기록된 줄이 실패하면 예제를 고치기 전에 달라진 줄을 먼저 읽는다. 맞은 답의 개수가 달라지는 원인은 기계가 다르거나, 라이브러리 버전이 다르거나, 프롬프트가 바뀐 것일 수 있으며, 각각 해결 방법이 다르다.
동점에도 고정된 규칙이 필요하다. 지난 절의 레이블 점수 계산은 정렬 키 (score, -index)를 통해 점수가 같으면 팀 인덱스가 낮은 쪽을 택하고, 가장 많이 지정된 팀의 횟수 계산은 횟수가 같으면 팀 이름으로 순서를 정한다. 제약 디코딩에는 팀 점수가 없다. 이 방식의 탐욕 단계는 허용된 토큰 중 처음 나오는 최댓값을 택하므로, 동점이면 토큰 id가 낮은 쪽이 선택된다.
작업 규칙: 탐욕적 디코딩을 사용하고, 시드와 스레드 수를 고정하며, 실행할 때마다 출력된 각 줄을 기록된 사본과 비교한다. 결과를 실행한 버전과 기계의 종류를 넘어서 재현 가능하다고 설명하지 않는다.
제약된 답변 측정하기
라이브 예제는 메시지 여섯 개를 다룬다. 원시 프롬프트를 쓴 135M 모델은 1/6 (16.7%)개를 맞혔고, 360M 모델은 0/6 (0.0%)개를 맞혔다. 메시지 여섯 개로는 이 모델들의 순위를 매길 수 없다. 두 수의 차이는 정답 하나에 불과하다. 135M 모델이 가장 자주 내놓은 답은 card_arrival, 4/6였고, 같은 메시지 여섯 개에 챗 형식을 쓴 경우의 결과는 0/6 (0.0%)였다.
360M 실행은 더 큰 모델을 쓴 같은 프로그램이다.
1"""Decode team names for the first 6 messages of test_40 with the 360M model, and count how many of them are right.2The prose sets its accuracy line against the 135M model's, on the same six messages. The messages are read from the test split and are never printed."""34import os56# no network: the pinned model must already be in the local cache7os.environ["HF_HUB_OFFLINE"] = "1"8os.environ["TRANSFORMERS_OFFLINE"] = "1"910import collections # noqa: E4021112import torch # noqa: E4021314# two threads, so the sums add in the same order on every run15torch.set_num_threads(2)1617import router_lib # noqa: E4021819# seeds 0 for random and torch, deterministic algorithms and float32, so greedy decoding repeats20router_lib.setup_runtime()2122MEDIUM = "HuggingFaceTB/SmolLM2-360M-Instruct"2324tokenizer, model = router_lib.load_model(MEDIUM)25trie = router_lib.build_trie(tokenizer)26# (text, label index) for every test row, in file order; the index is the gold team27rows = router_lib.read_rows("test")28# row numbers of the first six messages of the fixed 40-message sample29sample = router_lib.read_sample("test_40", 6)30teams = set(router_lib.LABELS)3132# (label index, team text); the index comes from the trie walk, not from parsing the text33results = [router_lib.constrained_team(tokenizer, model, trie, rows[i][0]) for i in sample]34valid = [text in teams for _, text in results]35# the walk's index, never the decoded text, is what counts36right = [index == rows[i][1] for (index, _), i in zip(results, sample)]37given = collections.Counter(text for _, text in results)38# most given team; a tie in count goes to the team listed first39top = min(given, key=lambda team: (-given[team], router_lib.LABELS.index(team)))4041print(f"messages: {len(sample)}")42print(f"answers that are a team: {sum(valid)}/{len(sample)}")43print(f"accuracy: {sum(right)}/{len(sample)} ({100 * sum(right) / len(sample):.1f}%)")44print(f"distinct teams given: {len(given)}")45print(f"most given team: {top}, {given[top]}/{len(sample)}")
python constrained-decode-360m.pymessages: 6
answers that are a team: 6/6
accuracy: 0/6 (0.0%)
distinct teams given: 4
most given team: card_payment_wrong_exchange_rate, 3/6
비교를 위해 각 변형이 메시지 200개에 답했다. 기록에 담긴 수치는 표와 같고, 모든 행에서 메시지는 같다.
| test_200에서의 변형 | 팀 목록 밖의 답 | 정답 | 제시된 서로 다른 팀 |
|---|---|---|---|
| 135M, 원시 프롬프트 | 0/200 | 9/200 (4.5%) | 18 |
| 135M, 챗 템플릿 | 0/200 | 11/200 (5.5%) | 17 |
| 360M, 원시 프롬프트 | 0/200 | 12/200 (6.0%) | 8 |
이 예제는 표의 수치를 기록에서 읽어 온다.
1"""Compare the three prompting variants on test_200, from the recording only. No model is loaded.2The chapter's table takes its three columns from the first three lines printed for each variant, and the point rests on the correct count.34recordings/prompting_eval.py wrote one answer per variant and message to examples/data/recorded/prompting-eval/answers.jsonl.5"""67import collections8import json9from pathlib import Path1011import torch1213# two threads, as in the other examples14torch.set_num_threads(2)1516import router_lib # noqa: E4021718# seeds 0 for random and torch, deterministic algorithms and float32, as in the other examples19router_lib.setup_runtime()2021ANSWERS = Path(__file__).resolve().parent / "data" / "recorded" / "prompting-eval" / "answers.jsonl"22teams = set(router_lib.LABELS)23# (text, label index) for every test row, in file order; the index is the gold team24rows = router_lib.read_rows("test")25# the 200 messages of the fixed sample; every variant answers all of them26total = len(router_lib.read_sample("test_200"))2728by_variant = collections.defaultdict(list)29with open(ANSWERS) as f:30 for line in f:31 answer = json.loads(line)32 by_variant[answer["variant"]].append(answer)3334for variant in sorted(by_variant):35 answers = by_variant[variant]36 outside = sum(answer["team"] not in teams for answer in answers)37 # answer["label"] is the team index the variant chose; rows[...][1] is the message's gold index38 right = sum(answer["label"] == rows[answer["index"]][1] for answer in answers)39 given = collections.Counter(answer["team"] for answer in answers)40 # most given team; a tie in count goes to the team name that sorts first, not to the index41 top = min(given, key=lambda team: (-given[team], team))42 # the gold index becomes a team name, to compare with the most given team43 gold_top = sum(router_lib.LABELS[rows[answer["index"]][1]] == top for answer in answers)44 print(f"{variant} answers outside the team list: {outside}/{total}")45 print(f"{variant} correct: {right}/{total} ({100 * right / total:.1f}%)")46 print(f"{variant} distinct teams given: {len(given)}")47 print(f"{variant} most given team: {top}, {given[top]}/{total}")48 print(f"{variant} gold for most given team: {gold_top}/{total}")
python prompting-on-test-200.py135m-chat answers outside the team list: 0/200
135m-chat correct: 11/200 (5.5%)
135m-chat distinct teams given: 17
135m-chat most given team: topping_up_by_card, 55/200
135m-chat gold for most given team: 1/200
135m-raw answers outside the team list: 0/200
135m-raw correct: 9/200 (4.5%)
135m-raw distinct teams given: 18
135m-raw most given team: card_arrival, 165/200
135m-raw gold for most given team: 0/200
360m-raw answers outside the team list: 0/200
360m-raw correct: 12/200 (6.0%)
360m-raw distinct teams given: 8
360m-raw most given team: card_payment_wrong_exchange_rate, 94/200
360m-raw gold for most given team: 4/200
라우터라고 부를 만한 행은 하나도 없지만, 제약은 모든 행에서 지켜졌다. 어느 행에도 팀 목록 밖의 답은 없다. 360M 원시 행의 정답이 12/200 (6.0%)개로 가장 많지만, 어떤 행도 다른 행보다 몇 개 메시지 이상 앞서지 않는다.
서로 다른 팀의 수만으로는 오해하기 쉽다. 135M 원시 행은 서로 다른 팀을 18개 제시했고 360M 원시 행은 8개 제시했지만, 135M 행의 답은 대부분 한 팀인 card_arrival, 165/200로 몰린다. 반면 360M 원시 행에서 가장 많이 제시된 팀은 card_payment_wrong_exchange_rate, 94/200개의 답만 받는다.
행을 읽을 때는 첫 번째 열부터 본다. 이 값이 0이 아니면 제약이 지켜지지 않은 것이고, 이를 고치기 전에는 나머지 두 열이 아무 의미도 없다. 라우팅에서 중요한 열은 두 번째 열이다. 이 열은 팀이 정답 레이블과 일치하는 메시지의 수를 전체 표본에 대해 센 것이며, 틀린 답은 틀린 것으로 센다. 세 번째 열은 그 변형이 팀을 몇 개나 사용하는지를 말해 준다. 팀을 몇 개만 제시하는 변형은 인기 있는 몇몇 팀을 찍고 있거나 좁은 무언가를 학습한 것인데, 이 수치만으로는 어느 쪽인지 알 수 없다. 수가 크다고 해서 쏠림이 없다고 할 수도 없으며, 135M 원시 행이 그 예다. 자신의 메시지 표본에서 같은 세 가지 수를 구해 보면, 각 열의 의미가 같은 비교를 자신의 데이터로 얻을 수 있다.
360M 모델은 두 모델 중 더 큰 쪽이며, 3장에서 얼마나 더 큰지 셌다. 표는 이 프롬프트와 이 제약에서 그 비용이 무엇을 사 주는지 보여 준다. 360M 모델은 12/200 (6.0%)개를 맞혔고, 같은 원시 형식에서 135M 모델은 9/200 (4.5%)개를 맞혔다. 더 큰 모델이 몇 개 메시지를 더 맞힌 것이며, 이 장은 그것을 더 큰 크기에 대한 비용을 치를 이유로 보지 않는다.
이 책은 이 수치에 대한 구간을 계산하지 않으며, 200개 중 몇 개 차이는 표본에서 비롯될 수 있다. 따라서 표가 뒷받침하는 진술은 하나뿐이다. 세 변형은 서로 가깝고, 어느 것도 라우터가 아니다. 두 프롬프트 중 하나를 고르려는 독자는 자신의 메시지 표본에서 둘 다 실행해 같은 세 가지를 세어야 한다.
트라이는 답의 형태만 검사하고 그 밖의 것은 검사하지 않는다. 프롬프트 너머의 메시지는 읽지 않으며, 어느 팀이 맞는지도 모른다. 목록에 있는 팀은 이름을 아직 쓸 수 있는 모든 단계에서 허용되므로, 그 가운데 디코더가 무엇을 고르는지는 모델의 선택이다. 마스크는 어떤 팀을 쓸 수 있는지만 정한다.
유효하지만 틀린 답 하나를 팀만으로 설명하면 다음과 같다. 이 책에서는 메시지를 인용하지 않기 때문이다. 정답 팀이 card_not_working인 테스트 메시지 하나에 대해 135M 원시 행은 card_arrival를 답했다. 이는 목록에 있는 팀이므로 제약이 통과시켰고, 목록 밖 답의 수는 0으로 남는다.
출력이 뒷받침하는 교훈은 제약된 디코딩이 모든 답을 팀으로 만들지만 유효한 답이 곧 맞는 답은 아니라는 것이다. 제약은 팀이 아닌 답을 없애기만 한다. 더 나은 팀을 고르게 하지는 못하며, 프롬프트를 바꾼 것도 마찬가지였다. 5장이 다음 단계다. 5장은 레이블이 붙은 메시지로 헤드를 학습시키고, 학습된 모델이 같은 표본에서 더 잘 라우팅하는지 측정한다.
운영 환경에서 이 실패는 오류로 나타나지 않는다. 팀이 아닌 답의 수는 0으로 유지되므로 이 수만 지켜보는 점검은 계속 정상으로 보인다. 고정된 레이블 표본에서 정답 수를 세어야만 문제가 드러난다.
비용은 메시지를 받는 사람들이 진다. 유효하지만 틀린 팀은 메시지를 잘못된 목적지로 보내고, 그곳의 지원 담당자는 자신의 일이 아닌 요청을 보게 된다. 이들은 올바른 팀을 찾아 메시지를 옮겨야 하는데, 이는 인계가 만드는 작업과 같으며 메시지에는 잘못 라우팅되었다는 표시가 없다. 확신이 없을 때 이를 말하지 못하는 라우터는 이 사람들에게 행동할 근거를 주지 못한다. 제약된 디코딩은 나머지 76개 팀에 대한 점수도 반환하지 않으므로, 이를 바탕으로 한 인계 규칙에는 비교할 팀별 점수가 없다.
작업 규칙: 비교하는 모든 변형에 대해, 고정된 표본 하나에서 유효한 답의 수 옆에 정답의 수를 함께 보고하라. 모든 답이 유효한 라우터도 대부분의 메시지에서 틀릴 수 있으며, 이는 두 번째 수만이 보여 준다.
이 부분은 아직 번역되지 않았으므로 영어로 표시된다.
Why a prior is not a router
Constrained decoding returns one answer and no scores. Label scoring gives every team a score. For each team, label scoring sums the log-probability of the team's tokens after the prompt, where a log-probability is the logarithm of the probability the model gives a token. The team with the highest sum is the model's top team for the message.
Run it on three messages and read the top team of each:
1"""Score every team for the first 3 messages of test_40 with the 135M model, by the summed log-probability of its tokens.2This shows the model's prior, the team it favours before any fine-tuning. The point rests on the most frequent top team and how many messages it tops. The messages are never printed."""34import os56# no network: the pinned model must already be in the local cache7os.environ["HF_HUB_OFFLINE"] = "1"8os.environ["TRANSFORMERS_OFFLINE"] = "1"910import collections # noqa: E4021112import torch # noqa: E4021314# two threads, so the sums add in the same order on every run15torch.set_num_threads(2)1617import router_lib # noqa: E4021819# seeds 0 for random and torch, deterministic algorithms and float32, so greedy decoding repeats20router_lib.setup_runtime()2122SMALL = "HuggingFaceTB/SmolLM2-135M-Instruct"2324tokenizer, model = router_lib.load_model(SMALL)25rows = router_lib.read_rows("test")26# row numbers of the first three messages of the fixed 40-message sample27sample = router_lib.read_sample("test_40", 3)28# each team's token ids, padded to the longest name, built once for all messages29table = router_lib.label_token_table(tokenizer)3031tops = []32for i in sample:33 scores = router_lib.label_scores(tokenizer, model, table, rows[i][0])34 # index of the highest-scoring team; a tie goes to the lower index35 tops.append(max(range(len(scores)), key=lambda k: (scores[k], -k)))3637counts = collections.Counter(tops)38# most frequent top team; a tie in count goes to the lower index39best = min(counts, key=lambda k: (-counts[k], k))4041print(f"messages: {len(sample)}")42print(f"distinct top teams: {len(counts)}")43print(f"most frequent top team name: {router_lib.LABELS[best]}")44print(f"most frequent top team: {counts[best]} of {len(sample)}")
python label-scoring-prior.pymessages: 3
distinct top teams: 1
most frequent top team name: card_arrival
most frequent top team: 3 of 3
Before any training, the model puts one team first for every message: card_arrival tops 3 of 3 messages. That team is the model's prior, and three messages are too few to say more about it.
If the top team is the same for every message, the score is the model's prior and says little about any one message. The 200-message recording shows the same prior in constrained decoding: card_arrival, 165/200, the 135M raw row's favourite, is the gold team of 0/200 messages in the sample.
The sum favours short names. Each token of a team's name adds a log-probability, which is never above zero, so a team with more tokens has more terms to pull its total down. The example adds the terms without dividing by length, and the chapter does not claim to correct for it. A reader who uses label scoring should check the top teams against a sample with gold labels before trusting them.
Label scoring does give a score for each team, which is what a hand-off rule needs. Each message is scored against all 77 team names, which the code scores in one batch after the prompt runs once. Chapter 5 gets a score for each team from a single forward pass through a head that is trained on labelled messages. Label scoring is the bridge from this chapter to that one: it shows that the model already has per-team scores, and that before training they say little about the message.
Working rule: Use label scoring to see which team a model favours before training, and do not route with it. Do not route messages with a prompted model of this size on this task; the 200-message recording is the evidence. Train a head on the labelled messages instead, as chapter 5 does.
이 장에서 결정한 것
이 장의 규칙은 녹화된 메시지 200개에 대해 이 두 모델, 이 프롬프트, 이 제약이라는 범위에서만 유효하다. 더 큰 모델, 다른 프롬프트, 더 긴 표본은 집계 결과를 바꿀 수 있으며, 이 책은 그 표본에서 그중 어느 것도 시험하지 않았다. 이 장이 확립하는 내용은 더 좁다. 원형 프롬프트와 트라이를 쓰면 이 정도 크기의 모델은 유효한 팀을 반환하지만 올바른 팀은 거의 반환하지 못하며, 주시해야 할 수치는 올바른 답의 개수다.
각 결정은 해당 절에서 따로 시험한다. 프롬프트는 첫 번째 절에서, 트라이는 해당 절에서, 탐욕적 디코딩은 해당 절에서, 두 가지 집계는 측정 절에서 다룬다. 이 중 하나라도 바꾸는 독자는 첫 번째 절에서 말한 대로 비교하기 전에 다시 녹화해야 한다. 제약은 모든 답을 유효하게 만들 뿐이며, 답을 올바르게 만드는 것은 훈련뿐이다.
이 장에서 내린 결정은 다음과 같다.
- 라우터 프롬프트는 원형이며, 비교하는 두 모델 모두 이 프롬프트를 사용한다.
- 제약 디코딩은 팀 이름 77개에 대한 토큰 트라이를 사용하며, 탐욕적 디코딩과 고정된 시드를 함께 쓴다.
- 모든 변형은 하나의 고정된 표본에서 유효한 답의 개수와 올바른 답의 개수를 함께 보고한다.
- 라이브 예제는 각 구성 요소가 어떻게 동작하는지 보여 주며, 모델 간 비교는 200개 메시지 녹화본에서만 한다.
이 판의 이 장
2026.11.9판예제 통과 2026년 11월 20이 장에서 5개 예제개 중 5개가 통과한다
영어판 2026.11.9판을 번역한 것이다.