Views
No views yet
W4A16 with the lm_head ignored.1from transformers import AutoTokenizer, AutoModelForCausalLM
2import torch
3
4MODEL_ID = "mistralai/Mistral-Small-24B-Instruct-2501"
5
6# Load model with better memory management
7model = AutoModelForCausalLM.from_pretrained(
8 MODEL_ID,
9 device_map="auto",
10 torch_dtype=torch.bfloat16,
11)
12tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)1from datasets import load_dataset
2
3NUM_CALIBRATION_SAMPLES=1024
4MAX_SEQUENCE_LENGTH=4096
5
6# Load dataset.
7ds = load_dataset("HuggingFaceH4/ultrachat_200k", split="train_sft")
8ds = ds.shuffle(seed=42).select(range(NUM_CALIBRATION_SAMPLES))
9
10# Preprocess the data into the format the model is trained with.
11def preprocess(example):
12 return {"text": tokenizer.apply_chat_template(example["messages"], tokenize=False,)}
13ds = ds.map(preprocess)
14
15# Tokenize the data (be careful with bos tokens - we need add_special_tokens=False since the chat_template already added it).
16def tokenize(sample):
17 return tokenizer(sample["text"], padding=False, max_length=MAX_SEQUENCE_LENGTH, truncation=True, add_special_tokens=False)
18ds = ds.map(tokenize, remove_columns=ds.column_names)1from llmcompressor.transformers import oneshot
2from llmcompressor.modifiers.quantization import GPTQModifier
3
4# Configure the quantization algorithm to run.
5recipe = GPTQModifier(targets="Linear", scheme="W4A16", ignore=["lm_head"], dampening_frac=0.1)
6
7# Apply quantization.
8oneshot(
9 model=model, dataset=ds,
10 recipe=recipe,
11 max_seq_length=MAX_SEQUENCE_LENGTH,
12 num_calibration_samples=NUM_CALIBRATION_SAMPLES,
13)
14
15# Save to disk compressed.
16SAVE_DIR = "models/" + MODEL_ID.split("/")[1] + "-GPTQ-INT4"
17model.save_pretrained(SAVE_DIR, max_shard_size="4GB")
18tokenizer.save_pretrained(SAVE_DIR)| Category | Gemma-2-27B | Qwen-2.5-32B | Llama-3.3-70B | Gpt4o-mini |
|---|---|---|---|---|
| Mistral is better | 0.536 | 0.496 | 0.192 | 0.200 |
| Mistral is slightly better | 0.196 | 0.184 | 0.164 | 0.204 |
| Ties | 0.052 | 0.060 | 0.236 | 0.160 |
| Other is slightly better | 0.060 | 0.088 | 0.112 | 0.124 |
| Other is better | 0.156 | 0.172 | 0.296 | 0.312 |
| Evaluation | mistral-small-24B-instruct-2501 | gemma-2b-27b | llama-3.3-70b | qwen2.5-32b | gpt-4o-mini-2024-07-18 |
|---|---|---|---|---|---|
| mmlu_pro_5shot_cot_instruct | 0.663 | 0.536 | 0.666 | 0.683 | 0.617 |
| gpqa_main_cot_5shot_instruct | 0.453 | 0.344 | 0.531 | 0.404 | 0.377 |
| Evaluation | mistral-small-24B-instruct-2501 | gemma-2b-27b | llama-3.3-70b | qwen2.5-32b | gpt-4o-mini-2024-07-18 |
|---|---|---|---|---|---|
| humaneval_instruct_pass@1 | 0.848 | 0.732 | 0.854 | 0.909 | 0.890 |
| math_instruct | 0.706 | 0.535 | 0.743 | 0.819 | 0.761 |
| Evaluation | mistral-small-24B-instruct-2501 | gemma-2b-27b | llama-3.3-70b | qwen2.5-32b | gpt-4o-mini-2024-07-18 |
|---|---|---|---|---|---|
| mtbench_dev | 8.35 | 7.86 | 7.96 | 8.26 | 8.33 |
| wildbench | 52.27 | 48.21 | 50.04 | 52.73 | 56.13 |
| arena_hard | 0.873 | 0.788 | 0.840 | 0.860 | 0.897 |
| ifeval | 0.829 | 0.8065 | 0.8835 | 0.8401 | 0.8499 |
<s>[SYSTEM_PROMPT]<system prompt>[/SYSTEM_PROMPT][INST]<user message>[/INST]<assistant response></s>[INST]<user message>[/INST]<system_prompt>, <user message> and <assistant response> are placeholders.vllm: See heretransformers: See heretemperature=0.15.system_prompt = """You are Mistral Small 3, a Large Language Model (LLM) created by Mistral AI, a French startup headquartered in Paris.
Your knowledge base was last updated on 2023-10-01. The current date is 2025-01-30.
When you're not sure about some information, you say that you don't have the information and don't make up anything.
If the user's question is not clear, ambiguous, or does not provide enough context for you to accurately answer the question, you do not try to answer it right away and you rather ask the user to clarify their request (e.g. \"What are some good restaurants around me?\" => \"Where are you?\" or \"When is the next flight to Tokyo\" => \"Where do you travel from?\")"""vLLM >= 0.6.4:pip install --upgrade vllmmistral_common >= 1.5.2 installed:pip install --upgrade mistral_commonvllm serve mistralai/Mistral-Small-24B-Instruct-2501 --tokenizer_mode mistral --config_format mistral --load_format mistral --tool-call-parser mistral --enable-auto-tool-choice1import requests
2import json
3from datetime import datetime, timedelta
4
5url = "http://<your-server>:8000/v1/chat/completions"
6headers = {"Content-Type": "application/json", "Authorization": "Bearer token"}
7
8model = "mistralai/Mistral-Small-24B-Instruct-2501"
9
10messages = [
11 {
12 "role": "system",
13 "content": "You are a conversational agent that always answers straight to the point, always end your accurate response with an ASCII drawing of a cat."
14 },
15 {
16 "role": "user",
17 "content": "Give me 5 non-formal ways to say 'See you later' in French."
18 },
19]
20
21data = {"model": model, "messages": messages}
22
23response = requests.post(url, headers=headers, data=json.dumps(data))
24print(response.json()["choices"][0]["message"]["content"])
25
26# Sure, here are five non-formal ways to say "See you later" in French:
27#
28# 1. À plus tard
29# 2. À plus
30# 3. Salut
31# 4. À toute
32# 5. Bisous
33#
34# ```
35# /\_/\
36# ( o.o )
37# > ^ <
38# ```1import requests
2import json
3from huggingface_hub import hf_hub_download
4from datetime import datetime, timedelta
5
6url = "http://<your-url>:8000/v1/chat/completions"
7headers = {"Content-Type": "application/json", "Authorization": "Bearer token"}
8
9model = "mistralai/Mistral-Small-24B-Instruct-2501"
10
11
12def load_system_prompt(repo_id: str, filename: str) -> str:
13 file_path = hf_hub_download(repo_id=repo_id, filename=filename)
14 with open(file_path, "r") as file:
15 system_prompt = file.read()
16 today = datetime.today().strftime("%Y-%m-%d")
17 yesterday = (datetime.today() - timedelta(days=1)).strftime("%Y-%m-%d")
18 model_name = repo_id.split("/")[-1]
19 return system_prompt.format(name=model_name, today=today, yesterday=yesterday)
20
21
22SYSTEM_PROMPT = load_system_prompt(model, "SYSTEM_PROMPT.txt")
23
24
25tools = [
26 {
27 "type": "function",
28 "function": {
29 "name": "get_current_weather",
30 "description": "Get the current weather in a given location",
31 "parameters": {
32 "type": "object",
33 "properties": {
34 "city": {
35 "type": "string",
36 "description": "The city to find the weather for, e.g. 'San Francisco'",
37 },
38 "state": {
39 "type": "string",
40 "description": "The state abbreviation, e.g. 'CA' for California",
41 },
42 "unit": {
43 "type": "string",
44 "description": "The unit for temperature",
45 "enum": ["celsius", "fahrenheit"],
46 },
47 },
48 "required": ["city", "state", "unit"],
49 },
50 },
51 },
52 {
53 "type": "function",
54 "function": {
55 "name": "rewrite",
56 "description": "Rewrite a given text for improved clarity",
57 "parameters": {
58 "type": "object",
59 "properties": {
60 "text": {
61 "type": "string",
62 "description": "The input text to rewrite",
63 }
64 },
65 },
66 },
67 },
68]
69
70messages = [
71 {"role": "system", "content": SYSTEM_PROMPT},
72 {
73 "role": "user",
74 "content": "Could you please make the below article more concise?\n\nOpenAI is an artificial intelligence research laboratory consisting of the non-profit OpenAI Incorporated and its for-profit subsidiary corporation OpenAI Limited Partnership.",
75 },
76 {
77 "role": "assistant",
78 "content": "",
79 "tool_calls": [
80 {
81 "id": "bbc5b7ede",
82 "type": "function",
83 "function": {
84 "name": "rewrite",
85 "arguments": '{"text": "OpenAI is an artificial intelligence research laboratory consisting of the non-profit OpenAI Incorporated and its for-profit subsidiary corporation OpenAI Limited Partnership."}',
86 },
87 }
88 ],
89 },
90 {
91 "role": "tool",
92 "content": '{"action":"rewrite","outcome":"OpenAI is a FOR-profit company."}',
93 "tool_call_id": "bbc5b7ede",
94 "name": "rewrite",
95 },
96 {
97 "role": "assistant",
98 "content": "---\n\nOpenAI is a FOR-profit company.",
99 },
100 {
101 "role": "user",
102 "content": "Can you tell me what the temperature will be in Dallas, in Fahrenheit?",
103 },
104]
105
106data = {"model": model, "messages": messages, "tools": tools}
107
108response = requests.post(url, headers=headers, data=json.dumps(data))
109import ipdb; ipdb.set_trace()
110print(response.json()["choices"][0]["message"]["tool_calls"])
111# [{'id': '8PdihwL6d', 'type': 'function', 'function': {'name': 'get_current_weather', 'arguments': '{"city": "Dallas", "state": "TX", "unit": "fahrenheit"}'}}]1from vllm import LLM
2from vllm.sampling_params import SamplingParams
3from datetime import datetime, timedelta
4
5SYSTEM_PROMPT = "You are a conversational agent that always answers straight to the point, always end your accurate response with an ASCII drawing of a cat."
6
7user_prompt = "Give me 5 non-formal ways to say 'See you later' in French."
8
9messages = [
10 {
11 "role": "system",
12 "content": SYSTEM_PROMPT
13 },
14 {
15 "role": "user",
16 "content": user_prompt
17 },
18]
19
20# note that running this model on GPU requires over 60 GB of GPU RAM
21llm = LLM(model=model_name, tokenizer_mode="mistral", tensor_parallel_size=8)
22
23sampling_params = SamplingParams(max_tokens=512, temperature=0.15)
24outputs = llm.chat(messages, sampling_params=sampling_params)
25
26print(outputs[0].outputs[0].text)
27# Sure, here are five non-formal ways to say "See you later" in French:
28#
29# 1. À plus tard
30# 2. À plus
31# 3. Salut
32# 4. À toute
33# 5. Bisous
34#
35# ```
36# /\_/\
37# ( o.o )
38# > ^ <
39# ```1from transformers import pipeline
2import torch
3
4messages = [
5 {"role": "user", "content": "Give me 5 non-formal ways to say 'See you later' in French."},
6]
7chatbot = pipeline("text-generation", model="mistralai/Mistral-Small-24B-Instruct-2501", max_new_tokens=256, torch_dtype=torch.bfloat16)
8chatbot(messages)ollama run mistral-smallollama run mistral-small:24b-instruct-2501-q4_K_Mollama run mistral-small:24b-instruct-2501-q8_0ollama run mistral-small:24b-instruct-2501-fp16