LoRA로 분류 헤드 미세 조정하기
읽는 데 약 30분분 걸린다, 6절에 5개 예제이(가) 있음.
AI로 번역함. 영어 원문을 사람이 검증함. 우리가 책을 만드는 방식
영어판 2026.11.9판을 번역한 것이다. 원문 읽기
이 장을 마치면 레이블이 붙은 메시지로 LoRA를 사용해 분류 헤드를 학습하고, 학습으로 바뀌는 파라미터를 세고, 정해 둔 규칙에 따라 dev 분할에서 인계 임계값을 고르고, 그 임계값을 그것이 만들어 낸 결과 옆에 기록할 수 있다.
지금까지의 라우터는 호스팅 모델 대신 답을 텍스트로 쓰는 스탠드인을 실행하며, 임계값은 아무도 고르지 않았고 모든 출력이 자리표시자라고 표시하는 자리표시자 값 0.5를 쓴다. 답은 팀이어야 하고 임계값은 선택된 값이어야 하므로, 이 장에서는 그 답을 한 번의 순방향 계산으로 팀과 신뢰도를 함께 반환하는 헤드로 교체하고, 어떤 테스트 결과도 보고하기 전에 dev에서 임계값을 고른다. 학습에는 라우터의 팀에 해당하는 레이블이 붙은 메시지가 필요하며, 이는 공개 데이터셋인 BANKING77에서 가져온다. 3장에서 기본 모델로 SmolLM2-135M-Instruct를 골랐고, 이 장에서는 그 모델만 미세 조정한다. 3장에서 말했듯이 360M은 비교용으로만 남는다. 라우터는 2장에서 확정한 샘플로 측정한다.
이 장에서는 어댑터를 360M과 비교하지 않으며, 어떤 것도 증류하거나 양자화하지 않는다. 6장, 7장, 9장에서 어댑터를 증류하고, 양자화하고, 버전 관리한다.
이 부분은 아직 번역되지 않았으므로 영어로 표시된다.
A head that scores the teams
The stand-in writes its answer as text, and a grammar limits that text to the 77 team names while it decodes (chapter 4). A classification head works differently from the stand-in: it keeps the language model's layers and adds one output layer with 77 outputs, one for each team. For each message, the model produces 77 scores. Softmax turns the scores into 77 probabilities that sum to one. The router returns the team with the highest probability, and the confidence is that probability.
The answer is an index into the 77 teams, so it is always one of them. Chapter 4 reaches the same guarantee for a prompted model by constraining its text. This head never writes text, so it has nothing to constrain.
A message costs one forward pass: one run of the network from input to scores, with no loop that writes tokens one at a time. The team and the confidence come from that same pass. This matters for the hand-off. The flag that sends a message to a person is computed from the same probabilities as the team it protects, so the two cannot drift apart between two calls. A separate scoring call would need its own check that the two agree.
The confidence here has a narrower meaning than the stand-in's. In chapter 1, a confidence was the probability the stand-in's recorded answer had, which is not a softmax over teams. In this chapter, the confidence is the softmax probability of the chosen team. The two numbers are both called confidence, and both are compared with a threshold, but they are not the same quantity, so a threshold chosen for one is not a threshold for the other.
When two teams tie, router_lib's classify function takes the lower label index. That follows from torch's argmax, whose documentation says: "If there are multiple maximal values then the indices of the first maximal value are returned." (torch 2.15.0+cpu documentation). A fixed rule for ties keeps the output reproducible.
Working rule: Read the team and the confidence from one forward pass, and take the team as the output with the highest probability. Keep both in one function, so that a hand-off decision and the team it protects come from the same answer. Do not set a head's confidence beside a stand-in's as though they measured the same thing.
이 부분은 아직 번역되지 않았으므로 영어로 표시된다.
Adapters train a small part of the model
Full fine-tuning changes every weight in the base model. LoRA takes a different route. The paper that introduced LoRA, Hu et al. (2021), says it freezes the pre-trained weights and injects trainable low-rank matrices into the layers of the Transformer, and the trained LoRA matrices are the adapter. The base model stays as it was, and the adapter is the part this book stores, loads and versions.
The rank, r, is the inner size of each added matrix, and it is kept small. Peft scales the added update by lora_alpha divided by r (peft 0.21.3, src/peft/tuners/lora/layer.py, line 281: self.scaling[adapter_name] = lora_alpha / r), so lora_alpha sets how strongly the update counts. This book uses a rank of 8, with lora_alpha set to 16. The added matrices go in the projection layers named q_proj and v_proj in each attention block. The abstract does not name those layers, so this choice is the book's, not something the paper prescribes. We recommend it as a starting point, and the recorded adapter below is the test of that recommendation on this task. Other targets are a choice to measure, not a fact about the method.
The head is trained as well. Peft does that for this book's setup: a model built as a sequence classifier lists its classifier and score layers in modules_to_save (peft 0.21.3, src/peft/peft_model.py, line 1830: classifier_module_names = ["classifier", "score"]), so training moves the 77-output layer and the adapter together. Count only the adapter's matrices and you get a smaller number than the one the code trains, and the difference is the head. The next section's run counts the split from the loaded model: 460800 in the adapter and 44352 in the head, which together make 505152.
The adapter's manifest records the base model's revision, so a reader can check that revision against models.toml before scoring.
Working rule: Set the rank, the scaling and the target layers in one configuration, and count the trainable parameters from the loaded model before training starts. Print the total with the head in it. A count that leaves out the head reports part of what training changes, and it will not match what the optimizer updates.
30단계로는 충분하지 않다
이 책은 녹화된 실행을 사용하기 전에, 같은 레시피로 짧게 실행하면 어떤 결과가 나오는지 먼저 보여 준다. 아래의 실행은 dev 밖에 있는 학습 행을 대상으로 학습 단계 30, 배치 크기 8, 시드 0로 진행한 뒤, 2장에서 추출한 고정 표본의 앞 200개 항목인 test_200를 채점한다. 이 실행은 실패이며, 책도 실패로 보여 준다. 짧은 실행은 파이프라인이 처음부터 끝까지 동작하는지만 확인하며, 여기서 맡은 역할은 그것뿐이다.
1"""Train for 30 steps on the recorded recipe, then score test_200 at the placeholder threshold of 0.5.2Read the three step losses against the uniform-guess loss, then the hand-off line at that threshold. The recording runs 1,125 steps."""34import math56import torch78torch.set_num_threads(2)910import router_lib # noqa: E4021112router_lib.setup_runtime()13REPO = "HuggingFaceTB/SmolLM2-135M-Instruct"14STEPS, BATCH, SEED = 30, 8, 01516train, order = router_lib.training_rows(SEED) # the seed sets the shuffled order of the training rows, the one the recording used17tok, model = router_lib.new_classifier(REPO) # SmolLM2 with a 77-way head, LoRA rank 8, lora_alpha 16, on q_proj and v_proj18lora, head = router_lib.parameter_split(model) # LoRA tensors have "lora_" in their names; every other trainable tensor is the head19print(f"trainable parameters: {lora + head}")20print(f"LoRA parameters: {lora}")21print(f"head parameters: {head}")2223losses = router_lib.train_steps(model, tok, train, order, STEPS, BATCH) # AdamW at learning rate 1e-3, router_lib's default24print(f"training steps: {STEPS}")25print(f"batch size: {BATCH}")26print(f"seed: {SEED}")27for step in (10, 20, 30):28 print(f"loss at step {step}: {losses[step - 1]:.2f}") # train_steps returns one loss per step, from step 1 at index 0, so step 10 is index 929print(f"loss of a uniform guess over 77 teams: {math.log(77):.2f}")3031result = router_lib.score_test_sample(model, tok, "test_200", 0.5) # 0.5 is chapter 1's placeholder; this run chooses no threshold32n = result["n"]33print(f"messages on test_200: {n}")34print(f"accuracy on test_200: {result['correct']}/{n} ({result['accuracy']:.1%})")35print(f"handed off at placeholder 0.50: {result['handed_off']}/{n} ({result['handoff_rate']:.1%})")36if result["accuracy_not_handed_off"] is None: # None when no message is kept, so there is no accuracy to print37 print("accuracy on messages not handed off: not defined (0 messages not handed off)")38else:39 m = result["not_handed_off"]40 print(f"accuracy on messages not handed off: {result['correct_not_handed_off']}/{m} ({result['accuracy_not_handed_off']:.1%})")
python lora-thirty-steps.pytrainable parameters: 505152
LoRA parameters: 460800
head parameters: 44352
training steps: 30
batch size: 8
seed: 0
loss at step 10: 4.13
loss at step 20: 6.12
loss at step 30: 4.38
loss of a uniform guess over 77 teams: 4.34
messages on test_200: 200
accuracy on test_200: 5/200 (2.5%)
handed off at placeholder 0.50: 200/200 (100.0%)
accuracy on messages not handed off: not defined (0 messages not handed off)
30단계로는 라우팅에 쓸 수 없다. 이 실행이 학습시킨 헤드는 test_200에서 5/200 (2.5%)를 맞히고, 임시 임계값에서는 모든 메시지를 사람에게 넘긴다. 그 값은 200/200 (100.0%)이다. 모든 메시지를 넘기는 라우터는 어떤 메시지도 팀에 배정하지 않으므로, 라우터가 예측한 레이블은 호출자에게 전혀 도달하지 않는다. 남는 메시지가 없으므로, 출력에 나온 대로 넘기지 않은 메시지에 대한 정확도는 정의되지 않는다.
출력된 세 단계에 걸쳐 손실은 꾸준히 줄어들지 않는다. 10단계에서 4.13, 20단계에서 6.12, 30단계에서 4.38이다. 20단계는 10단계보다 높고, 30단계는 20단계보다 낮지만 10단계보다는 높다. 30단계 동안 얻은 세 점은 학습 곡선이 아니다. 30단계의 손실은 4.34인 균등 추측에 가까우므로, 이 시점에서 헤드는 아직 우연 수준에 가깝다. 균등 추측은 각 팀에 같은 확률인 77분의 1을 주므로 그 손실은 77의 자연로그이다. 기록된 어댑터 실행 절에서 사용하는 녹화본은 같은 레시피를 훨씬 많은 단계 동안 실행하며, 이 책이 보고하는 정확도는 그 녹화본의 것이다.
여기서 test_200를 채점하는 것은 실패를 보고할 뿐이며, 그 결과로 무엇을 선택하지는 않는다. 레시피는 실행 전에 고정되고, 임계값은 나중에 dev에서 정한다. 학습이 되는지 알려면 테스트 표본이 아니라 손실과 dev 측정값을 읽어야 한다. 이것은 2장이 모든 표본에 대해 정한 규칙이다. 테스트 표본에 맞춰 레시피를 조정하면 보고할 깨끗한 수치가 남지 않고, 그 표본은 더 이상 테스트가 아니게 된다.
작업 규칙: 파이프라인이 처음부터 끝까지 동작하는지 확인하려면 짧게 학습시켜 보되, 그 헤드로 라우팅하지 않는다. 미세 조정한 헤드는 측정값에 도달할 만큼 충분히 긴 실행을 마친 뒤, 2장에서 정한 측정값으로 dev 분할에서 판단한다. 몇 개 점으로 이루어진 손실 곡선을 헤드가 학습한다는 증거로 읽지 않는다.
학습 행으로 학습하고, 테스트 행으로는 학습하지 않는다
학습 파일에는 레이블이 붙은 메시지가 들어 있으며, 2장에서는 고정된 시드로 팀별로 이 파일에서 개발 분할을 떼어 냈다. 학습에는 개발용으로 따로 떼어 두지 않은 학습 행을 사용한다. 테스트 파일은 학습 중에 읽지 않는다. thirty steps are not enough의 학습 순서는 개발 분할을 제거하고 남은 행으로 만들며, 시드 0으로 섞으므로 실행할 때마다 같다.
개발 분할은 여러 결정을 좌우한다. 개발 분할에는 학습 파일인 train.csv의 메시지 1003개가 들어 있다. 어떤 학습 단계도 이 메시지를 읽지 않으며, 이 메시지는 임계값을 고르고 마지막 절에서 보정을 확인하는 데만 쓴다.
학습 방법은 어댑터의 매니페스트에 기록되므로, 독자는 어댑터가 무엇으로 학습되었는지 확인할 수 있다. 기록 항목은 기반 모델의 고정된 리비전, 데이터 커밋, 배치 크기, 시드, 스텝 수이다. 학습을 반복하려면 이 값들이 필요하고, 결과가 깨끗한 분할에서 나왔는지 확인하려면 데이터 커밋이 필요하다.
이 규칙은 결과가 좋아 보일 때 가장 중요하다. 테스트 표본을 읽은 학습은 이후에 채점받을 메시지를 이미 본 것이므로, 그 테스트 정확도는 새로운 메시지에 대해 아무것도 측정하지 못한다. 개발 분할과 테스트 분할을 분리해 두어야 다음 절의 테스트 정확도가 공정한 보고가 된다.
작업 규칙: 개발 분할 밖에 있는 학습 행으로만 학습한다. 시드, 배치 크기, 스텝 수, 데이터 커밋을 매니페스트에 기록한다. 개발 분할이 너무 작아 임계값을 정할 수 없으면, 2장에서 말한 대로 테스트 파일이 아니라 학습 파일에서 메시지를 더 뽑는다.
이 부분은 아직 번역되지 않았으므로 영어로 표시된다.
Use the recorded adapter
The working router uses banking77-lora-v1: the adapter from the full recorded run, version 1, written by recordings/lora_full.py. That script trained the adapter once, on the recipe in the section on training rows, and wrote its files and a manifest. The manifest holds the base model's revision, the data commit, the threshold, the recipe's hash and the hashes of the output files. Offline, the adapter loads and scores test_200 at the threshold from its manifest, and nothing is trained.
Take the adapter as it was recorded. A different recipe becomes a new run, named v2; the book does not edit the adapter by hand. Keeping the recording fixed is what lets a reader check the numbers in this chapter against the files they downloaded.
1"""Load the recorded adapter banking77-lora-v1 and score test_200 at the threshold in its manifest; no training runs here.2Read the accuracy line with the two hand-off lines printed under it."""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"19manifest = json.loads((RECORDED / "manifest.json").read_text())20threshold = manifest["handoff_threshold"] # the threshold the recording chose on dev; this script chooses none2122tokenizer, model = router_lib.load_classifier(RECORDED / "adapter") # the base model comes from the adapter's config, at its revision in models.toml23test = router_lib.read_rows("test")24sample = router_lib.read_sample("test_200")25golds = [test[i][1] for i in sample]26preds, confs = router_lib.classify(model, tokenizer, [test[i][0] for i in sample]) # a tie goes to the lower label index2728result = router_lib.metrics(preds, golds, confs, threshold) # a message is handed off when its confidence is below the threshold29n = result["n"]30print(f"adapter: {manifest['adapter']}")31print(f"handoff threshold from manifest: {threshold:.2f}")32print(f"messages on test_200: {n}")33print(f"accuracy on test_200: {result['correct']}/{n} ({result['accuracy']:.1%})")34print(f"handed off: {result['handed_off']}/{n} ({result['handoff_rate']:.1%})")35if result["accuracy_not_handed_off"] is None: # None when no message is kept, so there is no accuracy to print36 print("accuracy on messages not handed off: not defined (0 messages not handed off)")37else:38 m = result["not_handed_off"]39 print(40 f"accuracy on messages not handed off: {result['correct_not_handed_off']}/{m} "41 f"({result['accuracy_not_handed_off']:.1%})"42 )
python lora-recorded-adapter.pyadapter: banking77-lora-v1
handoff threshold from manifest: 0.63
messages on test_200: 200
accuracy on test_200: 172/200 (86.0%)
handed off: 33/200 (16.5%)
accuracy on messages not handed off: 156/167 (93.4%)
The recorded adapter is right on 172/200 (86.0%) of the messages, against 9/200 (4.5%) for the prompted 135M model that chapter 4 measured on the same 200. The 30-step run, at 5/200 (2.5%), falls below the prompted model. A handed-off message counts as wrong when its team is wrong. The output beside this paragraph gives the hand-off count and the accuracy on messages not handed off, each with its count and denominator, as chapter 2 requires.
The threshold is not chosen on this sample. It came from the manifest, which the section on choosing the threshold explains. It is the threshold the recorded adapter's hand-off counts on test_200 use: 0.63. Reading it from the manifest keeps the choice on dev, where the rule made it.
The recorded adapter is the router's model, and the stand-in is the baseline. The two were measured with different thresholds, so their hand-off counts are not the same kind of result. Compare them on the same messages, with each threshold named beside its count. The comparison below does that for test_200, reading the stand-in's recorded answers for the same messages.
1"""Set the stand-in's recorded answers beside the recorded adapter's live predictions on the same 200 test messages.2The last two lines count where the models disagree."""34import os56os.environ["HF_HUB_OFFLINE"] = "1"7os.environ["TRANSFORMERS_OFFLINE"] = "1"89import json # noqa: E40210import math # noqa: E4021112import torch # noqa: E4021314torch.set_num_threads(2)1516import router_lib # noqa: E4021718router_lib.setup_runtime()19STANDIN_THRESHOLD = 0.5 # chapter 1's placeholder; the stand-in's own threshold is never chosen on dev20ADAPTER = router_lib.HERE / "data" / "recorded" / "lora-full"2122with open(router_lib.HERE / "data" / "recorded" / "standin-baseline" / "answers.jsonl") as f:23 answers = {row["index"]: row for row in map(json.loads, f)} # keyed by the test-row index that read_sample returns24threshold = json.loads((ADAPTER / "manifest.json").read_text())["handoff_threshold"]2526test = router_lib.read_rows("test")27sample = router_lib.read_sample("test_200")28golds = [test[i][1] for i in sample]29standin_preds = [answers[i]["label"] for i in sample]30standin_confs = [math.exp(answers[i]["logprob"]) for i in sample] # the recording stores log-probabilities; exp turns one back into the probability its answer had3132tokenizer, model = router_lib.load_classifier(ADAPTER / "adapter")33adapter_preds, adapter_confs = router_lib.classify(model, tokenizer, [test[i][0] for i in sample])3435standin = router_lib.metrics(standin_preds, golds, standin_confs, STANDIN_THRESHOLD)36adapter = router_lib.metrics(adapter_preds, golds, adapter_confs, threshold)37n = standin["n"]38s_right = [p == g for p, g in zip(standin_preds, golds)]39a_right = [p == g for p, g in zip(adapter_preds, golds)]4041print(f"messages on test_200: {n}")42print(f"stand-in correct: {standin['correct']}/{n} ({standin['accuracy']:.1%})")43print(f"adapter banking77-lora-v1 correct: {adapter['correct']}/{n} ({adapter['accuracy']:.1%})")44print(f"stand-in placeholder threshold: {STANDIN_THRESHOLD:.2f}")45print(f"stand-in handed off: {standin['handed_off']}/{n} ({standin['handoff_rate']:.1%})")46print(f"adapter threshold from manifest: {threshold:.2f}")47print(f"adapter handed off: {adapter['handed_off']}/{n} ({adapter['handoff_rate']:.1%})")48print(f"right for the adapter, wrong for the stand-in: {sum(a and not s for a, s in zip(a_right, s_right))}/{n}")49print(f"right for the stand-in, wrong for the adapter: {sum(s and not a for a, s in zip(a_right, s_right))}/{n}")
python compare-with-standin.pymessages on test_200: 200
stand-in correct: 109/200 (54.5%)
adapter banking77-lora-v1 correct: 172/200 (86.0%)
stand-in placeholder threshold: 0.50
stand-in handed off: 9/200 (4.5%)
adapter threshold from manifest: 0.63
adapter handed off: 33/200 (16.5%)
right for the adapter, wrong for the stand-in: 69/200
right for the stand-in, wrong for the adapter: 6/200
Matching the two models message by message shows which messages each one misses. The stand-in's answers come from its recording, and the adapter runs live on the same 200 messages. The stand-in's confidence is the probability its recorded answer had, from the recording's log-probability. The stand-in's threshold is chapter 1's placeholder, 0.50, and the output labels it as one. Its hand-off count, 9/200 (4.5%), says what that placeholder does to the stand-in, and nothing about the stand-in's own threshold, which was never chosen on dev. The adapter hands off 33/200 (16.5%) at 0.63.
The adapter is right on 172/200 (86.0%) of these messages, the stand-in on 109/200 (54.5%). Where the two disagree, the adapter alone is right on 69/200, and the stand-in alone on 6/200. Two accuracies can be equal while the two models miss different messages, and the disagreement counts show where that happens.
The comparison is one sample of 200 messages. Chapter 1 said that its small sample can show that a router fails, but cannot tell two routers apart with confidence. Chapter 1's sample was smaller. The discordant counts here, 69/200 against 6/200, are stronger evidence than that sample could give. For a firmer claim, run the same comparison on the full test_1001 sample, which the stand-in's recording also covers.
Working rule: Compare two models only on the same messages, and name the threshold each one used beside its count. When one threshold is a placeholder, say so beside its count, and do not read its hand-off count as the model's own result.
dev에서 임계값 정하기
임계값은 메시지를 사람에게 넘기는 기준선이다. 2장에서 그 척도를 정했고, 1장에서는 임계값을 자리표시자로 남겨 두었다. 이 책의 규칙은 dev 분할만으로 임계값을 정한다. 0.01 간격의 격자에서, 인계되지 않은 메시지의 정확도가 목표값 0.90 이상이 되는 가장 낮은 신뢰도 임계값을 고른다. 이 규칙은 값과 함께 매니페스트에 기록하므로, 독자는 규칙이 낳은 숫자뿐 아니라 규칙 자체도 볼 수 있다. 2장이 요구하듯이 테스트 표본은 여기에 관여하지 않는다.
1"""Find the hand-off threshold on dev by the manifest's rule, then check it against the manifest's value.2Read the chosen threshold beside the three threshold lines. test_200 is not read here."""34import json56import torch78torch.set_num_threads(2)910import router_lib # noqa: E4021112router_lib.setup_runtime()13RECORDED = router_lib.HERE / "data" / "recorded" / "lora-full"14manifest_threshold = json.loads((RECORDED / "manifest.json").read_text())["handoff_threshold"]15TARGET = 0.90 # the book's target accuracy on messages not handed off: a choice the book makes, not one the data sets1617tokenizer, model = router_lib.load_classifier(RECORDED / "adapter")18rows = router_lib.read_rows("train")19dev = router_lib.read_sample("dev")20golds = [rows[i][1] for i in dev]21preds, confs = router_lib.classify_by_length(model, tokenizer, [rows[i][0] for i in dev]) # batches by length to pad less; results come back in dev order22n = len(dev)23chosen = router_lib.choose_threshold(preds, golds, confs, TARGET) # the rule lives in router_lib: the lowest 0.01 grid value that meets TARGET; None if no value meets it, and the prints below would then fail2425print(f"dev messages: {n}")26print(f"target accuracy on messages not handed off: {TARGET:.2f}")27print(f"chosen threshold: {chosen:.2f}")28print(f"threshold in manifest: {manifest_threshold:.2f}")29print(f"chosen threshold matches manifest: {'yes' if chosen == manifest_threshold else 'no'}") # both come from the same 0.01 grid, so equal means the same threshold30for t in sorted({0.50, chosen, 0.90}): # 0.50 is chapter 1's placeholder; a set drops the chosen value if it is one of the other two31 r = router_lib.metrics(preds, golds, confs, t)32 print(f"threshold {t:.2f} handed off: {r['handed_off']}/{n} ({r['handoff_rate']:.1%})")33 print(f"threshold {t:.2f} accuracy on messages not handed off: {r['correct_not_handed_off']}/{r['not_handed_off']} ({r['accuracy_not_handed_off']:.1%})")
python choose-threshold-on-dev.pydev messages: 1003
target accuracy on messages not handed off: 0.90
chosen threshold: 0.63
threshold in manifest: 0.63
chosen threshold matches manifest: yes
threshold 0.50 handed off: 80/1003 (8.0%)
threshold 0.50 accuracy on messages not handed off: 811/923 (87.9%)
threshold 0.63 handed off: 148/1003 (14.8%)
threshold 0.63 accuracy on messages not handed off: 770/855 (90.1%)
threshold 0.90 handed off: 352/1003 (35.1%)
threshold 0.90 accuracy on messages not handed off: 620/651 (95.2%)
기록된 어댑터로 dev를 채점하고 규칙을 적용하면 임계값은 0.63이다. 매니페스트의 값과 대조한 결과는 yes이며, 둘이 일치하지 않는다면 매니페스트와 규칙이 서로 어긋난다는 뜻이다.
세 가지 임계값으로 상충 관계를 보이며, 아래 표는 각 개수와 비율을 나란히 놓는다. 임계값을 올리면 인계되는 메시지가 줄어드는 일은 없고, 규칙은 목표를 충족하는 가장 낮은 값을 고른다. 각 행은 같은 dev 메시지에 같은 어댑터를 쓴 결과이므로 달라지는 것은 임계값뿐이다.
| 임계값 | dev에서 인계된 수 | dev에서 인계되지 않은 메시지의 정확도 |
|---|---|---|
| 0.50 | 80/1003 (8.0%) | 811/923 (87.9%) |
| 0.63, 선택됨 | 148/1003 (14.8%) | 770/855 (90.1%) |
| 0.90 | 352/1003 (35.1%) | 620/651 (95.2%) |
0.50에서는 라우터가 더 많은 메시지를 직접 처리하지만, 그렇게 처리한 메시지의 정확도가 낮아 목표에 미치지 못한다. 0.90에서는 직접 처리한 메시지의 정확도가 세 값 중 가장 높지만, 사람에게 넘어가는 dev 메시지가 가장 많다. 선택된 값은 세 임계값 중 목표를 충족하는 가장 낮은 값이므로, 0.50보다 많이, 0.90보다 적게 메시지를 인계한다. 표는 인계라는 비용과 정확도라는 이득을 보여 준다. 목표를 어디에 둘지는 규칙이 정할 수 없는 업무상의 선택이다. 이 책은 직접 처리한 메시지의 정확도로 0.90를 쓰며, 자체 라우터를 운용하는 은행이라면 이 상충 관계에서 자기 목표를 읽어 낼 것이다.
프로덕션에서도 어댑터는 그대로이지만 어댑터가 받는 메시지는 그렇지 않다. 제품 문제로 한 주 동안 한 팀에 관한 메시지가 대량으로 들어온다고 하자. 임계값은 dev의 메시지 구성에서 정해졌으므로, 어댑터가 전혀 바뀌지 않아도 인계 비율은 저절로 움직일 수 있다. 어댑터에 변화가 없는데 인계가 늘었다면, 먼저 메시지 구성을 확인하라는 신호이다. 인계 비율이 ‘맞아 보임’ 상태가 될 때까지 임계값을 눈대중으로 옮기면, 이 규칙을 고른 이유였던 성질, 곧 라우터가 직접 처리하는 dev 메시지에서 목표 이상의 정확도를 얻는다는 성질을 포기하게 된다.
신뢰도는 그 팀이 맞을 확률이 아니다. Guo et al. (2017)은 자신들의 네트워크가 "poorly calibrated"라고 보고하는데, 이는 신뢰도가 실제로 맞는 빈도와 일치하지 않는다는 뜻이다. 이 책은 dev에서 자체 어댑터를 점검한다. dev 메시지를 신뢰도에 따라 다섯 구간으로 나누고, 각 구간에 개수, 정확도, 평균 신뢰도를 구한다. 이 가운데 뒤의 두 양이 곧 Guo et al.이 보정을 측정할 때 비교하는 두 양이다. dev를 신뢰도로 묶어 보면 0.9가 열 번 중 아홉 번을 뜻하는지 알 수 있다.
1"""Group the dev messages into five bands by the adapter's confidence, and print each band's count, accuracy and mean confidence.2Read the top band's mean confidence against its accuracy. Only dev is read."""34import os56os.environ["HF_HUB_OFFLINE"] = "1"7os.environ["TRANSFORMERS_OFFLINE"] = "1"89import torch # noqa: E4021011torch.set_num_threads(2)1213import router_lib # noqa: E4021415router_lib.setup_runtime()16RECORDED = router_lib.HERE / "data" / "recorded" / "lora-full"17BANDS = [(0.0, 0.2), (0.2, 0.4), (0.4, 0.6), (0.6, 0.8), (0.8, 1.0)]1819tokenizer, model = router_lib.load_classifier(RECORDED / "adapter")20rows = router_lib.read_rows("train")21dev = router_lib.read_sample("dev")22golds = [rows[i][1] for i in dev]23preds, confs = router_lib.classify_by_length(model, tokenizer, [rows[i][0] for i in dev]) # results come back in dev order, so index i matches golds[i]2425print(f"dev messages: {len(dev)}")26counted = 027for lo, hi in BANDS:28 last = hi == 1.029 members = [i for i, c in enumerate(confs) if lo <= c < hi or (last and c == 1.0)] # lower edges are in, upper edges out; the top band also takes 1.0, so each message is counted once30 counted += len(members)31 name = f"band {lo:.1f}-{hi:.1f}"32 print(f"{name} messages: {len(members)}")33 if members:34 correct = sum(preds[i] == golds[i] for i in members)35 print(f"{name} correct: {correct}/{len(members)} ({correct / len(members):.1%})")36 print(f"{name} mean confidence: {sum(confs[i] for i in members) / len(members):.1%}")37 else:38 print(f"{name} correct: not defined (0 messages)")39 print(f"{name} mean confidence: not defined (0 messages)")40print(f"messages in bands: {counted}")
python calibration-bands-on-dev.pydev messages: 1003
band 0.0-0.2 messages: 1
band 0.0-0.2 correct: 1/1 (100.0%)
band 0.0-0.2 mean confidence: 19.9%
band 0.2-0.4 messages: 41
band 0.2-0.4 correct: 10/41 (24.4%)
band 0.2-0.4 mean confidence: 32.9%
band 0.4-0.6 messages: 92
band 0.4-0.6 correct: 49/92 (53.3%)
band 0.4-0.6 mean confidence: 51.0%
band 0.6-0.8 messages: 123
band 0.6-0.8 correct: 84/123 (68.3%)
band 0.6-0.8 mean confidence: 70.6%
band 0.8-1.0 messages: 746
band 0.8-1.0 correct: 693/746 (92.9%)
band 0.8-1.0 mean confidence: 96.4%
messages in bands: 1003
dev 메시지의 대부분은 0.8에서 1.0 사이의 최상위 구간에 속하며, 이 구간에는 746개가 있다. 0.0에서 0.2 사이의 최하위 구간에는 1개가 있는데, 낮은 신뢰도에 대해 그 정확도로 말할 수 있는 바가 없을 만큼 적다.
dev에서 신뢰도는 메시지를 유용하게 정렬하지만, 맨 위에서는 신뢰도가 정확도보다 높다. 최상위 구간의 평균 신뢰도는 96.4%이고 정확도는 693/746 (92.9%)이다. 다섯 구간 중 네 구간은 정확도가 해당 구간의 범위 안에 있으며, 최하위 구간만 예외이고 그 구간에는 메시지가 하나뿐이다. 두 번째 구간부터는 위로 갈수록 정확도가 오른다. 가운데 두 구간에서는 정확도와 평균 신뢰도가 서로 가깝지만, 0.2에서 0.4 사이 구간에서는 평균 신뢰도가 정확도보다 훨씬 높다.
구간으로는 더 알 수 없다. 0.2에서 0.4 사이 구간에는 메시지가 41개 있다. 여기의 모든 수치는 임계값을 정하는 데도 쓰인 하나의 dev 표본에서 나왔으므로, 어느 것도 새 메시지에서 어댑터가 얼마나 잘 보정될지를 보여 주지 않는다.
규칙이 고른 라우터는 dev에서의 경험적 기준선이며, 규칙과 데이터와 함께 기록된다. 이는 임계 기준일 뿐 메시지의 모델이 아니므로, 그 수치는 dev의 메시지 구성을 설명한다. 독자는 인계 비율과 직접 처리한 메시지의 정확도를 라우터의 결과로 받아들이고, 메시지 구성이 달라지면 dev 규칙을 다시 점검한다.
작업 규칙: 명시한 규칙에 따라 dev 분할에서 임계값을 정하고, 그 값과 규칙을 어댑터의 매니페스트에 기록한다. 인계 비율을 직접 처리한 메시지의 정확도와 함께, 각각의 개수를 붙여 보고하고, 선택한 값의 양쪽으로 적어도 하나씩 설정을 보인다. 신뢰도를 기준선으로 믿기 전에 dev에서 보정을 점검하고, 메시지 구성이 바뀌면 훈련 파일에서 새로 뽑은 dev로 임계값을 다시 정한다.
이 판의 이 장
2026.11.9판예제 통과 2026년 11월 20이 장에서 5개 예제개 중 5개가 통과한다
영어판 2026.11.9판을 번역한 것이다.