Skip to content

Commit f19deaa

Browse files
authored
1 parent 7359e1b commit f19deaa

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
from transformers import AutoModelForCausalLM, AutoTokenizer
2+
3+
from llmcompressor import oneshot
4+
from llmcompressor.modeling import replace_modules_for_calibration
5+
from llmcompressor.modifiers.quantization import QuantizationModifier
6+
from llmcompressor.utils import dispatch_for_generation
7+
8+
MODEL_ID = "meta-llama/Llama-4-Scout-17B-16E-Instruct"
9+
10+
# Load model.
11+
model = AutoModelForCausalLM.from_pretrained(MODEL_ID, torch_dtype="auto")
12+
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
13+
model = replace_modules_for_calibration(model)
14+
# Configure the quantization algorithm and scheme.
15+
# In this case, we:
16+
# * quantize the weights to fp8 with block size 128 via ptq
17+
# * quantize the activations to fp8 with dynamic group activations
18+
recipe = QuantizationModifier(
19+
targets="Linear",
20+
scheme="FP8_BLOCK",
21+
ignore=[
22+
"re:.*lm_head",
23+
"re:.*self_attn",
24+
"re:.*router",
25+
"re:vision_model.*",
26+
"re:multi_modal_projector.*",
27+
"Llama4TextAttention",
28+
],
29+
)
30+
31+
# Apply quantization.
32+
oneshot(model=model, recipe=recipe)
33+
34+
# Confirm generations of the quantized model look sane.
35+
print("========== SAMPLE GENERATION ==============")
36+
dispatch_for_generation(model)
37+
input_ids = tokenizer("Hello my name is", return_tensors="pt").input_ids.to(
38+
model.device
39+
)
40+
output = model.generate(input_ids, max_new_tokens=20)
41+
print(tokenizer.decode(output[0]))
42+
print("==========================================")
43+
44+
# Save to disk in compressed-tensors format.
45+
SAVE_DIR = MODEL_ID.split("/")[1] + "-FP8-BLOCK"
46+
model.save_pretrained(SAVE_DIR)
47+
tokenizer.save_pretrained(SAVE_DIR)

0 commit comments

Comments
 (0)