from llmcompressor.modifiers.quantization import GPTQModifierfrom llmcompressor.modifiers.smoothquant import SmoothQuantModifierfrom llmcompressor.transformers import oneshotfrom transformers import AutoModelForCausalLM, AutoTokenizer
# Load modelmodel_stub = "Qwen/Qwen3-4B-Instruct"model_name = model_stub.split("/")[-1]
num_samples = 1024max_seq_len = 8192
model = AutoModelForCausalLM.from_pretrained(model_stub)
tokenizer = AutoTokenizer.from_pretrained(model_stub)
def preprocess_fn(example): return {"text": tokenizer.apply_chat_template(example["messages"], add_generation_prompt=False, tokenize=False)}
ds = load_dataset("neuralmagic/LLM_compression_calibration", split="train")ds = ds.map(preprocess_fn)
# Configure the quantization algorithm and schemerecipe = [ SmoothQuantModifier( smoothing_strength=0.9, mappings=[ [["re:.*q_proj", "re:.*k_proj", "re:.*v_proj"], "re:.*input_layernorm"], ], ), GPTQModifier( ignore: ["lm_head"] config_groups={"group_0": {"targets": ["Linear"], "weights": { "num_bits": 4, "type": int, "strategy": "group", "group_size": 128, "symmetric": true, "dynamic": false, "observer": "mse" } } }, dampening_frac=0.1, )]
# Apply quantizationoneshot( model=model, dataset=ds, recipe=recipe, max_seq_length=max_seq_len, num_calibration_samples=num_samples,)
# Save to disk in compressed-tensors formatsave_path = model_name + "-quantized.w8a8"model.save_pretrained(save_path)tokenizer.save_pretrained(save_path)print(f"Model and tokenizer saved to: {save_path}")