jerryzh168 commited on
Commit
320a2cf
·
verified ·
1 Parent(s): d9d3993

Upload README.md with huggingface_hub

Browse files
Files changed (1) hide show
  1. README.md +326 -161
README.md CHANGED
@@ -1,199 +1,364 @@
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
+ base_model: Qwen/Qwen3-8B
3
+ tags:
4
+ - transformers
5
+ - torchao
6
+ - qwen3
7
+ license: apache-2.0
8
+ language:
9
+ - en
10
  ---
11
 
12
+ # INT4 Qwen/Qwen3-8B model
13
+
14
+ - **Developed by:** jerryzh168
15
+ - **License:** apache-2.0
16
+ - **Quantized from Model :** Qwen/Qwen3-8B
17
+ - **Quantization Method :** INT4
18
+
19
+ # Inference with vLLM
20
+ Install vllm nightly and torchao nightly to get some recent changes:
21
+ ```
22
+ pip install vllm --pre --extra-index-url https://wheels.vllm.ai/nightly
23
+ pip install torchao
24
+ ```
25
+
26
+ ## Serving
27
+ Then we can serve with the following command:
28
+ ```Shell
29
+ # Server
30
+ export MODEL=jerryzh168/Qwen3-8B-INT4
31
+ VLLM_DISABLE_COMPILE_CACHE=1 vllm serve $MODEL --tokenizer $MODEL -O3
32
+ ```
33
+
34
+ ```Shell
35
+ # Client
36
+ curl http://localhost:8000/v1/chat/completions -H "Content-Type: application/json" -d '{
37
+ "model": "jerryzh168/Qwen3-8B-INT4",
38
+ "messages": [
39
+ {"role": "user", "content": "Give me a short introduction to large language models."}
40
+ ],
41
+ "temperature": 0.6,
42
+ "top_p": 0.95,
43
+ "top_k": 20,
44
+ "max_tokens": 32768
45
+ }'
46
+ ```
47
+
48
+ 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,
49
+ this is expected be resolved in pytorch 2.8.
50
+
51
+ # Inference with Transformers
52
+
53
+ Install the required packages:
54
+ ```Shell
55
+ pip install git+https://github.com/huggingface/transformers@main
56
+ pip install torchao
57
+ pip install torch
58
+ pip install accelerate
59
+ ```
60
+
61
+ Example:
62
+ ```Py
63
+ import torch
64
+ from transformers import AutoModelForCausalLM, AutoTokenizer
65
+
66
+ model_name = "jerryzh168/Qwen3-8B-INT4"
67
+
68
+ # load the tokenizer and the model
69
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
70
+ model = AutoModelForCausalLM.from_pretrained(
71
+ model_name,
72
+ torch_dtype="auto",
73
+ device_map="auto"
74
+ )
75
+
76
+ # prepare the model input
77
+ prompt = "Give me a short introduction to large language model."
78
+ messages = [
79
+ {"role": "user", "content": prompt}
80
+ ]
81
+ text = tokenizer.apply_chat_template(
82
+ messages,
83
+ tokenize=False,
84
+ add_generation_prompt=True,
85
+ enable_thinking=True # Switches between thinking and non-thinking modes. Default is True.
86
+ )
87
+ model_inputs = tokenizer([text], return_tensors="pt").to(model.device)
88
+
89
+ # conduct text completion
90
+ generated_ids = model.generate(
91
+ **model_inputs,
92
+ max_new_tokens=32768
93
+ )
94
+ output_ids = generated_ids[0][len(model_inputs.input_ids[0]):].tolist()
95
+
96
+ # parsing thinking content
97
+ try:
98
+ # rindex finding 151668 (</think>)
99
+ index = len(output_ids) - output_ids[::-1].index(151668)
100
+ except ValueError:
101
+ index = 0
102
+
103
+ thinking_content = tokenizer.decode(output_ids[:index], skip_special_tokens=True).strip("
104
+ ")
105
+ content = tokenizer.decode(output_ids[index:], skip_special_tokens=True).strip("
106
+ ")
107
+
108
+ print("thinking content:", thinking_content)
109
+ print("content:", content)
110
+ ```
111
+
112
+ # Quantization Recipe
113
+
114
+ Install the required packages:
115
+ ```Shell
116
+ pip install git+https://github.com/huggingface/transformers@main
117
+ pip install --pre torchao --index-url https://download.pytorch.org/whl/nightly/cu126
118
+ pip install torch
119
+ pip install accelerate
120
+ ```
121
+
122
+
123
+ Use the following code to get the quantized model:
124
+ ```Py
125
+ import torch
126
+ from transformers import AutoModelForCausalLM, AutoTokenizer, TorchAoConfig
127
+
128
+ model_id = "Qwen/Qwen3-8B"
129
+ model_to_quantize = "Qwen/Qwen3-8B"
130
+
131
+
132
+ from torchao.quantization import Int4WeightOnlyConfig
133
+ quant_config = Int4WeightOnlyConfig(group_size=128, use_hqq=True)
134
+ quantization_config = TorchAoConfig(quant_type=quant_config)
135
+
136
+ quantized_model = AutoModelForCausalLM.from_pretrained(model_to_quantize, device_map="auto", torch_dtype=torch.bfloat16, quantization_config=quantization_config)
137
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
138
+
139
+ # Push to hub
140
+ USER_ID = "YOUR_USER_ID"
141
+ MODEL_NAME = model_id.split("/")[-1]
142
+ save_to = f"{USER_ID}/{MODEL_NAME}-INT4"
143
+ quantized_model.push_to_hub(save_to, safe_serialization=False)
144
+ tokenizer.push_to_hub(save_to)
145
+
146
+ # Manual Testing
147
+ prompt = "Hey, are you conscious? Can you talk to me?"
148
+ messages = [
149
+ {
150
+ "role": "system",
151
+ "content": "",
152
+ },
153
+ {"role": "user", "content": prompt},
154
+ ]
155
+ templated_prompt = tokenizer.apply_chat_template(
156
+ messages,
157
+ tokenize=False,
158
+ add_generation_prompt=True,
159
+ )
160
+ print("Prompt:", prompt)
161
+ print("Templated prompt:", templated_prompt)
162
+ inputs = tokenizer(
163
+ templated_prompt,
164
+ return_tensors="pt",
165
+ ).to("cuda")
166
+ generated_ids = quantized_model.generate(**inputs, max_new_tokens=128)
167
+ output_text = tokenizer.batch_decode(
168
+ generated_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False
169
+ )
170
+ print("Response:", output_text[0][len(prompt):])
171
+ ```
172
+
173
+ Note: to `push_to_hub` you need to run
174
+ ```Shell
175
+ pip install -U "huggingface_hub[cli]"
176
+ huggingface-cli login
177
+ ```
178
+ and use a token with write access, from https://huggingface.co/settings/tokens
179
+
180
+ # Model Quality
181
+ We rely on [lm-evaluation-harness](https://github.com/EleutherAI/lm-evaluation-harness) to evaluate the quality of the quantized model. Here we only run on mmlu for sanity check.
182
+
183
+ | Benchmark | | |
184
+ |----------------------------------|----------------|---------------------------|
185
+ | | Qwen/Qwen3-8B | jerryzh168/Qwen3-8B-INT4 |
186
+ | mmlu | To be filled | To be filled |
187
+
188
+
189
+ <details>
190
+ <summary> Reproduce Model Quality Results </summary>
191
+
192
+ Need to install lm-eval from source:
193
+ https://github.com/EleutherAI/lm-evaluation-harness#install
194
+
195
+ ## baseline
196
+ ```Shell
197
+ lm_eval --model hf --model_args pretrained=Qwen/Qwen3-8B --tasks mmlu --device cuda:0 --batch_size 8
198
+ ```
199
+
200
+ ## int4 weight only quantization with hqq (INT4)
201
+ ```Shell
202
+ export MODEL=jerryzh168/Qwen3-8B-INT4
203
+ lm_eval --model hf --model_args pretrained=$MODEL --tasks mmlu --device cuda:0 --batch_size 8
204
+ ```
205
+ </details>
206
+
207
+
208
+
209
+ # Peak Memory Usage
210
+
211
+ ## Results
212
+
213
+ | Benchmark | | |
214
+ |------------------|----------------|--------------------------------|
215
+ | | Qwen/Qwen3-8B | jerryzh168/Qwen3-8B-INT4 |
216
+ | Peak Memory (GB) | To be filled | To be filled (?% reduction) |
217
+
218
+
219
 
220
+ <details>
221
+ <summary> Reproduce Peak Memory Usage Results </summary>
222
 
223
+ We can use the following code to get a sense of peak memory usage during inference:
224
 
225
+ ```Py
226
+ import torch
227
+ from transformers import AutoModelForCausalLM, AutoTokenizer, TorchAoConfig
228
+
229
+ # use "Qwen/Qwen3-8B" or "jerryzh168/Qwen3-8B-INT4"
230
+ model_id = "jerryzh168/Qwen3-8B-INT4"
231
+ quantized_model = AutoModelForCausalLM.from_pretrained(model_id, device_map="auto", torch_dtype=torch.bfloat16)
232
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
233
+
234
+ torch.cuda.reset_peak_memory_stats()
235
+
236
+ prompt = "Hey, are you conscious? Can you talk to me?"
237
+ messages = [
238
+ {
239
+ "role": "system",
240
+ "content": "",
241
+ },
242
+ {"role": "user", "content": prompt},
243
+ ]
244
+ templated_prompt = tokenizer.apply_chat_template(
245
+ messages,
246
+ tokenize=False,
247
+ add_generation_prompt=True,
248
+ )
249
+ print("Prompt:", prompt)
250
+ print("Templated prompt:", templated_prompt)
251
+ inputs = tokenizer(
252
+ templated_prompt,
253
+ return_tensors="pt",
254
+ ).to("cuda")
255
+ generated_ids = quantized_model.generate(**inputs, max_new_tokens=128)
256
+ output_text = tokenizer.batch_decode(
257
+ generated_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False
258
+ )
259
+ print("Response:", output_text[0][len(prompt):])
260
 
261
+ mem = torch.cuda.max_memory_reserved() / 1e9
262
+ print(f"Peak Memory Usage: {mem:.02f} GB")
263
+ ```
264
 
265
+ </details>
266
 
 
267
 
 
268
 
269
+ # Model Performance
 
 
 
 
 
 
270
 
271
+ ## Results (A100 machine)
272
+ | Benchmark (Latency) | | |
273
+ |----------------------------------|----------------|--------------------------|
274
+ | | Qwen/Qwen3-8B | jerryzh168/Qwen3-8B-INT4 |
275
+ | latency (batch_size=1) | ?s | ?s (?x speedup) |
276
 
277
+ <details>
278
+ <summary> Reproduce Model Performance Results </summary>
279
 
280
+ ## Setup
 
 
281
 
282
+ Get vllm source code:
283
+ ```Shell
284
+ git clone [email protected]:vllm-project/vllm.git
285
+ ```
286
 
287
+ Install vllm
288
+ ```
289
+ VLLM_USE_PRECOMPILED=1 pip install --editable .
290
+ ```
291
 
292
+ Run the benchmarks under `vllm` root folder:
293
 
294
+ ## benchmark_latency
295
 
296
+ ### baseline
297
+ ```Shell
298
+ export MODEL=Qwen/Qwen3-8B
299
+ python benchmarks/benchmark_latency.py --input-len 256 --output-len 256 --model $MODEL --batch-size 1
300
+ ```
301
 
302
+ ### INT4
303
+ ```Shell
304
+ export MODEL=jerryzh168/Qwen3-8B-INT4
305
+ VLLM_DISABLE_COMPILE_CACHE=1 python benchmarks/benchmark_latency.py --input-len 256 --output-len 256 --model $MODEL --batch-size 1
306
+ ```
307
 
308
+ ## benchmark_serving
309
 
310
+ We benchmarked the throughput in a serving environment.
311
 
312
+ Download sharegpt dataset:
313
 
314
+ ```Shell
315
+ wget https://huggingface.co/datasets/anon8231489123/ShareGPT_Vicuna_unfiltered/resolve/main/ShareGPT_V3_unfiltered_cleaned_split.json
316
+ ```
317
 
 
318
 
 
319
 
320
+ Other datasets can be found in: https://github.com/vllm-project/vllm/tree/main/benchmarks
321
 
322
+ Note: you can change the number of prompts to be benchmarked with `--num-prompts` argument for `benchmark_serving` script.
323
 
324
+ ### baseline
325
+ Server:
326
+ ```Shell
327
+ export MODEL=Qwen/Qwen3-8B
328
+ vllm serve $MODEL --tokenizer $MODEL -O3
329
+ ```
330
 
331
+ Client:
332
+ ```Shell
333
+ export MODEL=Qwen/Qwen3-8B
334
+ python benchmarks/benchmark_serving.py --backend vllm --dataset-name sharegpt --tokenizer $MODEL --dataset-path ./ShareGPT_V3_unfiltered_cleaned_split.json --model $MODEL --num-prompts 1
335
+ ```
336
 
337
+ ### INT4
338
+ Server:
339
+ ```Shell
340
+ export MODEL=jerryzh168/Qwen3-8B-INT4
341
+ VLLM_DISABLE_COMPILE_CACHE=1 vllm serve $MODEL --tokenizer $MODEL -O3 --pt-load-map-location cuda:0
342
+ ```
343
 
344
+ Client:
345
+ ```Shell
346
+ export MODEL=jerryzh168/Qwen3-8B-INT4
347
+ python benchmarks/benchmark_serving.py --backend vllm --dataset-name sharegpt --tokenizer $MODEL --dataset-path ./ShareGPT_V3_unfiltered_cleaned_split.json --model $MODEL --num-prompts 1
348
+ ```
349
+ </details>
350
 
351
+ # Paper: TorchAO: PyTorch-Native Training-to-Serving Model Optimization
352
+ The model's quantization is powered by **TorchAO**, a framework presented in the paper [TorchAO: PyTorch-Native Training-to-Serving Model Optimization](https://huggingface.co/papers/2507.16099).
353
 
354
+ **Abstract:** We present TorchAO, a PyTorch-native model optimization framework leveraging quantization and sparsity to provide an end-to-end, training-to-serving workflow for AI models. TorchAO supports a variety of popular model optimization techniques, including FP8 quantized training, quantization-aware training (QAT), post-training quantization (PTQ), and 2:4 sparsity, and leverages a novel tensor subclass abstraction to represent a variety of widely-used, backend agnostic low precision data types, including INT4, INT8, FP8, MXFP4, MXFP6, and MXFP8. TorchAO integrates closely with the broader ecosystem at each step of the model optimization pipeline, from pre-training (TorchTitan) to fine-tuning (TorchTune, Axolotl) to serving (HuggingFace, vLLM, SGLang, ExecuTorch), connecting an otherwise fragmented space in a single, unified workflow. TorchAO has enabled recent launches of the quantized Llama 3.2 1B/3B and LlamaGuard3-8B models and is open-source at this https URL .
355
 
356
+ # Resources
357
+ * **Official TorchAO GitHub Repository:** [https://github.com/pytorch/ao](https://github.com/pytorch/ao)
358
+ * **TorchAO Documentation:** [https://docs.pytorch.org/ao/stable/index.html](https://docs.pytorch.org/ao/stable/index.html)
359
 
 
360
 
361
+ # Disclaimer
362
+ 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.
363
 
364
+ 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.