-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquantize.py
More file actions
2412 lines (2189 loc) · 100 KB
/
Copy pathquantize.py
File metadata and controls
2412 lines (2189 loc) · 100 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Quantize a model to NVFP4 (W4A4) using llm-compressor.
By default attention q/k/v/o projections are kept at FP8 (channel-wise
weights, dynamic per-token activations) and an FP8 KV cache scale is
calibrated — the mixed-precision layout vLLM's NVFP4 kernels expect. FP8
attention is ~3.5x closer to the original weights than NVFP4 for a small
size cost (~13% on a dense 12B, ~1% on a MoE).
On hybrid linear-attention models (Qwen3.5/3.6/3.8), the Gated DeltaNet
qkv/z/out projections get an explicit NVFP4 group of their own (FP8 with
--fp8-deltanet) and the tiny in_proj_a/in_proj_b gating projections stay
unquantized — automatic, keyed off the live module tree.
Usage:
python quantize.py [--model MODEL_ID] [--output OUTPUT_DIR]
[--samples N] [--max-len N] [--weight-only]
[--no-fp8-attn] [--fp8-deltanet] [--fp8-lm-head]
[--gptq-mlp {auto,on,off}]
[--gptq-mlp-projections LIST] [--gptq-mlp-damp SPEC]
[--fp8-mlp SPEC] [--sensitivity-samples N]
[--sensitivity-report PATH]
[--sensitivity-context {clean,quantized}]
[--ignore PATTERN ...] [--dtype TYPE]
[--trust-remote-code] [--dataset DATASET]
[--split SPLIT] [--vision-samples N]
Defaults:
model = Qwen/Qwen2.5-0.5B-Instruct
output = <model-basename>-NVFP4
samples = 512
max-len = 1024
weight-only = False (W4A4; set flag for W4A16)
fp8-attn = True (FP8 attention + FP8 KV cache; the KV cache scale
needs calibration, so it is skipped with --weight-only)
fp8-deltanet = False (NVFP4 DeltaNet projections on hybrid models;
set the flag to keep them at FP8 instead — ~+1.5GB on a
27B for most of the DeltaNet quantization KL back)
fp8-lm-head = False (output head stays at model dtype; set the flag to
quantize it to FP8 and take it off the ignore list — half
the head's bytes, worth +14% decode throughput at k=2 MTP
against 1.7 points of draft acceptance)
gptq-mlp = auto (GPTQ + imatrix_mse observer + static actorder on
dense MLP gate/up/down projections; calibration-only, same
on-disk format, ~20% lower KL vs BF16 than plain minmax.
auto enables it for dense models and skips it for MoE,
--weight-only, and --no-fp8-attn runs)
gptq-mlp-projections = gate,up,down (which dense MLP projections the
GPTQ modifier owns; the rest stay NVFP4 minmax. 'gate,up'
is the A/B arm for the down_proj finding in GUIDE.md:
down_proj Hessians are dominated by a handful of
massive-activation channels and GPTQ's compensation
measured worse than plain rounding there in isolation)
fp8-mlp = off (uniform NVFP4 across every dense MLP layer; 'top:N'
keeps the N most quantization-sensitive layers at FP8
instead, 'gptq-loss:N' ranks by GPTQ's own Hessian-weighted
proxy loss rather than per-layer KL trials, an explicit
list like '1,2,3,10-15' names them outright, and 'scan' or
'gptq-loss' just print the ranking. KL sensitivity is
measured W4A4-faithfully: each trial fake-quantizes the
layer's input activations along with its weights, the same
two formats serving uses. On Qwen-family hybrids the KL
trials do not predict the measured promotion value --
use gptq-loss there; see GUIDE.md)
sensitivity-samples = 64 (calibration samples behind the --fp8-mlp rank)
sensitivity-context = clean (each trial quantizes one layer against an
otherwise-BF16 model; 'quantized' scores each layer's FP8
promotion against an all-MLP-quantized baseline instead,
and 'quantized-acts' quantizes activations only -- both
diagnostics, not better default rankers)
ignore = lm_head (dropped automatically by --fp8-lm-head)
dtype = auto
dataset = mix (chat + instruct + code + math + multilingual + tool
calls + raw web text, streamed from seven HuggingFace
datasets and rendered through the model's chat template;
'ultrachat' selects the old single-source set, and any
HuggingFace dataset id still works)
vision-samples = auto (12.5% of --samples carry an image when the
checkpoint has an image processor, 0 otherwise)
split = auto (train_sft for ultrachat, train otherwise; ignored for
multi-source mixtures)
"""
import argparse
import json
import random
from contextlib import contextmanager
from pathlib import Path
from typing import NamedTuple
import torch
from compressed_tensors.config import CompressionFormat
from compressed_tensors.quantization import (
QuantizationArgs,
preset_name_to_scheme,
)
from compressed_tensors.quantization.lifecycle.forward import fake_quantize
from compressed_tensors.utils import match_name
from compressed_tensors.utils.safetensors_load import (
get_safetensors_header,
get_weight_mappings,
)
from datasets import load_dataset
from llmcompressor import oneshot
from llmcompressor.modifiers.gptq import GPTQModifier
from llmcompressor.modifiers.quantization import QuantizationModifier
from llmcompressor.observers import Observer
from torch.utils.data import DataLoader
# llm-compressor 0.12.0 (current stable) only collects imatrix importance
# statistics when an IMatrixGatherer is prepended to the recipe; without it,
# observer=imatrix_mse silently falls back to a uniform MSE grid search.
# Nightlies (0.12.1a+) remove the class and make the observer self-collecting,
# so treat its absence as "no gatherer needed" rather than an error.
try:
from llmcompressor.modifiers.transform.imatrix import IMatrixGatherer
except ImportError:
IMatrixGatherer = None
import transformers
from transformers import (
AutoConfig,
AutoModelForCausalLM,
AutoProcessor,
AutoTokenizer,
PreTrainedTokenizerBase,
)
if IMatrixGatherer is not None:
class _PersistentIMatrixGatherer(IMatrixGatherer):
"""IMatrixGatherer whose collected statistics survive session finalize.
With --pipeline basic the gatherer cannot share a calibration epoch
with GPTQ (GPTQ's imatrix observers pick up — and delete — the
module accumulators at epoch start, before any data has flowed), so
the gathering runs as its own oneshot session first. The base class
deletes the accumulators on finalize; this subclass leaves them on
the modules for the next session's observers to pick up.
"""
def on_finalize(self, state, **kwargs) -> bool:
if not self.ended_:
self.on_end(state, None)
return True
# Attention projections kept at FP8 by --fp8-attn. Name-based, so fused-QKV
# and MLA architectures won't match; main() verifies the pattern hits at
# least one module before quantizing.
FP8_ATTN_TARGET = r"re:.*self_attn\.(q|k|v|o)_proj$"
# vLLM fuses q/k/v into a single qkv_proj module and resolves its scheme by
# layer name before class name, so the saved config must name the fused module
# too — otherwise the broad Linear/NVFP4 target wins and vLLM tries to load
# the FP8 shards as NVFP4. Matches nothing at quantization time, where the
# projections are still unfused.
FP8_ATTN_FUSED_TARGET = r"re:.*self_attn\.qkv_proj$"
# Dense MLP projections given the GPTQ + imatrix_mse + actorder treatment by
# --gptq-mlp. MoE expert projections (".mlp.experts.N.gate_proj") do not
# match, deliberately: per-expert calibration coverage is too thin for
# activation-statistics observers to be trustworthy there.
GPTQ_MLP_TARGET = r"re:.*\.mlp\.(gate|up|down)_proj$"
# Gated DeltaNet projections on hybrid linear-attention models (Qwen3.5/3.6/
# 3.8 `linear_attn` layers). All five are plain nn.Linear, so the catch-all
# Linear group covers them -- but --gptq-mlp on deletes that group, and
# neither surviving regex (self_attn FP8, .mlp GPTQ) matches linear_attn, so
# every DeltaNet projection silently stayed BF16 (the 25% size gap against
# unsloth's Qwen3.6-27B-NVFP4). Naming them here keeps them quantized in both
# recipe shapes. in_proj_a and in_proj_b produce the recurrence's decay and
# beta gating scalars and round to nothing beside the qkv/z/out projections;
# following unsloth's split they stay unquantized via the ignore list.
DELTANET_TARGET = r"re:.*linear_attn\.(in_proj_qkv|in_proj_z|out_proj)$"
DELTANET_IGNORE = (
r"re:.*linear_attn\.in_proj_a$",
r"re:.*linear_attn\.in_proj_b$",
)
# The output head, promoted from BF16 to FP8 by --fp8-lm-head. It is a plain
# Linear, so the only thing keeping it unquantized is the default ignore list;
# the flag drops it from there and gives it a group of its own.
LM_HEAD_TARGET = r"re:.*lm_head$"
# The Gemma-4 E-series per-layer embedding table, quantized to INT8 by
# --int8-ple. It is a lookup table, not a matmul, so this is weight-only; vLLM
# unpacks only the gathered rows (CompressedTensorsEmbeddingWNA16Int), which
# makes the saving VRAM as well as disk. The trailing "_per_layer" keeps this
# off the ordinary embed_tokens table, which is not a candidate: it is read
# through lm_head, which is on the ignore list unless --fp8-lm-head takes it
# off (and even then the table itself stays at model dtype).
PLE_TARGET = r"re:.*embed_tokens_per_layer$"
# ---------------------------------------------------------------------------
# Calibration data
# ---------------------------------------------------------------------------
#
# W4A4 fits activation scales to whatever text it is shown, so the corpus is
# an accuracy knob rather than a formality. `mix` spreads that exposure across
# what a served model actually sees: multi-turn chat, general instruction
# following, code and math reasoning, tool calls, 65-language prompts, and raw
# multilingual web text.
#
# Chat sources are rendered through the model's own chat template, which puts
# the template's control tokens into the activation statistics -- an instruct
# model calibrated on plain text never sees the format it is served in. The
# raw-text component is the deliberate exception.
#
# Every source is read with streaming=True, so a run pulls only the rows it
# samples rather than the whole repo (tulu-3 alone is 1.4 GB on disk).
#
# Note that on a 5B model, neither this mixture nor a 4.4x larger token budget
# moved KL against the BF16 original by more than measurement noise; the case
# for it is breadth of coverage, which an English-chat KL harness cannot see.
class MixSource(NamedTuple):
"""One component of a calibration mixture."""
id: str
role: str
weight: float
split: str = "train"
config: str | None = None
data_files: str | None = None
TEXT_MIX: tuple[MixSource, ...] = (
MixSource("HuggingFaceH4/ultrachat_200k", "chat", 0.20, split="train_sft"),
MixSource("allenai/tulu-3-sft-mixture", "instruct", 0.15),
MixSource("open-r1/Mixture-of-Thoughts", "code", 0.12, config="code"),
MixSource("open-r1/Mixture-of-Thoughts", "math", 0.12, config="math"),
MixSource("CohereLabs/aya_dataset", "multilingual", 0.15),
MixSource("HuggingFaceTB/smoltalk", "tools", 0.10, config="apigen-80k"),
# Purpose-built imatrix calibration text: cleaned, de-duplicated FineWeb
# across 18 languages. Not chat-templated, deliberately -- it is the one
# component that exercises the model outside its instruct format.
MixSource(
"eaddario/imatrix-calibration",
"raw-text",
0.16,
data_files="text_all_small.parquet",
),
)
# Image+text turns for multimodal checkpoints. The vision tower itself stays
# unquantized, but its output embeddings are spliced into the decoder's input
# sequence, and their distribution is nothing like a text embedding's -- so
# without image samples the decoder's NVFP4 input scales and FP8 KV scales are
# calibrated on half the input distribution the model actually sees.
VISION_MIX: tuple[MixSource, ...] = (
MixSource("unsloth/llava-instruct-mix-vsft-mini", "vision", 1.0),
)
CALIBRATION_MIXES: dict[str, tuple[MixSource, ...]] = {
"mix": TEXT_MIX,
"ultrachat": (
MixSource("HuggingFaceH4/ultrachat_200k", "chat", 1.0, split="train_sft"),
),
}
# Share of --samples given to image turns when --vision-samples is auto and
# the checkpoint has an image processor.
VISION_FRACTION = 0.125
def _allocate(sources: tuple[MixSource, ...], total: int) -> list[int]:
"""Split `total` samples across sources by weight (largest remainder)."""
if total <= 0:
return [0] * len(sources)
scale = sum(s.weight for s in sources) or 1.0
exact = [total * s.weight / scale for s in sources]
quotas = [int(x) for x in exact]
order = sorted(
range(len(sources)), key=lambda i: exact[i] - quotas[i], reverse=True
)
for i in order[: total - sum(quotas)]:
quotas[i] += 1
return quotas
def _stream(src: MixSource, seed: int, buffer: int):
kwargs = {}
if src.config is not None:
kwargs["name"] = src.config
if src.data_files is not None:
kwargs["data_files"] = src.data_files
ds = load_dataset(src.id, split=src.split, streaming=True, **kwargs)
return ds.shuffle(seed=seed, buffer_size=buffer)
def _row_to_messages(row: dict) -> list | None:
"""Normalise a row to chat turns, or None if it is unstructured text."""
messages = row.get("messages")
if isinstance(messages, list) and messages:
return messages
# CohereLabs/aya_dataset: single-turn prompt/completion columns
if isinstance(row.get("inputs"), str) and isinstance(row.get("targets"), str):
return [
{"role": "user", "content": row["inputs"]},
{"role": "assistant", "content": row["targets"]},
]
return None
def _row_to_text(row: dict) -> str | None:
for key in ("content", "text", "article"):
value = row.get(key)
if isinstance(value, str) and value.strip():
return value
return next(
(v for v in row.values() if isinstance(v, str) and len(v.strip()) > 32), None
)
def _render_chat(tokenizer, messages: list) -> str | None:
"""Apply the chat template, folding a system turn into the first user turn
if the template rejects it (gemma's does)."""
try:
return tokenizer.apply_chat_template(messages, tokenize=False)
except Exception:
pass
folded: list[dict] = []
carried = ""
for message in messages:
content = message.get("content")
if not isinstance(content, str):
return None
if message.get("role") == "system":
carried += content.strip() + "\n\n"
continue
if carried and message.get("role") == "user":
message = {**message, "content": carried + content}
carried = ""
folded.append(message)
if not folded:
return None
try:
return tokenizer.apply_chat_template(folded, tokenize=False)
except Exception:
return None
def _chunk_text(text: str | None, max_len: int) -> list[str]:
"""Split a raw-text row into chunks of roughly `max_len` tokens each.
Splits on line boundaries and budgets 3 characters per token, which
under-fills for English and over-fills for CJK; the tokenizer truncates
either way, so the only cost of being wrong is chunk size drift.
"""
if not text:
return []
budget = 3 * max_len
if len(text) <= budget:
return [text]
chunks: list[str] = []
current: list[str] = []
size = 0
for line in text.splitlines(keepends=True):
current.append(line)
size += len(line)
if size >= budget:
chunks.append("".join(current))
current, size = [], 0
if size > budget // 4:
chunks.append("".join(current))
return chunks
def build_text_samples(
sources: tuple[MixSource, ...],
total: int,
tokenizer,
max_len: int,
seed: int = 42,
) -> tuple[list[dict], dict[str, int]]:
"""Stream `total` tokenized samples from a weighted mixture of sources."""
samples: list[dict] = []
counts: dict[str, int] = {}
for src, quota in zip(sources, _allocate(sources, total)):
if quota <= 0:
continue
taken = 0
# Cap the scan so a source that keeps failing to render can't spin.
for scanned, row in enumerate(_stream(src, seed, max(512, quota * 4))):
if taken >= quota or scanned >= quota * 20 + 64:
break
messages = _row_to_messages(row)
if messages is not None:
rendered = _render_chat(tokenizer, messages)
texts = [rendered] if rendered else []
add_special_tokens = False
else:
# Corpus rows can be whole documents (eaddario ships each of
# its files as one multi-megabyte string), so split rather
# than truncate away 99% of the row.
texts = _chunk_text(_row_to_text(row), max_len)
# Chunks come out in document order; sample across the whole
# document instead of only its opening pages.
random.Random(seed).shuffle(texts)
add_special_tokens = True
for text in texts:
if taken >= quota:
break
encoded = tokenizer(
text,
padding=False,
truncation=True,
max_length=max_len,
add_special_tokens=add_special_tokens,
return_tensors="pt",
)
if encoded["input_ids"].shape[-1] < 8:
continue
samples.append(dict(encoded))
taken += 1
counts[src.role] = counts.get(src.role, 0) + taken
if taken < quota:
print(f" warning: {src.id} yielded {taken}/{quota} usable samples")
return samples, counts
def _vision_messages(row: dict) -> list | None:
"""Rewrite a llava-style row into chat turns with inline PIL images."""
images = list(row.get("images") or [])
turns: list[dict] = []
for message in row.get("messages") or []:
content = []
for part in message.get("content") or []:
if part.get("type") == "image":
index = part.get("index") or 0
if index >= len(images):
return None
content.append({"type": "image", "image": images[index]})
elif part.get("text"):
content.append({"type": "text", "text": part["text"]})
if content:
turns.append({"role": message["role"], "content": content})
return turns or None
def build_vision_samples(
sources: tuple[MixSource, ...],
total: int,
processor,
max_len: int,
seed: int = 42,
) -> tuple[list[dict], dict[str, int]]:
"""Stream `total` image+text samples through the model's own processor.
Returns empty if the processor cannot render inline images -- a text-only
calibration set is a worse calibration set, not a failed run.
"""
samples: list[dict] = []
counts: dict[str, int] = {}
for src, quota in zip(sources, _allocate(sources, total)):
if quota <= 0:
continue
taken = 0
for scanned, row in enumerate(_stream(src, seed, max(256, quota * 4))):
if taken >= quota or scanned >= quota * 10 + 32:
break
messages = _vision_messages(row)
if messages is None:
continue
try:
encoded = processor.apply_chat_template(
messages,
tokenize=True,
return_dict=True,
return_tensors="pt",
add_generation_prompt=False,
)
except Exception as exc:
print(
f" warning: {type(processor).__name__} cannot render inline "
f"images ({exc}); calibrating on text only"
)
return [], {}
# Image placeholders must survive intact, so these are filtered on
# length rather than truncated.
if encoded["input_ids"].shape[-1] > 4 * max_len:
continue
samples.append(dict(encoded))
taken += 1
counts[src.role] = counts.get(src.role, 0) + taken
if taken < quota:
print(f" warning: {src.id} yielded {taken}/{quota} usable samples")
return samples, counts
def _collate_single(batch: list[dict]) -> dict:
# batch_size=1: text and image samples carry different keys, so there is
# nothing to stack. The processor/tokenizer already produced a batch dim.
assert len(batch) == 1
return batch[0]
def build_calibration_loader(samples: list[dict], seed: int = 42) -> DataLoader:
"""Shuffle the merged mixture and wrap it for llm-compressor.
oneshot() accepts a DataLoader directly, which is what lets one mixture
hold text-only and image-bearing samples with different key sets.
"""
shuffled = list(samples)
random.Random(seed).shuffle(shuffled)
return DataLoader(shuffled, batch_size=1, collate_fn=_collate_single)
def build_dataset(args, dataset: str, label: str, tokenizer, processor) -> DataLoader:
"""Assemble one named mixture (or bare HF dataset id) into a DataLoader.
Called once for the calibration corpus and, when they differ, again for the
--fp8-mlp ranking corpus.
"""
print(f"Loading {label.lower()} dataset ({dataset})...")
sources = CALIBRATION_MIXES.get(dataset)
if sources is None:
# Any HuggingFace dataset id still works as a single-source mix.
# ultrachat names its split "train_sft"; most datasets use "train".
default_split = (
"train_sft" if dataset == "HuggingFaceH4/ultrachat_200k" else "train"
)
sources = (
MixSource(dataset, "custom", 1.0, split=args.split or default_split),
)
elif args.split:
if len(sources) == 1:
sources = (sources[0]._replace(split=args.split),)
else:
print(f" note: --split {args.split} ignored for mixture {dataset}")
n_vision = args.vision_samples
if n_vision == "auto":
has_image_processor = processor is not None and (
getattr(processor, "image_processor", None) is not None
)
n_vision = round(args.samples * VISION_FRACTION) if has_image_processor else 0
elif n_vision > 0 and processor is None:
raise SystemExit(
"--vision-samples needs an image processor, but "
"AutoProcessor.from_pretrained() returned none."
)
samples: list[dict] = []
counts: dict[str, int] = {}
if n_vision > 0:
vision_samples, vision_counts = build_vision_samples(
VISION_MIX, n_vision, processor, args.max_len
)
samples += vision_samples
counts.update(vision_counts)
text_samples, text_counts = build_text_samples(
sources, args.samples - len(samples), tokenizer, args.max_len
)
samples += text_samples
counts.update(text_counts)
if not samples:
raise SystemExit(f"Calibration mixture {dataset!r} yielded no samples")
total_tokens = sum(s["input_ids"].shape[-1] for s in samples)
breakdown = ", ".join(f"{role} {n}" for role, n in counts.items())
print(f"{label} set: {len(samples)} samples, {total_tokens:,} tokens ({breakdown})")
return build_calibration_loader(samples)
# ---------------------------------------------------------------------------
# Mixed-precision MLP selection
# ---------------------------------------------------------------------------
#
# NVFP4 stores a weight in ~4.5 bits against FP8's ~8, but layers do not all
# pay the same accuracy price for that. --fp8-mlp promotes the ones that pay
# the most back to FP8, buying fidelity with size where it goes furthest.
#
# Promotion is per decoder layer, never per projection: vLLM fuses gate_proj
# and up_proj into a single gate_up_proj and resolves its scheme from whichever
# shard name its matcher reaches first, so a layer holding both precisions
# would load as one of them arbitrarily.
class LayerSensitivity(NamedTuple):
"""What promoting one decoder layer's MLP from NVFP4 to FP8 would buy."""
key: str # module prefix, e.g. "model.language_model.layers.7"
index: int # decoder layer index
nvfp4: float # this layer's cost at NVFP4 (mean KL, or GPTQ proxy loss)
fp8: float # ... and at FP8, same metric
modules: tuple[str, ...]
extra_bytes: int # on-disk cost of the promotion
@property
def gain(self) -> float:
"""Output divergence removed by promoting this layer."""
return self.nvfp4 - self.fp8
def _layer_key(name: str) -> str:
"""Module prefix shared by one layer's MLP projections."""
return name.rsplit(".mlp.", 1)[0]
def _layer_index(key: str) -> int:
"""Decoder index from a layer prefix; -1 when the name has no `.layers.N`."""
_, sep, tail = key.rpartition(".layers.")
return int(tail) if sep and tail.isdigit() else -1
def parse_layer_spec(spec: str) -> set[int]:
"""Parse a layer selection like "1,2,3,10-15,19" into a set of indices."""
indices: set[int] = set()
for part in spec.split(","):
part = part.strip()
if not part:
continue
low, sep, high = part.partition("-")
try:
indices.update(range(int(low), int(high) + 1) if sep else [int(part)])
except ValueError:
raise SystemExit(
f"--fp8-mlp: cannot parse {part!r} in layer spec {spec!r}. Expected "
"'off', 'scan', 'top:N', 'gptq-loss[:N]', or indices like "
"'1,2,3,10-15'."
) from None
return indices
def _stored_bytes(weight, args: QuantizationArgs) -> int:
"""On-disk size of one weight under `args`, scales included."""
numel, rows = weight.numel(), weight.shape[0]
if args.num_bits == 8:
# One byte per weight plus an fp32 scale per output channel.
return numel + 4 * rows
# Four bits per weight, one fp8 group scale per `group_size`, one global.
return numel // 2 + numel // (args.group_size or 16) + 4
def _fake_quant_weight(weight, args: QuantizationArgs, chunk: int = 4096):
"""Quantize-dequantize `weight` under `args`, same dtype and device.
Quantization parameters come from the whole tensor -- NVFP4's global scale
is tensor-wide -- and only the fake-quant is chunked over output rows,
which every strategy here computes row-locally. Chunking keeps a 12B
model's largest projection from needing an fp32 copy of itself.
"""
observer = Observer.load_from_registry(args.observer, base_name="weight", args=args)
observer(weight)
qparams = observer.get_qparams()
scale, zero_point = qparams["scale"], qparams["zero_point"]
global_scale = qparams.get("global_scale")
out = torch.empty_like(weight)
for start in range(0, weight.shape[0], chunk):
stop = start + chunk
out[start:stop] = fake_quantize(
weight[start:stop],
scale[start:stop],
None if zero_point is None else zero_point[start:stop],
args,
global_scale=global_scale,
).to(weight.dtype)
return out
@contextmanager
def _swapped_weights(modules: dict, args: QuantizationArgs):
"""Temporarily replace each module's weight with its fake-quantized self."""
originals = {name: module.weight.data for name, module in modules.items()}
try:
for name, module in modules.items():
module.weight.data = _fake_quant_weight(originals[name], args)
yield
finally:
for name, module in modules.items():
module.weight.data = originals[name]
# FP4 E2M1 representable magnitudes and the midpoints between them, for
# round-to-nearest. Kept on CPU; moved to the activation's device on use.
_FP4_LEVELS = torch.tensor([0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0])
_FP4_MIDPOINTS = torch.tensor([0.25, 0.75, 1.25, 1.75, 2.5, 3.5, 5.0])
def _fake_quant_nvfp4_activation(x, global_scale: float):
"""Quantize-dequantize one activation tensor the way NVFP4 W4A4 serving
does: group-16 FP4 with per-group FP8-E4M3 scales computed per token, under
a static per-tensor global scale (448*6/amax) fixed at calibration.
The static global scale is the part that hurts on outlier-heavy layers:
one huge calibration amax shrinks it for every token thereafter, pushing
ordinary groups' scales toward the bottom of the FP8 range.
"""
hidden = x.shape[-1]
pad = (-hidden) % 16
v = torch.nn.functional.pad(x, (0, pad)) if pad else x
groups = v.float().reshape(-1, (hidden + pad) // 16, 16)
group_amax = groups.abs().amax(-1, keepdim=True)
group_scale = (group_amax * (global_scale / 6.0)).to(torch.float8_e4m3fn).float()
group_scale = torch.where(
group_scale == 0, torch.ones_like(group_scale), group_scale
)
scaled = (groups * (global_scale / group_scale)).clamp(-6.0, 6.0)
idx = torch.bucketize(scaled.abs(), _FP4_MIDPOINTS.to(scaled.device))
quant = scaled.sign() * _FP4_LEVELS.to(scaled.device)[idx]
out = (quant * (group_scale / global_scale)).reshape(*x.shape[:-1], -1)
return (out[..., :hidden] if pad else out).to(x.dtype)
def _fake_quant_fp8_activation(x):
"""Quantize-dequantize one activation tensor as FP8 serving does: dynamic
per-token E4M3 scales, so outlier tokens cannot poison anyone else's."""
scale = x.abs().amax(-1, keepdim=True).float().clamp(min=1e-12) / 448.0
quant = (x.float() / scale).clamp(-448.0, 448.0).to(torch.float8_e4m3fn)
return (quant.float() * scale).to(x.dtype)
@contextmanager
def _recorded_input_amax(modules: dict, store: dict):
"""Record each module's largest input magnitude seen while active -- the
scan's stand-in for the calibration amax behind input_global_scale."""
handles = []
def recorder(name):
def hook(_module, inputs):
amax = inputs[0].abs().amax().item()
store[name] = max(store.get(name, 0.0), amax)
return hook
try:
for name, module in modules.items():
handles.append(module.register_forward_pre_hook(recorder(name)))
yield
finally:
for handle in handles:
handle.remove()
def _activation_pre_hook(fmt: str, global_scale: float = 0.0):
"""Forward-pre-hook that fake-quantizes a module's input as `fmt`."""
if fmt == "nvfp4":
def hook(_module, inputs):
return (_fake_quant_nvfp4_activation(inputs[0], global_scale),) + tuple(
inputs[1:]
)
else:
def hook(_module, inputs):
return (_fake_quant_fp8_activation(inputs[0]),) + tuple(inputs[1:])
return hook
@contextmanager
def _quantized_activations(modules: dict, fmt: str, amax_by_name: dict):
"""Temporarily fake-quantize each module's input activations as `fmt`."""
handles = []
try:
for name, module in modules.items():
if fmt == "nvfp4":
amax = amax_by_name.get(name, 0.0)
if amax <= 0:
continue
hook = _activation_pre_hook("nvfp4", 448.0 * 6.0 / amax)
else:
hook = _activation_pre_hook("fp8")
handles.append(module.register_forward_pre_hook(hook))
yield
finally:
for handle in handles:
handle.remove()
@torch.no_grad()
def scan_mlp_sensitivity(
model,
loader: DataLoader,
module_names: list[str],
nvfp4_args: QuantizationArgs,
fp8_args: QuantizationArgs,
n_samples: int,
keep_positions: int = 64,
context: str = "clean",
) -> list[LayerSensitivity]:
"""Rank decoder layers by what each format costs the model's own output.
One layer's MLP at a time is fake-quantized -- weights AND input
activations, matching W4A4 serving -- while every other layer stays at
full precision, and the model's output distribution is compared against
the untouched model by mean KL over calibration tokens. That is a direct
measurement in the same currency the checkpoint is finally judged in.
With context='quantized', the control flips: every scanned layer's MLP
is fake-quantized at once -- weights (BF16 originals parked in CPU
memory, roughly their on-disk size in host RAM) and input activations
-- and each trial promotes one layer back to FP8 inside that context,
scoring it by the whole-model KL it removes. The isolated scan asks
"how much damage does quantizing this layer do to a clean model?"; the
in-context scan asks "how much does promoting this layer repair a
quantized one?". context='quantized-acts' leaves weights BF16
everywhere and quantizes activations only, each trial toggling one
layer's hook to dynamic FP8, isolating the activation-format half of a
promotion.
Treat the non-clean contexts as diagnostics, not better rankers. They
were built to explain why promoting Qwen3.8's outlier-heavy last eight
layers (down_proj input amax 300-717 against ~30 mid-stack) measures
~0.0016 lower emulated KL end to end than promoting this scan's picks
-- and measured on Qwen3.8, both still rank early/mid layers on top
and put the late outlier region near the bottom. So the late-layer
advantage is invisible to every minmax fake-quant trial, isolated or
in-context, weights or activations: it emerges only through the full
GPTQ pipeline, whose sequential error compensation reshapes where a
shipped checkpoint's residual error actually lives. On Qwen-family
hybrids, use --fp8-mlp gptq-loss (rank_mlp_gptq_loss below), which
measures error where GPTQ does and recovers the winning list exactly.
The in-context marginals also interact strongly -- a third of
layers measure negative, i.e. promoting them alone makes the
fully-quantized model worse through lost error cancellation -- which
is itself evidence that single-layer marginals in a high-error context
do not predict small differences between shipped checkpoints.
Activations are part of every trial because promotion changes their
format too: NVFP4 quantizes them group-16 under a static per-tensor
global scale, FP8 with dynamic per-token scales. The scan's earlier
proxies measured strictly worse: a weight-only trial has nothing to
say about activation outliers at all, and activation-weighted weight
reconstruction error could not separate gemma-4-E2B's layers (all
within 11% of each other, because relative weight error is mostly a
property of how Gaussian a matrix is).
Three caveats on the ranking. Per-layer KL measured in isolation does not
sum to whole-model KL, since quantization errors in different layers
interact, so taking the top N is a greedy heuristic rather than an optimal
subset. The NVFP4 trial uses plain minmax weights: GPTQ later claws back
part of the NVFP4 error on whatever stays at NVFP4, which this cannot
model. And the ranking is a property of the data it is measured on, which
is why --sensitivity-dataset exists and defaults to chat rather than to
the wider calibration mixture -- see GUIDE.md for the measurement behind
that.
"""
modules = dict(model.named_modules())
layers: dict[str, list[str]] = {}
for name in module_names:
if name in modules:
layers.setdefault(_layer_key(name), []).append(name)
if not layers:
return []
device = next(model.parameters()).device
batches = []
for i, batch in enumerate(loader):
if i >= n_samples:
break
batches.append(
{
k: v.to(device) if isinstance(v, torch.Tensor) else v
for k, v in batch.items()
}
)
if not batches:
return []
def logprobs(batch):
"""Log-probs at evenly spaced positions -- the full sequence's worth of
vocab logits would be tens of GB to hold as a reference."""
logits = model(**batch).logits[0]
keep = torch.linspace(
0,
logits.shape[0] - 1,
min(keep_positions, logits.shape[0]),
device=logits.device,
).long()
return logits[keep].float().log_softmax(-1)
def mean_kl(reference) -> float:
total = count = 0
for batch, ref in zip(batches, reference):
ref = ref.to(device).float()
kl = (ref.exp() * (ref - logprobs(batch))).sum(-1)
total += kl.sum().item()
count += kl.numel()
return total / count
what = (
"activations only" if context == "quantized-acts" else "weights + activations"
)
print(
f"Scanning MLP sensitivity: {len(layers)} layers x "
f"{len(batches)} samples ({context} context, {what})"
)
scanned = {name: modules[name] for names in layers.values() for name in names}
input_amax: dict[str, float] = {}
with _recorded_input_amax(scanned, input_amax):
reference = [logprobs(batch).half().cpu() for batch in batches]
def extra_bytes(names) -> int:
return sum(
_stored_bytes(modules[name].weight, fp8_args)
- _stored_bytes(modules[name].weight, nvfp4_args)
for name in names
)
ranking = []
if context != "clean":
ranking = _scan_in_context(
modules,
layers,
scanned,
input_amax,
nvfp4_args,
fp8_args,
mean_kl,
reference,
extra_bytes,
device,
quantize_weights=context == "quantized",
)
else:
for position, (key, names) in enumerate(sorted(layers.items()), start=1):
group = {name: modules[name] for name in names}
with (
_swapped_weights(group, nvfp4_args),
_quantized_activations(group, "nvfp4", input_amax),
):
kl_nvfp4 = mean_kl(reference)
with (
_swapped_weights(group, fp8_args),
_quantized_activations(group, "fp8", input_amax),
):
kl_fp8 = mean_kl(reference)
ranking.append(
LayerSensitivity(
key=key,
index=_layer_index(key),
nvfp4=kl_nvfp4,
fp8=kl_fp8,
modules=tuple(sorted(names)),
extra_bytes=extra_bytes(names),
)
)
print(
f" [{position}/{len(layers)}] layer {ranking[-1].index}: "
f"NVFP4 {kl_nvfp4:.5f} FP8 {kl_fp8:.5f}"
)
ranking.sort(key=lambda layer: layer.gain, reverse=True)
return ranking
def _scan_in_context(
modules: dict,
layers: dict[str, list[str]],
scanned: dict,
input_amax: dict[str, float],
nvfp4_args: QuantizationArgs,
fp8_args: QuantizationArgs,
mean_kl,
reference,
extra_bytes,
device,
quantize_weights: bool = True,
) -> list[LayerSensitivity]:
"""The in-context trials behind scan_mlp_sensitivity(context != 'clean').
Baseline first: every scanned module's weight is replaced with its NVFP4
fake-quantized self (BF16 original parked on CPU) and gets an NVFP4
input-activation hook, and the whole-model KL of that state is measured.
Each trial then lifts one layer to FP8 -- weights re-fake-quantized from
the parked original, hook swapped to dynamic per-token FP8 -- remeasures,
and restores. A layer's LayerSensitivity carries the shared baseline as
`nvfp4` and its promoted KL as `fp8`, so `gain` is the promotion marginal
and the ranking sorts exactly as the isolated scan's does.
Without `quantize_weights` (the 'quantized-acts' context), weights are
untouched everywhere and the trials only toggle the activation hook, so
the marginal isolates the activation-format half of a promotion.
The NVFP4 activation hooks reuse the amax recorded on the clean reference
pass. Calibration would instead see amax under quantized-upstream drift,
but the drift is small in scale terms and a static global scale off by a
few percent changes little next to 4-bit group rounding.
"""
handles: dict[str, object] = {}
def install_nvfp4_hook(name):
amax = input_amax.get(name, 0.0)