| """ |
| 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() |
|
|