ルーターを量子化し、何が変わるかを測る
読了まで約33 分分、5 節 節の 2 例 例。
この章を終えると、ファインチューニングしたルーターのバックボーンの重みを、1 回の呼び出しで 8 ビット整数として保存できるようになる。さらに、固定サンプルで予測が変わる件数を数え、その件数が何を示し何を示さないかを説明できるようになる。速度をどのように測るか、また 1 台のマシンでの記録から何が分かったかも扱う。
ルーターの量子化コピーは、占める容量が小さくなるはずである。問題は、それが元と同じように答えるかどうかである。第 5 章では、ルーターを 1 つのアダプター banking77-lora-v1 として残した。その重みは float32 である。引き継ぎのしきい値は 0.63 であり、第 5 章の規則に従って dev 分割で選んだ。量子化とは、重みをより少ないビット数で保存することである。量子化したモデルは重みの占める容量が小さくなるが、返す答えが変わることがある。この章では後者を測る。この章では後者を、第 5 章で採点した 200 件のテストメッセージからなる固定サンプル test_200 で測る。量子化に代償がないとは主張しない。
このコピーは、銀行のサポートメッセージを振り分ける受信箱で float32 のアダプターに代わって使われる可能性がある。その前に、次の 3 つの問いに答える必要がある。コピーの重みは、アダプターと比べて何バイトを占めるか。コピーは同じメッセージに同じ答えを返すか。そして、受信箱を動かすマシンで速いか。最初の 2 つは、モデルの形状と固定サンプルからここで測定できる。3 つ目は、名前を明示したマシンでの記録から得られる。速度の節では、その記録で何が分かったか、また何が対象外かを述べる。どの答えも、分母を示した件数、または入力を明示した比率である。
この部分はまだ翻訳されていないため、英語で表示している。
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.
予測が変わる数を数える
量子化は層が計算する数値を変えるため、出力される答えも変わりうる。量子化したコピーの検査とは、そのコピーが同じメッセージに同じように答えるかどうかを確かめることである。
第5章のマニフェストにある閾値で、test_200 を両方のコピーで採点すると、両者が同じように答えるかどうかがわかる。この実行では、コピーごとに正解数、ハンドオフ数、およびハンドオフされなかったメッセージでの正解率を数える。次に、2つのコピー間で担当チームが異なるメッセージの数と、ハンドオフの判断が異なる件数を数える。同じ実行である int8-changed-predictions は、ヘッドも量子化した3つ目のコピーも採点する。これについてはスコアヘッドの節で扱う。
2つのコピーは、意図的に同じ扱いにはしていない。float32 側は第5章で読み込んだままのアダプタであり、マージしていない。一方、int8 側はヘルパーが量子化の前にマージを行うため、先にマージしてある。したがって、以下の数はマージと量子化を合わせた結果である。この実行ではマージ済みの float32 コピー単独は採点しておらず、本章はマージだけでは何も変わらないとは主張しない。
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
このサンプルでは、int8 コピーによって 0/200 (0.0%) 件の予測と 0/200 件のハンドオフ判断が変わる。ヘッドも量子化したコピーについては、スコアヘッドの節で数える。この段落の隣にある出力には、各コピーの正解率、ハンドオフ数、ハンドオフされなかったメッセージでの正解率が、それぞれ分母とともに示されている。
3つの指標は第2章で定義したものであり、それぞれに分母がある。正解率は正解したメッセージ数を全200件で割る。したがって、ハンドオフされたメッセージも、チームが誤っていれば誤りとして数える。ハンドオフ率は、閾値を下回ったメッセージ数を全200件で割る。ハンドオフされなかったメッセージでの正解率は、残されたメッセージのうち正解したものの割合であり、1件も残されない場合は定義されない。予測が変わった数は同じ200件を対象とし、3つの指標では答えられない問いを立てる。すなわち、2つのコピーは各メッセージで一致したか、という問いである。一致は正しさを意味しない。そのため、出力には正解率も併せて示している。
予測が変わったからといって、自動的に損失になるわけではない。誤ったチームが正しいチームに変わることもあれば、正しいチームが誤ったチームに変わることもあり、数だけではどちらかわからない。変化の向きを読むには、2つのコピーの判断が食い違うすべてのメッセージについて、各コピーのチームを正解ラベルと比較する。正解率はこの点を隠しうる。2つのコピーが同じ正解率でも、正解しているメッセージが異なることがあり、同じ合計からはどのメッセージが動いたかはわからない。数が0であれば、どちらの向きにも読むべき変化は存在しない。0でない数を得た場合は、合計を読む前に変化したものを読むべきである。
コピーがキューを処理し始めると、変化には具体的なコストが生じる。float32 のアダプタがあるメッセージを card_arrival に振り分け、int8 のコピーが同じメッセージを card_delivery_estimate に振り分けたとする。どちらもチームであり、そのメッセージの正解ラベルになりうるのは一方だけである。したがって、両方とも誤りでない限り、この変化は答えを直すか壊すかのどちらかになる。受信箱はどちらの場合でも、メッセージを1つのチームに送る。この変化はそのチームのキューを担当するサポート担当者に及ぶ可能性があるが、合計を見ても誰も気づかないだろう。コピーがメッセージを処理する前にこの変化を見えるようにするのが、この数である。
予測が変わった数は、1つのアダプタを1つの閾値で評価した1つの結果として読むべきであり、保証として読んではならない。別のサンプル、アダプタ、閾値では変化が現れることがあり、200件のサンプルでは、メッセージの全体の流れの中で稀にしか起きない変化を見逃すことがある。
この数が扱うのは予測だけであり、それ以外には何も語らない。ヘルパーの docstring にあるとおり、このコピーは活性化も float32 のまま保持する。したがって、この数は活性化も量子化したコピーについては何も教えない。本章はそのコピーを測定しない。
実践ルール: 変わった予測の数は、同じメッセージ、同じ閾値で両方のコピーについて数え、正解率とハンドオフ数の隣に、それぞれの分母とともに示す。数が0のときは、そのサンプルでの0として報告し、サンプルと、その数を取ったアダプタを明記する。
スコアヘッドは float32 のまま保つ
スコアヘッドは、チームごとに 1 つ、計 77 個の出力を持つ層である。そのソフトマックスが、5 章でしきい値と比較する確信度を与え、最大の確率を持つものがルーターの返すチームになる。ヘルパーはこのヘッドを呼び出しの対象から外すので、ヘッドは float32 のままである。本節では、本書がこの選択をする理由と、その根拠となる集計結果を述べる。
本章で扱うコピーはヘッドを float32 のまま保っている。この選択は、int8-changed-predictions による 1 つの集計に基づく。ヘッドも int8 にすると、このサンプルでは 1/200 件の予測が変わる。この集計は層を感度の順に並べるものではなく、変化の原因がヘッドにあるとも、ないとも、本章は主張しない。
危険にさらされるのは、確信度がしきい値をわずかに上回っているメッセージである。ヘッドに変化が生じると、そのようなメッセージがしきい値を下回ることがあり、その場合、メッセージはチームではなく人に回される。前の節にある、変化した引き継ぎ判断の件数を見れば、コピーが引き継ぎ判断を動かすかどうかが分かる。この実行では、int8 のコピーが動かした引き継ぎ判断は 0/200 件である。
ヘルパーがヘッドに対して行った処理は int8-layers-and-bytes に示されている。その例が表明しているとおり、ヘッドは量子化されておらず、その重みは torch.float32 である。これらの出力行は、最初の節の層の数と同じ実行から得られたものなので、両者を直接比較できる。
予測の変化数は、int8 のコピー全体と、ヘッドも量子化したコピーについて数えたものである。どちらも層ごとに分けてはいないので、変化がどの層から生じるかは言えない。それを調べるには、層を 1 つずつ量子化し、dev 分割で再び数える必要がある。
実践ルール: 選んだしきい値での dev 分割の集計で、量子化したヘッドが、依拠するどのチームも引き継ぎ判断も変えないと示されない限り、スコアヘッドは float32 のまま保つ。どのしきい値で数えたかを明記すること。
録画で速度を測る
重みのバイト数が減っただけでは、モデルは速くならない。本章も、速くなると主張するものではない。int8 のコピーが特定の CPU で速く計算できるかどうかは、その CPU 上で動く演算ルーチンによって決まる。そのため本書では、名前を挙げた 1 台のマシンで測定する。
例は、どれも時間の計測値を出力しない。計測値はマシンやその負荷によって変わるので、計測値を出力する例は実行のたびに異なる出力を返すことになる。しかし、本書の例は毎回同じ出力を返さなければならない。したがって、速度比は録画に収める。
重みのみの int8 化で節約できたのは重みのバイト数である。このコピーが CPU 上で速く計算できるかどうかは、別の問題である。throughput の録画はそれを検証する。録画では、例が使うのと同じヘルパーで作った本章の int8 コピー banking77-lora-v1-int8 を、float32 のアダプタおよび代役のモデルと比較して計測する。計測は、マニフェストに記されたマシンで行う。そのマシンで、スレッド数を 4、バッチサイズを 16 としたとき、int8 のコピーが 1 秒あたりに処理するメッセージ数は float32 の分類器の 0.9 倍であった。したがって、この録画からは、int8 で提供すべき速度上の理由は得られない。第10章では、測定したマシンとともにその速度を報告する。この録画では 360M モデルを計測しておらず、本章はそのマシン以外のどのマシンについても速度を主張しない。
この種の録画では、モデルと入力を固定し、名前を挙げたマシンで 1 回だけ実行して、その出力をスクリプト名を記したマニフェストとともに保存する。録画を使う例は、保存された出力を読み込むだけで、モデルを自分では実行しない。速度の比較では、録画は同じメッセージを両方のコピーに通し、スレッド数も両者で同じにして、各コピーの計測値をそれぞれ別の出力として保存する。速度比はこれらの保存された出力から求められ、読者はその横でマシンとスレッド数を確認できる。自分のマシンでの速度比を知りたい読者は、同じ録画をそのマシンで実行し、結果とともにマシンを報告するべきである。
実践ルール: 速度比は、実行したマシンが明記された録画からのみ読み取り、重みのバイト数から推測してはならない。上の速度比は、そのマシン自体についてのみ当てはまる。したがって、自分の速度として読む前に、実際に提供に使うマシンでその録画を実行すること。
引き渡しを見据えて決める
決めるべきことは、ルーターがどちらのコピーを提供するかである。第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 分割でももう一度数える。しきい値はそこで選ばれたからである。これらの手順を通ったコピーでも、float32 のアダプターに置き換える前に、速度とメモリを記録で測ってからにする。
実践ルール: float32 のアダプターを既定として提供する。int8 コピーを検討するのは、提供先のマシンでの記録が速度の向上を示し、かつ実測されたメモリの必要性がint8を支持する場合に限る。さらに、メッセージを提供する前に、選んだしきい値で dev 分割において予測が変わった件数を数える。
この版における本章
第2026.11.9版2026年11月20日時点で例が通過この章の2 例件のうち2件が合格
英語版の書籍(版2026.11.9)から翻訳した。