jerryzh168 commited on
Commit
8004dfc
·
verified ·
1 Parent(s): d683295

Update README.md

Browse files
Files changed (1) hide show
  1. README.md +340 -179
README.md CHANGED
@@ -1,199 +1,360 @@
1
  ---
2
  library_name: transformers
3
- tags: []
 
 
 
 
 
 
 
 
 
 
 
 
4
  ---
5
 
6
- # Model Card for Model ID
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
 
8
- <!-- Provide a quick summary of what the model is/does. -->
 
 
 
9
 
 
10
 
 
11
 
12
- ## Model Details
13
 
14
- ### Model Description
 
 
15
 
16
- <!-- Provide a longer summary of what this model is. -->
17
 
18
- This is the model card of a 🤗 transformers model that has been pushed on the Hub. This model card has been automatically generated.
19
 
20
- - **Developed by:** [More Information Needed]
21
- - **Funded by [optional]:** [More Information Needed]
22
- - **Shared by [optional]:** [More Information Needed]
23
- - **Model type:** [More Information Needed]
24
- - **Language(s) (NLP):** [More Information Needed]
25
- - **License:** [More Information Needed]
26
- - **Finetuned from model [optional]:** [More Information Needed]
27
 
28
- ### Model Sources [optional]
29
 
30
- <!-- Provide the basic links for the model. -->
 
 
 
 
31
 
32
- - **Repository:** [More Information Needed]
33
- - **Paper [optional]:** [More Information Needed]
34
- - **Demo [optional]:** [More Information Needed]
 
35
 
36
- ## Uses
 
 
 
 
37
 
38
- <!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
 
 
 
39
 
40
- ### Direct Use
41
 
42
- <!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->
 
43
 
44
- [More Information Needed]
45
-
46
- ### Downstream Use [optional]
47
-
48
- <!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->
49
-
50
- [More Information Needed]
51
-
52
- ### Out-of-Scope Use
53
-
54
- <!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
55
-
56
- [More Information Needed]
57
-
58
- ## Bias, Risks, and Limitations
59
-
60
- <!-- This section is meant to convey both technical and sociotechnical limitations. -->
61
-
62
- [More Information Needed]
63
-
64
- ### Recommendations
65
-
66
- <!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->
67
-
68
- Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.
69
-
70
- ## How to Get Started with the Model
71
-
72
- Use the code below to get started with the model.
73
-
74
- [More Information Needed]
75
-
76
- ## Training Details
77
-
78
- ### Training Data
79
-
80
- <!-- This should link to a Dataset Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->
81
-
82
- [More Information Needed]
83
-
84
- ### Training Procedure
85
-
86
- <!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
87
-
88
- #### Preprocessing [optional]
89
-
90
- [More Information Needed]
91
-
92
-
93
- #### Training Hyperparameters
94
-
95
- - **Training regime:** [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->
96
-
97
- #### Speeds, Sizes, Times [optional]
98
-
99
- <!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. -->
100
-
101
- [More Information Needed]
102
-
103
- ## Evaluation
104
-
105
- <!-- This section describes the evaluation protocols and provides the results. -->
106
-
107
- ### Testing Data, Factors & Metrics
108
-
109
- #### Testing Data
110
-
111
- <!-- This should link to a Dataset Card if possible. -->
112
-
113
- [More Information Needed]
114
-
115
- #### Factors
116
-
117
- <!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->
118
-
119
- [More Information Needed]
120
-
121
- #### Metrics
122
-
123
- <!-- These are the evaluation metrics being used, ideally with a description of why. -->
124
-
125
- [More Information Needed]
126
-
127
- ### Results
128
-
129
- [More Information Needed]
130
-
131
- #### Summary
132
-
133
-
134
-
135
- ## Model Examination [optional]
136
-
137
- <!-- Relevant interpretability work for the model goes here -->
138
-
139
- [More Information Needed]
140
-
141
- ## Environmental Impact
142
-
143
- <!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->
144
-
145
- Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).
146
-
147
- - **Hardware Type:** [More Information Needed]
148
- - **Hours used:** [More Information Needed]
149
- - **Cloud Provider:** [More Information Needed]
150
- - **Compute Region:** [More Information Needed]
151
- - **Carbon Emitted:** [More Information Needed]
152
-
153
- ## Technical Specifications [optional]
154
-
155
- ### Model Architecture and Objective
156
-
157
- [More Information Needed]
158
-
159
- ### Compute Infrastructure
160
-
161
- [More Information Needed]
162
-
163
- #### Hardware
164
-
165
- [More Information Needed]
166
-
167
- #### Software
168
-
169
- [More Information Needed]
170
-
171
- ## Citation [optional]
172
-
173
- <!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
174
-
175
- **BibTeX:**
176
-
177
- [More Information Needed]
178
-
179
- **APA:**
180
-
181
- [More Information Needed]
182
-
183
- ## Glossary [optional]
184
-
185
- <!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->
186
-
187
- [More Information Needed]
188
-
189
- ## More Information [optional]
190
-
191
- [More Information Needed]
192
-
193
- ## Model Card Authors [optional]
194
-
195
- [More Information Needed]
196
-
197
- ## Model Card Contact
198
-
199
- [More Information Needed]
 
1
  ---
2
  library_name: transformers
3
+ tags:
4
+ - torchao
5
+ - code
6
+ - math
7
+ - chat
8
+ - conversational
9
+ language:
10
+ - multilingual
11
+ license: apache-2.0
12
+ license_link: https://huggingface.co/Qwen/Qwen3-8B/blob/main/LICENSE
13
+ pipeline_tag: text-generation
14
+ base_model:
15
+ - Qwen/Qwen3-8B
16
  ---
17
 
18
+ [Qwen3-8B](https://huggingface.co/Qwen/Qwen3-8B) quantized with [torchao](https://huggingface.co/docs/transformers/main/en/quantization/torchao) int4 weight only quantization, using [hqq](https://mobiusml.github.io/hqq_blog/) algorithm for improved accuracy, by PyTorch team.
19
+ (UPDATE) Use it directly or serve using [vLLM](https://docs.vllm.ai/en/latest/) for 67% VRAM reduction and 12-20% speedup on A100 GPUs.
20
+
21
+ # Inference with vLLM
22
+ Install vllm nightly and torchao nightly to get some recent changes:
23
+ ```
24
+ pip install vllm --pre --extra-index-url https://wheels.vllm.ai/nightly
25
+ pip install torchao
26
+ ```
27
+
28
+ ## Code Example
29
+ ```Py
30
+ from vllm import LLM, SamplingParams
31
+
32
+ # Sample prompts.
33
+ prompts = [
34
+ "Hello, my name is",
35
+ "The president of the United States is",
36
+ "The capital of France is",
37
+ "The future of AI is",
38
+ ]
39
+ # Create a sampling params object.
40
+ sampling_params = SamplingParams(temperature=0.8, top_p=0.95)
41
+
42
+
43
+ if __name__ == '__main__':
44
+ # Create an LLM.
45
+ llm = LLM(model="pytorch/Phi-4-mini-instruct-int4wo-hqq")
46
+ # Generate texts from the prompts.
47
+ # The output is a list of RequestOutput objects
48
+ # that contain the prompt, generated text, and other information.
49
+ outputs = llm.generate(prompts, sampling_params)
50
+ # Print the outputs.
51
+ print("\nGenerated Outputs:\n" + "-" * 60)
52
+ for output in outputs:
53
+ prompt = output.prompt
54
+ generated_text = output.outputs[0].text
55
+ print(f"Prompt: {prompt!r}")
56
+ print(f"Output: {generated_text!r}")
57
+ print("-" * 60)
58
+ ```
59
+
60
+ Note: please use `VLLM_DISABLE_COMPILE_CACHE=1` to disable compile cache when running this code, e.g. `VLLM_DISABLE_COMPILE_CACHE=1 python example.py`, since there are some issues with the composability of compile in vLLM and torchao,
61
+ this is expected be resolved in pytorch 2.8.
62
+
63
+ ## Serving
64
+ Then we can serve with the following command:
65
+ ```Shell
66
+ vllm serve pytorch/Phi-4-mini-instruct-int4wo-hqq --tokenizer microsoft/Phi-4-mini-instruct -O3
67
+ ```
68
+
69
+
70
+ # Inference with Transformers
71
+
72
+ Install the required packages:
73
+ ```Shell
74
+ pip install git+https://github.com/huggingface/transformers@main
75
+ pip install --pre torchao --index-url https://download.pytorch.org/whl/nightly/cu126
76
+ pip install torch
77
+ pip install accelerate
78
+ ```
79
+
80
+ Example:
81
+ ```Py
82
+ import torch
83
+ from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
84
+
85
+ torch.random.manual_seed(0)
86
+
87
+ model_path = "pytorch/Phi-4-mini-instruct-int4wo-hqq"
88
+
89
+ model = AutoModelForCausalLM.from_pretrained(
90
+ model_path,
91
+ device_map="auto",
92
+ torch_dtype="auto",
93
+ trust_remote_code=True,
94
+ )
95
+ tokenizer = AutoTokenizer.from_pretrained(model_path)
96
+
97
+ messages = [
98
+ {"role": "system", "content": "You are a helpful AI assistant."},
99
+ {"role": "user", "content": "Can you provide ways to eat combinations of bananas and dragonfruits?"},
100
+ {"role": "assistant", "content": "Sure! Here are some ways to eat bananas and dragonfruits together: 1. Banana and dragonfruit smoothie: Blend bananas and dragonfruits together with some milk and honey. 2. Banana and dragonfruit salad: Mix sliced bananas and dragonfruits together with some lemon juice and honey."},
101
+ {"role": "user", "content": "What about solving an 2x + 3 = 7 equation?"},
102
+ ]
103
+
104
+ pipe = pipeline(
105
+ "text-generation",
106
+ model=model,
107
+ tokenizer=tokenizer,
108
+ )
109
+
110
+ generation_args = {
111
+ "max_new_tokens": 500,
112
+ "return_full_text": False,
113
+ "temperature": 0.0,
114
+ "do_sample": False,
115
+ }
116
+
117
+ output = pipe(messages, **generation_args)
118
+ print(output[0]['generated_text'])
119
+ ```
120
+
121
+ # Quantization Recipe
122
+
123
+ Install the required packages:
124
+ ```Shell
125
+ pip install git+https://github.com/huggingface/transformers@main
126
+ pip install --pre torchao --index-url https://download.pytorch.org/whl/nightly/cu126
127
+ pip install torch
128
+ pip install accelerate
129
+ ```
130
+
131
+ Use the following code to get the quantized model:
132
+ ```Py
133
+ import torch
134
+ from transformers import AutoModelForCausalLM, AutoTokenizer, TorchAoConfig
135
+
136
+ model_id = "microsoft/Phi-4-mini-instruct"
137
+
138
+ from torchao.quantization import Int4WeightOnlyConfig
139
+ quant_config = Int4WeightOnlyConfig(group_size=128, use_hqq=True)
140
+ quantization_config = TorchAoConfig(quant_type=quant_config)
141
+ quantized_model = AutoModelForCausalLM.from_pretrained(model_id, device_map="auto", torch_dtype=torch.bfloat16, quantization_config=quantization_config)
142
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
143
+
144
+ # Push to hub
145
+ USER_ID = "YOUR_USER_ID"
146
+ MODEL_NAME = model_id.split("/")[-1]
147
+ save_to = f"{USER_ID}/{MODEL_NAME}-int4wo-hqq"
148
+ quantized_model.push_to_hub(save_to, safe_serialization=False)
149
+ tokenizer.push_to_hub(save_to)
150
+
151
+ # Manual Testing
152
+ prompt = "Hey, are you conscious? Can you talk to me?"
153
+ messages = [
154
+ {
155
+ "role": "system",
156
+ "content": "",
157
+ },
158
+ {"role": "user", "content": prompt},
159
+ ]
160
+ templated_prompt = tokenizer.apply_chat_template(
161
+ messages,
162
+ tokenize=False,
163
+ add_generation_prompt=True,
164
+ )
165
+ print("Prompt:", prompt)
166
+ print("Templated prompt:", templated_prompt)
167
+ inputs = tokenizer(
168
+ templated_prompt,
169
+ return_tensors="pt",
170
+ ).to("cuda")
171
+ generated_ids = quantized_model.generate(**inputs, max_new_tokens=128)
172
+ output_text = tokenizer.batch_decode(
173
+ generated_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False
174
+ )
175
+ print("Response:", output_text[0][len(prompt):])
176
+ ```
177
+
178
+ Note: to `push_to_hub` you need to run
179
+ ```Shell
180
+ pip install -U "huggingface_hub[cli]"
181
+ huggingface-cli login
182
+ ```
183
+ and use a token with write access, from https://huggingface.co/settings/tokens
184
+
185
+ # Model Quality
186
+ We rely on [lm-evaluation-harness](https://github.com/EleutherAI/lm-evaluation-harness) to evaluate the quality of the quantized model.
187
+
188
+ Need to install lm-eval from source:
189
+ https://github.com/EleutherAI/lm-evaluation-harness#install
190
+
191
+ ## baseline
192
+ ```Shell
193
+ lm_eval --model hf --model_args pretrained=microsoft/Phi-4-mini-instruct --tasks hellaswag --device cuda:0 --batch_size 8
194
+ ```
195
+
196
+ ## int4 weight only quantization with hqq (int4wo-hqq)
197
+ ```Shell
198
+ lm_eval --model hf --model_args pretrained=pytorch/Phi-4-mini-instruct-int4wo-hqq --tasks hellaswag --device cuda:0 --batch_size 8
199
+ ```
200
+
201
+ | Benchmark | | |
202
+ |----------------------------------|----------------|---------------------------|
203
+ | | Phi-4-mini-ins | Phi-4-mini-ins-int4wo-hqq |
204
+ | **Popular aggregated benchmark** | | |
205
+ | mmlu (0-shot) | 66.73 | 63.56 |
206
+ | mmlu_pro (5-shot) | 46.43 | 36.74 |
207
+ | **Reasoning** | | |
208
+ | arc_challenge (0-shot) | 56.91 | 54.86 |
209
+ | gpqa_main_zeroshot | 30.13 | 30.58 |
210
+ | HellaSwag | 54.57 | 53.54 |
211
+ | openbookqa | 33.00 | 34.40 |
212
+ | piqa (0-shot) | 77.64 | 76.33 |
213
+ | social_iqa | 49.59 | 47.90 |
214
+ | truthfulqa_mc2 (0-shot) | 48.39 | 46.44 |
215
+ | winogrande (0-shot) | 71.11 | 71.51 |
216
+ | **Multilingual** | | |
217
+ | mgsm_en_cot_en | 60.8 | 59.6 |
218
+ | **Math** | | |
219
+ | gsm8k (5-shot) | 81.88 | 74.37 |
220
+ | mathqa (0-shot) | 42.31 | 42.75 |
221
+ | **Overall** | **55.35** | **53.28** |
222
+
223
+
224
+ # Peak Memory Usage
225
+
226
+ ## Results
227
+
228
+ | Benchmark | | |
229
+ |------------------|----------------|--------------------------------|
230
+ | | Phi-4 mini-Ins | Phi-4-mini-instruct-int4wo-hqq |
231
+ | Peak Memory (GB) | 8.91 | 2.98 (67% reduction) |
232
+
233
+
234
+ ## Code Example
235
+
236
+ We can use the following code to get a sense of peak memory usage during inference:
237
+
238
+ ```Py
239
+ import torch
240
+ from transformers import AutoModelForCausalLM, AutoTokenizer, TorchAoConfig
241
+
242
+ # use "microsoft/Phi-4-mini-instruct" or "pytorch/Phi-4-mini-instruct-int4wo-hqq"
243
+ model_id = "pytorch/Phi-4-mini-instruct-int4wo-hqq"
244
+ quantized_model = AutoModelForCausalLM.from_pretrained(model_id, device_map="auto", torch_dtype=torch.bfloat16)
245
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
246
+
247
+ torch.cuda.reset_peak_memory_stats()
248
+
249
+ prompt = "Hey, are you conscious? Can you talk to me?"
250
+ messages = [
251
+ {
252
+ "role": "system",
253
+ "content": "",
254
+ },
255
+ {"role": "user", "content": prompt},
256
+ ]
257
+ templated_prompt = tokenizer.apply_chat_template(
258
+ messages,
259
+ tokenize=False,
260
+ add_generation_prompt=True,
261
+ )
262
+ print("Prompt:", prompt)
263
+ print("Templated prompt:", templated_prompt)
264
+ inputs = tokenizer(
265
+ templated_prompt,
266
+ return_tensors="pt",
267
+ ).to("cuda")
268
+ generated_ids = quantized_model.generate(**inputs, max_new_tokens=128)
269
+ output_text = tokenizer.batch_decode(
270
+ generated_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False
271
+ )
272
+ print("Response:", output_text[0][len(prompt):])
273
+
274
+ mem = torch.cuda.max_memory_reserved() / 1e9
275
+ print(f"Peak Memory Usage: {mem:.02f} GB")
276
+ ```
277
+
278
+ # Model Performance
279
+
280
+ Our int4wo is only optimized for batch size 1, so expect some slowdown with larger batch sizes, we expect this to be used in local server deployment for single or a few users where the decode tokens per second will matters more than the time to first token.
281
+
282
+ ## Results (A100 machine)
283
+ | Benchmark (Latency) | | |
284
+ |----------------------------------|----------------|--------------------------|
285
+ | | Phi-4 mini-Ins | phi4-mini-int4wo-hqq |
286
+ | latency (batch_size=1) | 2.46s | 2.2s (12% speedup) |
287
+ | serving (num_prompts=1) | 0.87 req/s | 1.05 req/s (20% speedup) |
288
+
289
+ Note the result of latency (benchmark_latency) is in seconds, and serving (benchmark_serving) is in number of requests per second.
290
+ Int4 weight only is optimized for batch size 1 and short input and output token length, please stay tuned for models optimized for larger batch sizes or longer token length.
291
+
292
+ ## Setup
293
+
294
+ Get vllm source code:
295
+ ```Shell
296
+ git clone [email protected]:vllm-project/vllm.git
297
+ ```
298
+
299
+ Install vllm
300
+ ```
301
+ VLLM_USE_PRECOMPILED=1 pip install --editable .
302
+ ```
303
+
304
+ Run the benchmarks under `vllm` root folder:
305
+
306
+ ## benchmark_latency
307
+
308
+ ### baseline
309
+ ```Shell
310
+ python benchmarks/benchmark_latency.py --input-len 256 --output-len 256 --model microsoft/Phi-4-mini-instruct --batch-size 1
311
+ ```
312
 
313
+ ### int4wo-hqq
314
+ ```Shell
315
+ VLLM_DISABLE_COMPILE_CACHE=1 python benchmarks/benchmark_latency.py --input-len 256 --output-len 256 --model pytorch/Phi-4-mini-instruct-int4wo-hqq --batch-size 1
316
+ ```
317
 
318
+ ## benchmark_serving
319
 
320
+ We benchmarked the throughput in a serving environment.
321
 
322
+ Download sharegpt dataset:
323
 
324
+ ```Shell
325
+ wget https://huggingface.co/datasets/anon8231489123/ShareGPT_Vicuna_unfiltered/resolve/main/ShareGPT_V3_unfiltered_cleaned_split.json
326
+ ```
327
 
 
328
 
 
329
 
330
+ Other datasets can be found in: https://github.com/vllm-project/vllm/tree/main/benchmarks
 
 
 
 
 
 
331
 
332
+ Note: you can change the number of prompts to be benchmarked with `--num-prompts` argument for `benchmark_serving` script.
333
 
334
+ ### baseline
335
+ Server:
336
+ ```Shell
337
+ vllm serve microsoft/Phi-4-mini-instruct --tokenizer microsoft/Phi-4-mini-instruct -O3
338
+ ```
339
 
340
+ Client:
341
+ ```Shell
342
+ python benchmarks/benchmark_serving.py --backend vllm --dataset-name sharegpt --tokenizer microsoft/Phi-4-mini-instruct --dataset-path ./ShareGPT_V3_unfiltered_cleaned_split.json --model microsoft/Phi-4-mini-instruct --num-prompts 1
343
+ ```
344
 
345
+ ### int4wo-hqq
346
+ Server:
347
+ ```Shell
348
+ VLLM_DISABLE_COMPILE_CACHE=1 vllm serve pytorch/Phi-4-mini-instruct-int4wo-hqq --tokenizer microsoft/Phi-4-mini-instruct -O3 --pt-load-map-location cuda:0
349
+ ```
350
 
351
+ Client:
352
+ ```Shell
353
+ python benchmarks/benchmark_serving.py --backend vllm --dataset-name sharegpt --tokenizer microsoft/Phi-4-mini-instruct --dataset-path ./ShareGPT_V3_unfiltered_cleaned_split.json --model pytorch/Phi-4-mini-instruct-int4wo-hqq --num-prompts 1
354
+ ```
355
 
 
356
 
357
+ # Disclaimer
358
+ PyTorch has not performed safety evaluations or red teamed the quantized models. Performance characteristics, outputs, and behaviors may differ from the original models. Users are solely responsible for selecting appropriate use cases, evaluating and mitigating for accuracy, safety, and fairness, ensuring security, and complying with all applicable laws and regulations.
359
 
360
+ Nothing contained in this Model Card should be interpreted as or deemed a restriction or modification to the licenses the models are released under, including any limitations of liability or disclaimers of warranties provided therein.