|
| 1 | +import torch |
| 2 | +from compressed_tensors.quantization import QuantizationScheme |
| 3 | +from compressed_tensors.quantization.quant_args import ( |
| 4 | + QuantizationArgs, |
| 5 | + QuantizationStrategy, |
| 6 | + QuantizationType, |
| 7 | +) |
| 8 | +from transformers import AutoModelForCausalLM, AutoTokenizer |
| 9 | + |
| 10 | +from llmcompressor import oneshot |
| 11 | +from llmcompressor.modeling.gpt_oss import convert_model_for_quantization_gptoss |
| 12 | +from llmcompressor.modifiers.quantization import QuantizationModifier |
| 13 | + |
| 14 | + |
| 15 | +def main(): |
| 16 | + MODEL_ID = "openai/gpt-oss-20b" |
| 17 | + BASE_NAME = MODEL_ID.rstrip("/").split("/")[-1] |
| 18 | + OUTPUT_DIR = f"{BASE_NAME}-w4a8-channelwise" |
| 19 | + |
| 20 | + print(f"[GPT-OSS] Loading model: {MODEL_ID}") |
| 21 | + model = AutoModelForCausalLM.from_pretrained( |
| 22 | + MODEL_ID, |
| 23 | + torch_dtype=torch.bfloat16, |
| 24 | + device_map="auto", |
| 25 | + trust_remote_code=True, |
| 26 | + ) |
| 27 | + tokenizer = AutoTokenizer.from_pretrained(MODEL_ID, trust_remote_code=True) |
| 28 | + |
| 29 | + # ---- GPT-OSS MoE → linear experts conversion ---- |
| 30 | + print("[GPT-OSS] Converting fused MoE experts to LinearExperts for quantization...") |
| 31 | + convert_model_for_quantization_gptoss(model) |
| 32 | + print("[GPT-OSS] Conversion completed.") |
| 33 | + |
| 34 | + # ---- Quantization config: W4A8 (int4 weights, int8 activations) ---- |
| 35 | + |
| 36 | + # Weights: 4-bit, channelwise, symmetric, static |
| 37 | + weights_args = QuantizationArgs( |
| 38 | + num_bits=4, |
| 39 | + type=QuantizationType.INT, |
| 40 | + strategy=QuantizationStrategy.CHANNEL, |
| 41 | + symmetric=True, |
| 42 | + dynamic=False, |
| 43 | + ) |
| 44 | + |
| 45 | + # Activations: 8-bit, per-token, asymmetric, dynamic |
| 46 | + activations_args = QuantizationArgs( |
| 47 | + num_bits=8, |
| 48 | + type=QuantizationType.INT, |
| 49 | + strategy=QuantizationStrategy.TOKEN, |
| 50 | + symmetric=False, |
| 51 | + dynamic=True, |
| 52 | + observer=None, |
| 53 | + ) |
| 54 | + |
| 55 | + # Apply to all Linear layers, excluding lm_head |
| 56 | + scheme = QuantizationScheme( |
| 57 | + targets=["Linear"], |
| 58 | + weights=weights_args, |
| 59 | + input_activations=activations_args, |
| 60 | + ) |
| 61 | + |
| 62 | + recipe = QuantizationModifier( |
| 63 | + config_groups={"group_0": scheme}, |
| 64 | + ignore=["lm_head"], |
| 65 | + ) |
| 66 | + |
| 67 | + print(f"[GPT-OSS] Starting oneshot quantization → {OUTPUT_DIR}") |
| 68 | + oneshot( |
| 69 | + model=model, |
| 70 | + recipe=recipe, |
| 71 | + tokenizer=tokenizer, |
| 72 | + output_dir=OUTPUT_DIR, |
| 73 | + trust_remote_code_model=True, |
| 74 | + ) |
| 75 | + print(f"[GPT-OSS] Quantization finished. Quantized model written to: {OUTPUT_DIR}") |
| 76 | + |
| 77 | + |
| 78 | +if __name__ == "__main__": |
| 79 | + main() |
0 commit comments