jaytonde05's picture
Add model quantization scripts and command reference
e695de7 verified
Raw
History Blame Contribute Delete
7.46 kB
import argparse
import os
import shutil
import torch
from datasets import load_dataset
from transformers import AutoModelForCausalLM, AutoTokenizer
from huggingface_hub import HfApi, create_repo
from huggingface_hub.constants import HF_HUB_CACHE
from llmcompressor import oneshot
from llmcompressor.modifiers.transform import AWQModifier
from llmcompressor.modifiers.transform.awq import AWQMapping
from llmcompressor.modifiers.quantization import QuantizationModifier
MODEL_ID = "Qwen/Qwen3-8B"
QWEN_AWQ_MAPPINGS = [
AWQMapping(
"re:.*input_layernorm",
["re:.*q_proj", "re:.*k_proj", "re:.*v_proj"],
),
AWQMapping(
"re:.*v_proj",
["re:.*o_proj"],
),
AWQMapping(
"re:.*post_attention_layernorm",
["re:.*gate_proj", "re:.*up_proj"],
),
AWQMapping(
"re:.*up_proj",
["re:.*down_proj"],
),
]
SCHEMES = {
"fp8": "FP8_BLOCK",
"nvfp4": "NVFP4",
"mxfp4": "MXFP4",
"mxfp8": "MXFP8",
}
def purge_base_cache(model_id: str):
"""Delete the downloaded base-model snapshot from the HF hub cache.
Safe to call only after the model has been fully loaded into (GPU) memory,
since the on-disk safetensors are no longer needed to quantize and save.
"""
org_name = model_id.replace("/", "--")
cache_dir = os.path.join(HF_HUB_CACHE, f"models--{org_name}")
if os.path.isdir(cache_dir):
print(f"Purging base-model cache: {cache_dir}")
shutil.rmtree(cache_dir, ignore_errors=True)
else:
print(f"No base-model cache found at: {cache_dir}")
def load_wikitext2(num_samples: int):
ds = load_dataset(
"Salesforce/wikitext",
"wikitext-2-raw-v1",
split="train",
)
ds = ds.filter(lambda x: x["text"] is not None and len(x["text"].strip()) > 64)
ds = ds.shuffle(seed=42)
ds = ds.select(range(min(num_samples, len(ds))))
return ds
def build_hub_repo_id(
model_id: str,
scheme_name: str,
namespace: str | None = None,
token: str | None = None,
):
model_name = model_id.split("/")[-1]
repo_name = f"{model_name}-{scheme_name.upper()}-AWQ-wikitext2"
if namespace is None:
api = HfApi(token=token)
user_info = api.whoami(token=token)
namespace = user_info["name"]
return f"{namespace}/{repo_name}"
def upload_to_hub(
local_dir: str,
repo_id: str,
private: bool,
commit_message: str,
token: str | None = None,
):
print(f"Creating/checking HF repo: {repo_id}")
create_repo(
repo_id=repo_id,
repo_type="model",
private=private,
exist_ok=True,
token=token,
)
api = HfApi(token=token)
print(f"Uploading local checkpoint from: {local_dir}")
print(f"Target repo: https://huggingface.co/{repo_id}")
api.upload_folder(
folder_path=local_dir,
repo_id=repo_id,
repo_type="model",
commit_message=commit_message,
token=token,
)
print("Upload complete")
def main():
parser = argparse.ArgumentParser()
parser.add_argument(
"--scheme",
choices=["fp8", "nvfp4", "mxfp4", "mxfp8"],
required=True,
)
parser.add_argument("--model-id", default=MODEL_ID)
parser.add_argument("--num-calibration-samples", type=int, default=512)
parser.add_argument("--max-seq-length", type=int, default=2048)
parser.add_argument("--output-dir", default=None)
parser.add_argument(
"--upload-to-hub",
action="store_true",
help="Upload saved compressed checkpoint to Hugging Face Hub",
)
parser.add_argument(
"--purge-base-after-load",
action="store_true",
help="Delete the base-model HF cache after loading it into memory "
"(frees disk before saving large quantized outputs).",
)
parser.add_argument(
"--delete-local-after-upload",
action="store_true",
help="Delete the local compressed checkpoint after a successful upload.",
)
parser.add_argument(
"--hub-namespace",
default=None,
help="HF username/org. If not passed, uses logged-in HF user.",
)
parser.add_argument(
"--private",
action="store_true",
help="Create Hugging Face repo as private",
)
parser.add_argument(
"--hf-token",
default=None,
help="Optional HF token. Prefer HF_TOKEN env var or huggingface-cli login.",
)
args = parser.parse_args()
scheme = SCHEMES[args.scheme]
model_name = args.model_id.split("/")[-1]
output_dir = args.output_dir or f"{model_name}-{args.scheme.upper()}-AWQ-wikitext2"
print(f"Loading model: {args.model_id}")
# Shard the model across all visible GPUs (no CPU offloading). With two
# 97GB GPUs, accelerate places different decoder layers on each device,
# leaving ample headroom for the AWQ activation cache so we can run the
# full-quality calibration footprint.
model = AutoModelForCausalLM.from_pretrained(
args.model_id,
torch_dtype="auto",
device_map="auto",
trust_remote_code=True,
)
tokenizer = AutoTokenizer.from_pretrained(
args.model_id,
trust_remote_code=True,
)
if tokenizer.pad_token is None:
tokenizer.pad_token = tokenizer.eos_token
if args.purge_base_after_load:
purge_base_cache(args.model_id)
print("Loading WikiText-2 calibration dataset")
calib_ds = load_wikitext2(args.num_calibration_samples)
recipe = [
AWQModifier(
mappings=QWEN_AWQ_MAPPINGS,
),
QuantizationModifier(
targets="Linear",
scheme=scheme,
ignore=["lm_head"],
),
]
print(f"Running AWQ + {scheme} quantization")
oneshot(
model=model,
tokenizer=tokenizer,
dataset=calib_ds,
recipe=recipe,
max_seq_length=args.max_seq_length,
num_calibration_samples=args.num_calibration_samples,
)
print(f"Saving compressed model locally to: {output_dir}")
model.save_pretrained(
output_dir,
save_compressed=True,
)
tokenizer.save_pretrained(output_dir)
if args.upload_to_hub:
hf_token = args.hf_token or os.environ.get("HF_TOKEN")
hub_repo_id = build_hub_repo_id(
model_id=args.model_id,
scheme_name=args.scheme,
namespace=args.hub_namespace,
token=hf_token,
)
upload_to_hub(
local_dir=output_dir,
repo_id=hub_repo_id,
private=args.private,
commit_message=(
f"Upload {args.model_id} {args.scheme.upper()} "
"AWQ compressed checkpoint calibrated on WikiText-2"
),
token=hf_token,
)
if args.delete_local_after_upload:
print(f"Deleting local checkpoint after upload: {output_dir}")
shutil.rmtree(output_dir, ignore_errors=True)
print("Done")
if __name__ == "__main__":
main()
#python quantize_my_model.py --scheme fp8 --upload-to-hub --hub-namespace jaytonde5
#python quantize_my_model.py --scheme nvfp4 --upload-to-hub --hub-namespace jaytonde5
#python quantize_my_model.py --scheme mxfp4 --upload-to-hub --hub-namespace jaytonde5
#python quantize_my_model.py --scheme mxfp8 --upload-to-hub --hub-namespace jaytonde5