File size: 4,484 Bytes
3ccaf5a | 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 | """
Offline quantization of base models to AWQ / GPTQ with a FIXED calibration set,
using llmcompressor (Neural Magic). Output is compressed-tensors format, which
vLLM loads natively.
Must be run from the `sonthh-stepprobe-quant` conda env (vLLM's main env has
incompatible dep pins with llmcompressor).
Usage:
/home/aiteam1/anaconda3/envs/sonthh-stepprobe-quant/bin/python \
scripts/quantize_models.py \
--model deepseek-ai/DeepSeek-R1-Distill-Qwen-7B \
--method gptq --bits 4 --group-size 128 \
--output results/quantized_models/r1-qwen-7b_gptq_w4
"""
import argparse
import os
import random
CALIB_N_SAMPLES = 128
CALIB_SEQ_LEN = 512
CALIB_SEED = 42
def load_calib_dataset(tokenizer):
"""Fixed WikiText-2 calibration set, same for every (model, method, bits)."""
from datasets import load_dataset
ds = load_dataset("wikitext", "wikitext-2-raw-v1", split="train")
ds = ds.filter(lambda x: len(x["text"].strip()) > 200)
ds = ds.shuffle(seed=CALIB_SEED).select(range(min(CALIB_N_SAMPLES, len(ds))))
def tokenize(example):
return tokenizer(
example["text"],
padding=False,
max_length=CALIB_SEQ_LEN,
truncation=True,
add_special_tokens=False,
)
ds = ds.map(tokenize, remove_columns=ds.column_names)
return ds
def build_recipe(method: str, bits: int, group_size: int):
"""Build an llmcompressor recipe for the given (method, bits)."""
from compressed_tensors.quantization import (
QuantizationArgs,
QuantizationScheme,
QuantizationStrategy,
QuantizationType,
)
from llmcompressor.modifiers.quantization import GPTQModifier
weights_args = QuantizationArgs(
num_bits=bits,
type=QuantizationType.INT,
symmetric=True,
strategy=QuantizationStrategy.GROUP,
group_size=group_size,
)
scheme = QuantizationScheme(targets=["Linear"], weights=weights_args)
if method == "gptq":
return GPTQModifier(
config_groups={"group_0": scheme},
ignore=["lm_head"],
)
elif method == "awq":
if bits != 4:
raise ValueError(f"AWQ path only supports 4-bit; got bits={bits}")
from llmcompressor.modifiers.awq import AWQModifier
return AWQModifier(
config_groups={"group_0": scheme},
ignore=["lm_head"],
)
else:
raise ValueError(f"Unknown method: {method}")
def quantize(model_name: str, method: str, bits: int, group_size: int, output_dir: str):
from llmcompressor import oneshot
from transformers import AutoModelForCausalLM, AutoTokenizer
print(f"Loading base model: {model_name}")
model = AutoModelForCausalLM.from_pretrained(
model_name,
torch_dtype="auto",
device_map="auto",
trust_remote_code=True,
)
tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
print(f"Loading calibration set: WikiText-2 ({CALIB_N_SAMPLES} samples, seq_len={CALIB_SEQ_LEN}, seed={CALIB_SEED})")
ds = load_calib_dataset(tokenizer)
recipe = build_recipe(method, bits, group_size)
print(f"Running {method.upper()} oneshot: bits={bits}, group_size={group_size}")
oneshot(
model=model,
dataset=ds,
recipe=recipe,
output_dir=output_dir,
max_seq_length=CALIB_SEQ_LEN,
num_calibration_samples=CALIB_N_SAMPLES,
)
tokenizer.save_pretrained(output_dir)
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--model", required=True, help="HuggingFace model name or local path")
parser.add_argument("--method", choices=["awq", "gptq"], required=True)
parser.add_argument("--bits", type=int, required=True)
parser.add_argument("--group-size", type=int, default=128)
parser.add_argument("--output", required=True, help="Output directory for quantized model")
args = parser.parse_args()
if os.path.isfile(os.path.join(args.output, "config.json")):
print(f"[SKIP] Already quantized: {args.output}")
return
os.makedirs(args.output, exist_ok=True)
print(f"Quantizing {args.model} -> {args.method} w{args.bits} (group={args.group_size})")
print(f"Output: {args.output}")
quantize(args.model, args.method, args.bits, args.group_size, args.output)
print(f"Done: {args.output}")
if __name__ == "__main__":
main()
|