Views
No views yet
1import json, os
2from compressed_tensors.offload import dispatch_model
3from datasets import load_dataset
4from transformers import AutoModelForCausalLM, AutoTokenizer
5
6from llmcompressor import oneshot
7from llmcompressor.modifiers.quantization import QuantizationModifier
8
9MODEL_ID = "JetBrains/Mellum2-12B-A2.5B-Thinking"
10
11# Load model.
12model = AutoModelForCausalLM.from_pretrained(MODEL_ID)
13tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
14
15
16DATASET_ID = "HuggingFaceH4/ultrachat_200k"
17DATASET_SPLIT = "train_sft"
18
19# Select number of samples. 512 samples is a good place to start.
20# Increasing the number of samples can improve accuracy.
21NUM_CALIBRATION_SAMPLES = 20
22MAX_SEQUENCE_LENGTH = 2048
23
24# Load dataset and preprocess.
25ds = load_dataset(DATASET_ID, split=f"{DATASET_SPLIT}[:{NUM_CALIBRATION_SAMPLES}]")
26ds = ds.shuffle(seed=42)
27
28
29def preprocess(example):
30 return {
31 "text": tokenizer.apply_chat_template(
32 example["messages"],
33 tokenize=False,
34 )
35 }
36
37
38ds = ds.map(preprocess)
39
40
41# Tokenize inputs.
42def tokenize(sample):
43 return tokenizer(
44 sample["text"],
45 padding=False,
46 max_length=MAX_SEQUENCE_LENGTH,
47 truncation=True,
48 add_special_tokens=False,
49 )
50
51
52ds = ds.map(tokenize, remove_columns=ds.column_names)
53
54# Configure the quantization algorithm and scheme.
55# In this case, we:
56# * quantize the weights to fp4 with per group 16 via ptq
57# * calibrate a global_scale for activations, which will be used to
58# quantize activations to fp4 on the fly
59recipe = QuantizationModifier(targets="Linear", scheme="NVFP4", ignore=["lm_head"])
60
61# Apply quantization.
62oneshot(
63 model=model,
64 dataset=ds,
65 recipe=recipe,
66 max_seq_length=MAX_SEQUENCE_LENGTH,
67 num_calibration_samples=NUM_CALIBRATION_SAMPLES,
68)
69
70print("\n\n")
71print("========== SAMPLE GENERATION ==============")
72dispatch_model(model)
73input_ids = tokenizer("Hello my name is", return_tensors="pt").input_ids.to(
74 model.device
75)
76output = model.generate(input_ids, max_new_tokens=100)
77print(tokenizer.decode(output[0]))
78print("==========================================\n\n")
79
80
81# Save to disk in compressed-tensors format.
82SAVE_DIR = MODEL_ID.rstrip("/").split("/")[-1] + "-NVFP4"
83model.save_pretrained(SAVE_DIR, save_compressed=True)
84tokenizer.save_pretrained(SAVE_DIR)
85