Views
No views yet
1from vllm import LLM, SamplingParams
2from transformers import AutoTokenizer
3
4model_id = "neuralmagic/Phi-3.5-mini-instruct-FP8-KV"
5
6sampling_params = SamplingParams(temperature=0.6, top_p=0.9, max_tokens=256)
7
8tokenizer = AutoTokenizer.from_pretrained(model_id)
9
10messages = [
11 {"role": "system", "content": "You are a pirate chatbot who always responds in pirate speak!"},
12 {"role": "user", "content": "Who are you? Remember to respond in pirate speak!"},
13]
14
15prompts = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
16
17llm = LLM(model=model_id, kv_cache_dtype="fp8")
18
19outputs = llm.generate(prompts, sampling_params)
20
21generated_text = outputs[0].outputs[0].text
22print(generated_text)1from datasets import load_dataset
2from transformers import AutoTokenizer
3
4from llmcompressor.transformers import SparseAutoModelForCausalLM, oneshot
5
6# Select model and load it.
7# Phi-3.5 is a special case for KV cache quantization because it has
8# fused QKV linear layers.
9MODEL_ID = "microsoft/Phi-3.5-mini-instruct"
10model = SparseAutoModelForCausalLM.from_pretrained(
11 MODEL_ID,
12 device_map="auto",
13 torch_dtype="auto",
14)
15tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
16
17# Select calibration dataset.
18DATASET_ID = "HuggingFaceH4/ultrachat_200k"
19DATASET_SPLIT = "train_sft"
20
21# Select number of samples. 512 samples is a good place to start.
22# Increasing the number of samples can improve accuracy.
23NUM_CALIBRATION_SAMPLES = 512
24MAX_SEQUENCE_LENGTH = 2048
25
26# Load dataset and preprocess.
27ds = load_dataset(DATASET_ID, split=DATASET_SPLIT)
28ds = ds.shuffle(seed=42).select(range(NUM_CALIBRATION_SAMPLES))
29
30
31def process_and_tokenize(example):
32 text = tokenizer.apply_chat_template(example["messages"], tokenize=False)
33 return tokenizer(
34 text,
35 padding=False,
36 max_length=MAX_SEQUENCE_LENGTH,
37 truncation=True,
38 add_special_tokens=False,
39 )
40
41
42ds = ds.map(process_and_tokenize, remove_columns=ds.column_names)
43
44# Configure the quantization algorithm and scheme.
45# In this case, we:
46# * quantize the weights to fp8 with per-tensor scales
47# * quantize the activations to fp8 with per-tensor scales
48# * quantize the kv cache to fp8 with per-tensor scales
49recipe = """
50quant_stage:
51 quant_modifiers:
52 QuantizationModifier:
53 ignore: ["lm_head"]
54 config_groups:
55 group_0:
56 weights:
57 num_bits: 8
58 type: float
59 strategy: tensor
60 dynamic: false
61 symmetric: true
62 input_activations:
63 num_bits: 8
64 type: float
65 strategy: tensor
66 dynamic: false
67 symmetric: true
68 targets: ["Linear"]
69 kv_cache_scheme:
70 num_bits: 8
71 type: float
72 strategy: tensor
73 dynamic: false
74 symmetric: true
75"""
76
77# Apply algorithms.
78oneshot(
79 model=model,
80 dataset=ds,
81 recipe=recipe,
82 max_seq_length=MAX_SEQUENCE_LENGTH,
83 num_calibration_samples=NUM_CALIBRATION_SAMPLES,
84)
85
86# Confirm generations of the quantized model look sane.
87print("\n\n")
88print("========== SAMPLE GENERATION ==============")
89input_ids = tokenizer("Hello my name is", return_tensors="pt").input_ids.to("cuda")
90output = model.generate(input_ids, max_new_tokens=100)
91print(tokenizer.decode(output[0]))
92print("==========================================\n\n")
93
94# Save to disk compressed.
95SAVE_DIR = MODEL_ID.split("/")[1] + "-FP8-KV"
96model.save_pretrained(SAVE_DIR, save_compressed=True)
97tokenizer.save_pretrained(SAVE_DIR)lm_eval \
--model vllm \
--model_args pretrained="neuralmagic/Phi-3.5-mini-instruct-FP8-KV",kv_cache_dtype="fp8",gpu_memory_utilization=0.4,add_bos_token=True,max_model_len=4096 \
--tasks openllm \
--batch_size auto| Benchmark | Phi-3.5-mini-instruct | Phi-3.5-mini-instruct-FP8-KV(this model) | Recovery |
| MMLU (5-shot) | 68.81 | 68.56 | 99.64% |
| ARC Challenge (25-shot, acc_norm) | 64.68 | 64.51 | 99.74% |
| GSM-8K (5-shot, strict-match) | 78.24 | 77.26 | 98.75% |
| Hellaswag (10-shot, acc_norm) | 79.03 | 78.88 | 99.81% |
| Winogrande (5-shot, acc) | 73.40 | 73.80 | 100.5% |
| TruthfulQA (0-shot, mc2) | 56.39 | 56.95 | 100.9% |
| Average | 70.09 | 70.00 | 99.89% |