Views
No views yet
1from datasets import load_dataset
2from transformers import AutoModelForCausalLM, AutoTokenizer
3from llmcompressor.modifiers.quantization import GPTQModifier
4from llmcompressor.modifiers.smoothquant import SmoothQuantModifier
5from llmcompressor.transformers import oneshot
6
7model_id = "Qwen/Qwen3-4B-Instruct-2507"
8model = AutoModelForCausalLM.from_pretrained(
9 model_id,
10 torch_dtype="auto",
11 device_map="auto",
12 low_cpu_mem_usage=True,
13 offload_folder="./offload_tmp",
14 # for 2x 3090s.
15 max_memory={0: "22GB", 1: "22GB", "cpu": "64GB"},
16)
17tokenizer = AutoTokenizer.from_pretrained(model_id)
18
19DATASET_ID = "HuggingFaceH4/ultrachat_200k"
20DATASET_SPLIT = "train_sft"
21NUM_CALIBRATION_SAMPLES = 512
22MAX_SEQUENCE_LENGTH = 2048
23
24print("Loading and preprocessing calibration dataset...")
25ds = load_dataset(DATASET_ID, split=f"{DATASET_SPLIT}[:{NUM_CALIBRATION_SAMPLES}]")
26ds = ds.shuffle(seed=42)
27
28def preprocess(example):
29 return {
30 "text": tokenizer.apply_chat_template(
31 example["messages"],
32 tokenize=False,
33 )
34 }
35
36ds = ds.map(preprocess)
37
38def tokenize(sample):
39 return tokenizer(
40 sample["text"],
41 padding=False,
42 max_length=MAX_SEQUENCE_LENGTH,
43 truncation=True,
44 add_special_tokens=False,
45 )
46
47ds = ds.map(tokenize, remove_columns=ds.column_names)
48print("Dataset ready.")
49
50recipe = [
51 SmoothQuantModifier(smoothing_strength=0.8),
52 GPTQModifier(targets="Linear", scheme="W8A8", ignore=["lm_head"]),
53]
54
55output_dir = "./Qwen3-4B-Instruct-2507-W8A8"
56print(f"Starting one-shot quantization. Output will be in '{output_dir}'")
57
58oneshot(
59 model=model,
60 dataset=ds,
61 recipe=recipe,
62 max_seq_length=MAX_SEQUENCE_LENGTH,
63 num_calibration_samples=NUM_CALIBRATION_SAMPLES,
64 output_dir=output_dir,
65)
66print("Quantization complete.")
67
68SAVE_DIR = "Qwen3-4B-Instruct-2507-W8A8"
69print(f"Saving compressed model and tokenizer to '{SAVE_DIR}'...")
70model.save_pretrained(SAVE_DIR, save_compressed=True)
71tokenizer.save_pretrained(SAVE_DIR)