라우터를 양자화하고 무엇이 달라지는지 측정하기
읽는 데 약 32분분 걸린다, 5절에 2개 예제이(가) 있음.
AI로 번역함. 영어 원문을 사람이 검증함. 우리가 책을 만드는 방식
영어판 2026.11.9판을 번역한 것이다. 원문 읽기
이 장을 마치면 파인튜닝한 라우터의 백본 가중치를 함수 한 번의 호출로 8비트 정수로 저장하고, 고정된 표본에서 예측이 바뀌는 개수를 세고, 그 개수가 보여 주는 것과 보여 주지 않는 것을 설명할 수 있다. 속도를 어떻게 측정하는지, 그리고 한 대의 기계에서 기록한 결과가 무엇을 보였는지도 확인한다.
양자화한 라우터 사본은 공간을 덜 차지하겠지만, 문제는 그 사본이 여전히 같은 방식으로 답하는가이다. 5장은 라우터를 어댑터 하나, 곧 banking77-lora-v1로 남겼으며, 이 어댑터의 가중치는 float32이다. 이 어댑터의 인계 임곗값은 0.63이고, 5장의 규칙에 따라 dev 분할에서 정했다. 양자화는 가중치를 더 적은 비트로 저장하는 일이다. 양자화한 모델은 가중치가 차지하는 공간이 줄어들지만, 다른 답을 내놓을 수도 있다. 이 장은 두 번째 부분을 5장에서 채점한 테스트 메시지 200개의 고정 표본, test_200에서 측정한다. 양자화에 비용이 들지 않는다고 주장하지는 않는다.
이 사본은 은행의 지원 메시지를 분류하는 인박스에서 float32 어댑터를 대신할 수 있으며, 그러기 전에 세 가지 질문에 답해야 한다. 사본의 가중치는 어댑터와 비교해 몇 바이트를 차지하는가? 사본은 같은 메시지에 같은 방식으로 답하는가? 그리고 인박스를 서비스하는 기계에서 더 빠른가? 앞의 두 질문은 모델의 형태와 고정된 표본으로 여기서 측정할 수 있다. 세 번째 질문의 답은 이름이 밝혀진 기계에서 기록한 결과에서 나오며, 속도를 다루는 절에서 그 기록이 무엇을 보였고 무엇을 다루지 않는지 설명한다. 각 답은 분모가 붙은 개수이거나, 입력이 명시된 비율이다.
이 부분은 아직 번역되지 않았으므로 영어로 표시된다.
One call to quantize the linear layers
A linear layer is a weight matrix that maps one vector to another. The router's backbone is made of them. Quantizing a layer stores each of its weights as an 8-bit integer, with a scale that maps the integers back to approximate float values. Fewer bits per weight means fewer bytes for the layer, and the answers can move, because the values the layer computes are no longer the exact ones.
The scale is what makes the scheme work for a whole matrix. A single scale for an entire matrix has to cover its largest weight, so the rows whose weights are small get a coarse grid. Jacob et al. (2018) report that a shared resolution gives channels with narrow ranges much larger relative error (arXiv:1712.05877). That is a CNN result, so here it is a reason to test per-row scales, not a measurement. A per-row scale lets each output row use the full range of the 8-bit integers for its own weights. That is why the byte count adds one float32 scale for each output row. The scales are few, but they are not free, so the byte count below includes them.
The helper in this book, int8_classifier, names its scheme in its docstring: per-row int8 weights, with float32 activations. The scheme is torchao's Int8WeightOnlyConfig, which the torchao source at v0.18.0 describes as "int8 weight-only symmetric per-channel quantization to linear layers". The helper applies it in three steps. It merges the adapter's weights into the base model with PEFT's merge_and_unload. It calls quantize_ from torchao.quantization with Int8WeightOnlyConfig, and passes a filter that selects every nn.Linear layer except the one named score. Then it returns the model in evaluation mode. The int8 copy, named banking77-lora-v1-int8 in the recordings, is the model the helper returns: a derived model built from the adapter, not a second adapter. The output layer, score, is the head that chapter 5 trained, and the section on it explains why the helper leaves it out.
The merge comes first for a reason. Chapter 5 described the adapter as a small set of matrices beside the base model's layers. Merging folds the adapter's update into the base weights, so each layer is one weight matrix, quantized once, and the layer count describes the router. Without the merge, the same call would also quantize the adapter's own matrices as separate int8 layers.
Older PyTorch code uses torch.ao.quantization.quantize_dynamic, which also stores Linear weights as int8 and quantizes activations as it runs, a different scheme. PyTorch 2.15 deprecates it, and its warning points to torchao's quantize_ (PyTorch v2.15.0, torch/ao/quantization/utils.py), which the torchao README at v0.18.0 shows as the migration. The examples in this book call no deprecated API themselves.
1"""Counts the backbone Linear layers the int8 copy quantizes, and the weight bytes they store, from their shapes.2The prose's saving rests on the last printed line, the int8 share of float32 weight bytes; the head assert checks that the score head is not quantized."""34import os56os.environ["HF_HUB_OFFLINE"] = "1"7os.environ["TRANSFORMERS_OFFLINE"] = "1"89import torch # noqa: E4021011torch.set_num_threads(2) # the counts come from shapes, so the thread count changes no printed line1213import router_lib # noqa: E4021415router_lib.setup_runtime() # fixes the seeds, requires deterministic algorithms and sets float32 as the default dtype16RECORDED = router_lib.HERE / "data" / "recorded" / "lora-full"1718_, model = router_lib.int8_classifier(RECORDED / "adapter") # merges the adapter, then quantizes every backbone Linear, not score19layers = router_lib.backbone_linears(model) # (name, layer) pairs, all except score20quantized = [layer for _, layer in layers if router_lib.is_int8(layer)] # a torchao int8 weight, not a float one21weights = sum(layer.weight.numel() for _, layer in layers)22rows = sum(layer.weight.shape[0] for _, layer in layers) # weight shape is (output rows, input size)2324print(f"backbone Linear layers: {len(layers)}")25print(f"backbone Linear layers quantized to int8: {len(quantized)}")26head_quantized = router_lib.is_int8(model.score)27assert not head_quantized, "the score head must stay float32"28print(f"score head quantized: {'yes' if head_quantized else 'no'}")29print(f"score head weight dtype: {model.score.weight.dtype}")30print(f"weights in backbone Linear layers: {weights}")31print(f"output rows in backbone Linear layers: {rows}")32float_bytes = 4 * weights33int8_bytes = 1 * weights + 4 * rows # one byte a weight, plus one float32 scale (4 bytes) for each output row34print(f"weight bytes, int8 as a share of float32: {int8_bytes / float_bytes:.1%}")
python int8-layers-and-bytes.pybackbone Linear layers: 210
backbone Linear layers quantized to int8: 210
score head quantized: no
score head weight dtype: torch.float32
weights in backbone Linear layers: 106168320
output rows in backbone Linear layers: 155520
weight bytes, int8 as a share of float32: 25.1%
Building the int8 copy and counting its layers and their weights shows what the helper quantized. The backbone has 210 linear layers, and the int8 copy quantizes 210 of them. Those layers hold 106168320 weights, in 155520 output rows.
The last line is arithmetic on shapes, and it is not a measurement of a file or a process. A float32 weight takes 4 bytes. An int8 weight takes 1 byte, and the calculation adds one float32 scale, 4 bytes, for each output row, because that is the convention the helper's scheme names. Over the weights in those layers, the int8 copy takes 25.1% of the float32 bytes. A quarter of that is the weights themselves, and the rest is the scales. The figure covers only the weights of these layers. It leaves out every other tensor the model holds, so it says nothing about the size of a file on disk, and nothing about the memory a running router uses.
The bytes matter on the serving machine only if its memory has to hold the weights. Whether it does depends on the machine and the rest of the process, which this chapter does not measure. The ratio tells a reader how much of the weight budget the copy frees.
Importing torchao prints warnings to standard error, and an example's first run may print a load report from transformers. They come from the libraries' own import code, not from a call the examples make, and nothing in the examples suppresses or acts on them. Some lines say torchao could not load its GPU-only kernel libraries, which the CPU path does not use. A SyntaxWarning from torchao's own source shows only on the first import, before Python caches the bytecode. Notices that register_constant() is deprecated come from torch and are triggered by torchao's import. The load report lists score.weight as MISSING: the base checkpoint has no classification head, so transformers starts a new one, and the adapter's saved head replaces it. None of these changes an output line. The book pins torchao at 0.18.0 in its requirements file, and every example uses that pin.
Working rule: Quantize only the layers you can name, leave the output layer in float32, and count the bytes from the shapes before you claim any saving. Report the saving as a ratio of weight bytes, with the count of layers beside it, and never as a file size or as a speed.
이 부분은 아직 번역되지 않았으므로 영어로 표시된다.
Count the predictions that change
Quantizing changes the numbers a layer computes, so the answers can change too. The test of a quantized copy is whether it answers the same messages the same way.
Scoring test_200 with both copies at the threshold in chapter 5's manifest shows whether they answer alike. For each copy the run counts the correct answers, the hand-offs and the accuracy on the messages not handed off. It then counts the messages whose team differs between the two copies, and the hand-off decisions that differ. The same run, int8-changed-predictions, also scores a third copy, with the head quantized too, for the section on the score head.
The two copies are not treated alike on purpose. The float32 side is the adapter as chapter 5 loaded it, unmerged, while the int8 side is merged first, because the helper merges before it quantizes. So the count below holds the merge and the quantization together. The run never scores a merged float32 copy on its own, and the chapter does not claim that the merge alone changes nothing.
1"""Scores test_200 with the float32 adapter, its int8 copy and the copy with the head in int8, at the threshold in chapter 5's manifest.2The prose's point rests on the line that counts predictions changed by int8, read with the hand-off line 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) # two threads for these forward passes; the speed section's recording uses four1415import router_lib # noqa: E4021617router_lib.setup_runtime() # fixes the seeds, requires deterministic algorithms and sets float32 as the default dtype18RECORDED = router_lib.HERE / "data" / "recorded" / "lora-full"19threshold = json.loads((RECORDED / "manifest.json").read_text())["handoff_threshold"] # chosen on dev in chapter 5, stored in the manifest20test = router_lib.read_rows("test") # (text, label index) pairs21sample = router_lib.read_sample("test_200") # fixed row indices, so every copy scores the same messages22golds = [test[i][1] for i in sample] # index 1 of each row is its gold team23texts = [test[i][0] for i in sample]2425tokenizer, float_model = router_lib.load_classifier(RECORDED / "adapter") # the adapter as chapter 5 loaded it, unmerged26float_preds, float_confs = router_lib.classify_by_length(float_model, tokenizer, texts) # results in the order of texts27_, int8_model = router_lib.int8_classifier(RECORDED / "adapter") # merged first, then backbone quantized, head float3228int8_preds, int8_confs = router_lib.classify_by_length(int8_model, tokenizer, texts)29_, head_model = router_lib.int8_classifier_all_linears(RECORDED / "adapter") # as above, with the score head quantized too30head_preds, head_confs = router_lib.classify_by_length(head_model, tokenizer, texts)3132print(f"handoff threshold from manifest: {threshold:.2f}")33print(f"messages on test_200: {len(texts)}")34router_lib.print_copy_report("float32", float_preds, float_confs, golds, threshold) # a handed-off message is wrong if its team is wrong; the last measure divides by kept messages only35router_lib.print_copy_report("int8", int8_preds, int8_confs, golds, threshold)36changed, handoffs = router_lib.count_changes(float_preds, float_confs, int8_preds, int8_confs, threshold) # a changed prediction is a different team, handed off or not; a changed hand-off is a confidence on the other side of the threshold37print(f"predictions changed by int8: {changed}/{len(texts)} ({changed / len(texts):.1%})")38print(f"hand-off decisions changed by int8: {handoffs}/{len(texts)}")39changed_head, _ = router_lib.count_changes(float_preds, float_confs, head_preds, head_confs, threshold)40print(f"predictions changed with the head in int8 too: {changed_head}/{len(texts)}")
python int8-changed-predictions.pyhandoff threshold from manifest: 0.63
messages on test_200: 200
float32 accuracy on test_200: 172/200 (86.0%)
float32 handed off: 33/200 (16.5%)
float32 accuracy on messages not handed off: 156/167 (93.4%)
int8 accuracy on test_200: 172/200 (86.0%)
int8 handed off: 33/200 (16.5%)
int8 accuracy on messages not handed off: 156/167 (93.4%)
predictions changed by int8: 0/200 (0.0%)
hand-off decisions changed by int8: 0/200
predictions changed with the head in int8 too: 1/200
On this sample the int8 copy changes 0/200 (0.0%) predictions and 0/200 hand-off decisions. The copy that also quantizes the head is counted in the section on the score head. The output beside this paragraph gives each copy's accuracy, its hand-offs and its accuracy on the messages not handed off, each with its denominator.
The three measures are the ones chapter 2 defined, and each has its denominator. Accuracy divides the correct messages by all 200, so a handed-off message counts as wrong if its team is wrong. The hand-off rate divides the messages below the threshold by all 200. Accuracy on the messages not handed off divides the correct ones among the kept messages, and it is not defined when none are kept. The changed-prediction count uses the same 200 messages and asks a question the three measures do not: did the two copies agree on each one? Agreement is not correctness, which is why the output also prints the accuracy.
A changed prediction is not automatically a loss. It can turn a wrong team into a right one, or a right team into a wrong one, and the count alone does not say which. To read the direction, compare each copy's team with the gold label on every message the copies disagree on. Accuracy can hide this. Two copies can have the same accuracy while different messages are right on each, so the same total says nothing about which messages moved. When the count is zero, there are no flips to read in either direction. A reader who gets a non-zero count should read the flips before reading the totals.
A flip has a concrete cost once a copy serves the queue. Suppose the float32 adapter sends a message to card_arrival and the int8 copy sends the same message to card_delivery_estimate. Both are teams, and only one of them can be the message's gold label, so the change either fixes an answer or breaks one, unless both teams are wrong. The inbox sends the message to one team either way. The change would reach the support staff who work that team's queue, and nobody would see it in a total. The count is what makes that change visible before the copy serves any message.
Read the changed-prediction count as one result, from one adapter at one threshold, and not as a guarantee. A different sample, adapter or threshold could show a change, and a sample of 200 can miss a change that is rare in a full stream of messages.
The count is about predictions and nothing else. The copy also keeps its activations in float32, as the helper's docstring says, so this count tells you nothing about a copy that quantizes activations as well. This chapter does not measure that copy.
Working rule: Count the changed predictions on the same messages, at the same threshold, for both copies, and print each count with its denominator beside the accuracy and the hand-off count. When the count is zero, report it as zero on that sample, and name the sample and the adapter it was taken from.
점수 헤드는 float32로 유지한다
점수 헤드는 출력이 77개인 층이며, 출력 하나가 팀 하나에 대응한다. 이 층의 소프트맥스가 5장에서 임계값과 비교하는 신뢰도를 내고, 가장 큰 확률이 라우터가 반환하는 팀이 된다. 도우미는 호출에서 헤드를 제외하므로 헤드는 float32로 남는다. 이 절에서는 이 책이 그렇게 선택한 이유와, 그 근거로 집계가 보여 주는 내용을 설명한다.
이 장에서 서비스하는 복사본은 헤드를 float32로 유지하며, 이 선택은 int8-changed-predictions의 집계 하나에 근거한다. 헤드까지 int8로 바꾸면 이 표본에서 예측 1/200개가 바뀐다. 이 집계는 층별 민감도의 순위를 매기지 않으며, 변화가 헤드에서 오는지 아닌지를 이 장은 주장하지 않는다.
위험한 메시지는 신뢰도가 임계값보다 조금 높은 메시지이다. 헤드가 바뀌면 이런 메시지가 임계값 아래로 내려갈 수 있고, 그러면 그 메시지는 팀이 아니라 사람에게 넘어간다. 이전 절의 인계 결정 변경 횟수는 복사본이 이런 결정을 하나라도 바꾸는지 보여 주며, 이번 실행에서 int8 복사본은 인계 결정을 0/200개 바꾼다.
도우미가 헤드를 어떻게 처리했는지는 int8-layers-and-bytes에 있다. 이 예제가 단언하듯이 헤드는 양자화되지 않으며, 가중치는 torch.float32이다. 출력된 이 줄들은 첫 번째 절의 층 수와 같은 실행에서 나온 것이므로 둘을 직접 비교할 수 있다.
예측 변경 횟수는 int8 복사본 전체와, 헤드까지 양자화한 복사본에 대해 집계한 값이다. 어느 쪽도 층별로 나누지 않으므로 변화가 어느 층에서 오는지는 말해 주지 못한다. 그것을 찾으려면 층을 하나씩 양자화하고 dev 분할에서 다시 집계해야 한다.
작업 규칙: 사용자가 의존하는 어떤 팀이나 인계 결정도 양자화한 헤드가 바꾸지 않는다는 점을, 선택한 임계값에서 dev 분할로 집계해 보이지 못하는 한 점수 헤드는 float32로 유지한다. 어느 임계값에서 집계했는지 밝힌다.
녹화본으로 속도 측정하기
가중치에 필요한 바이트가 줄었다고 해서 모델이 빨라지는 것은 아니며, 이 장도 그렇게 주장하지 않는다. int8 사본이 특정 CPU에서 더 빠르게 계산되는지는 그 CPU에서 실행되는 산술 루틴에 달려 있다. 그래서 이 책은 이름을 밝힌 한 대의 머신에서 속도를 측정한다.
어떤 예제도 시간 측정값을 출력하지 않는다. 측정 시간은 머신과 그 머신의 부하에 따라 달라진다. 시간을 출력하는 예제는 실행할 때마다 다른 출력을 내므로, 매번 같은 출력을 내야 하는 이 책의 예제에는 맞지 않는다. 속도 비율은 대신 녹화본에 담는다.
가중치만 int8로 바꾸면 가중치 바이트는 줄지만, 그 사본이 CPU에서 더 빠르게 계산되는지는 별개의 문제다. throughput 녹화본이 이를 검증한다. 이 녹화본은 예제가 쓰는 것과 같은 도우미로 만든 이 장의 int8 사본 banking77-lora-v1-int8의 시간을, 매니페스트에 이름이 적힌 머신에서 float32 어댑터 및 대역 모델과 비교하여 측정한다. 그 머신에서 스레드 4개와 배치 크기 16으로 실행했을 때, int8 사본의 초당 메시지 처리량은 float32 분류기의 0.9배였다. 따라서 이 녹화본에서는 int8로 서비스해야 할 속도상의 이유가 나오지 않는다. 10장은 측정에 쓴 머신과 함께 이 처리율을 보고한다. 녹화본은 360M 모델의 시간은 측정하지 않았으며, 이 장은 그 머신 외의 어떤 머신에 대해서도 속도를 주장하지 않는다.
이런 종류의 녹화본은 모델과 입력을 고정하고, 이름이 적힌 머신에서 한 번 실행하며, 출력을 스크립트 이름이 적힌 매니페스트와 함께 저장한다. 녹화본을 쓰는 예제는 저장된 출력을 읽을 뿐 모델을 직접 실행하지 않는다. 속도 비교를 위해 녹화본은 두 사본에 같은 메시지를 같은 수의 스레드로 실행하고, 각 사본의 시간을 별도의 출력으로 저장한다. 비율은 저장된 출력으로 계산하며, 독자는 그 옆에서 머신과 스레드 수를 확인할 수 있다. 자신의 머신에서 비율을 알고 싶은 독자는 같은 녹화본을 그 머신에서 실행하고, 결과와 함께 머신을 밝혀야 한다.
작업 규칙: 속도 비율은 실행한 머신을 밝힌 녹화본에서만 읽고, 가중치 바이트로 추정하지 않는다. 위의 비율은 해당 머신에만 적용되므로, 이를 자신의 속도로 받아들이기 전에 서비스할 머신에서 녹화본을 실행한다.
핸드오프를 염두에 두고 결정한다
결정할 것은 라우터가 어느 복사본을 서비스하느냐이다. 8장은 float32 어댑터를 기본으로 서비스하며, 이 장의 어떤 내용도 그 기본값을 바꾸지 않는다. int8 복사본에서 예측이 바뀐 수는 0/200 (0.0%)이고, 핸드오프 결정이 바뀐 수는 0/200이다. 바뀐 수가 0이면 그 복사본은 계속 후보로 남는다. 그 복사본이 제공하는 절감은 일부 계층의 가중치 바이트 비율이다. 기록에서는 해당 머신에서 int8 복사본의 속도 향상이 확인되지 않았고, 이 책에는 int8 복사본에 유리한 측정된 메모리 요구도 없다. 따라서 이 집계에서 바뀐 답이 없더라도 측정된 이득이 없다면 아직 그 복사본을 권할 이유가 없다.
float32를 유지하는 것은 비용이 따르는 선택이다. 어댑터는 int8 복사본보다 더 많은 바이트를 차지하며, 작은 머신에서는 이것이 문제가 될 수 있다. 이 책이 보인 것은 이보다 좁은 범위이다. 이 표본에서 예측이 바뀐 수는 0/200 (0.0%)이며, 바뀐 수가 0일 때만 예측 변화가 복사본을 거부할 이유에서 제외된다. 남은 이유는 이 장에서 측정하지 않은 것들이므로, 그 이유들이 기본값을 정한다. 서비스할 머신에서의 기록이 의미 있는 속도 향상을 보이고 메모리 요구도 측정된다면, int8을 택하는 근거는 위험을 수치로 센 공학적 근거가 된다. 그때까지는 float32 어댑터가 미해결 질문이 가장 적은 쪽이다.
주의해서 볼 부분은 핸드오프이다. 5장은 핸드오프되지 않은 메시지의 정확도가 dev 분할에서 목표에 도달하도록 임곗값을 골랐다. 신뢰도가 조금만 움직이는 복사본도 다른 메시지 집합을 핸드오프할 수 있으며, 그러면 임곗값은 고른 목적대로 작동하지 않는다. 예측이 바뀐 수를 선택한 임곗값에서 세는 이유와 핸드오프 수를 그 옆에 두는 이유가 이것이다. 같은 측정은 양자화된 모든 어댑터에 적용되며, 다시 학습한 v2도 마찬가지이다.
양자화된 복사본은 아무도 세지 않은 변화 때문에 운영 중에 잘못된다. 라이브러리를 업그레이드하면 연산이 달라질 수 있고, 메시지 구성이 바뀌면 일부 메시지가 임곗값을 넘나들 수 있다. 라이브러리나 메시지가 바뀔 때마다, 그리고 양자화된 복사본이 첫 메시지를 서비스하기 전에 dev 분할에서 다시 센다.
같은 절차는 독자가 직접 만든 라우터의 양자화 복사본에도 적용되며, 표본과 임곗값 외에 이 책의 다른 것은 필요하지 않다. 임곗값은 어댑터의 매니페스트에서 가져오고, 매니페스트에 그 값이 dev 분할에서 선택되었다고 적혀 있는지 확인한다. 도우미가 하는 대로 백본은 양자화하고 헤드는 float32로 둔다. 고정된 표본을 두 복사본으로 각각 채점하고, 정확도, 핸드오프 수, 핸드오프되지 않은 메시지의 정확도, 바뀐 예측 수를 각각의 분모와 함께 센다. 총계를 읽기 전에 각 방향의 뒤바뀜을 먼저 읽는다. 그런 다음 임곗값이 dev 분할에서 선택되었으므로 선택한 임곗값에서 dev 분할에 대해 다시 센다. 이 절차를 통과한 복사본이라도 float32 어댑터를 대체하기 전에 속도와 메모리를 기록으로 측정해야 한다.
작업 규칙: 기본으로는 float32 어댑터를 서비스한다. 서비스할 머신에서의 기록이 속도 향상을 보이고 측정된 메모리 요구가 int8 복사본에 유리할 때에만 int8 복사본을 고려하며, 그 경우에도 메시지를 서비스하기 전에 선택한 임곗값에서 dev 분할의 바뀐 예측 수를 센다.
이 판의 이 장
2026.11.9판예제 통과 2026년 11월 20이 장에서 2개 예제개 중 2개가 통과한다
영어판 2026.11.9판을 번역한 것이다.