jerryzh168 commited on
Commit
201128c
·
verified ·
1 Parent(s): 2a29c86

Upload README.md with huggingface_hub

Browse files
Files changed (1) hide show
  1. README.md +292 -158
README.md CHANGED
@@ -1,199 +1,333 @@
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-4B
3
+ tags:
4
+ - transformers
5
+ - torchao
6
+ - qwen3
7
+ license: apache-2.0
8
+ language:
9
+ - en
10
  ---
11
 
12
+ # INT4 Qwen/Qwen3-4B model
13
+
14
+ - **Developed by:** jerryzh168
15
+ - **License:** apache-2.0
16
+ - **Quantized from Model :** Qwen/Qwen3-4B
17
+ - **Quantization Method :** INT4
18
+
19
+
20
+ # Inference with vLLM
21
+ Install vllm nightly and torchao nightly to get some recent changes:
22
+ ```
23
+ pip install vllm --pre --extra-index-url https://wheels.vllm.ai/nightly
24
+ pip install torchao
25
+ ```
26
+
27
+ ## Serving
28
+ Then we can serve with the following command:
29
+ ```Shell
30
+ # Server
31
+ export MODEL=jerryzh168/Qwen3-4B-INT4
32
+ VLLM_DISABLE_COMPILE_CACHE=1 vllm serve $MODEL --tokenizer $MODEL -O3
33
+ ```
34
+
35
+ ```Shell
36
+ # Client
37
+ curl http://localhost:8000/v1/chat/completions -H "Content-Type: application/json" -d '{
38
+ "model": "jerryzh168/Qwen3-4B-INT4",
39
+ "messages": [
40
+ {"role": "user", "content": "Give me a short introduction to large language models."}
41
+ ],
42
+ "temperature": 0.6,
43
+ "top_p": 0.95,
44
+ "top_k": 20,
45
+ "max_tokens": 32768
46
+ }'
47
+ ```
48
+
49
+ 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,
50
+ this is expected be resolved in pytorch 2.8.
51
+
52
+ # Inference with Transformers
53
+
54
+ Install the required packages:
55
+ ```Shell
56
+ pip install git+https://github.com/huggingface/transformers@main
57
+ pip install torchao
58
+ pip install torch
59
+ pip install accelerate
60
+ ```
61
+
62
+ Example:
63
+ ```Py
64
+ import torch
65
+ from transformers import AutoModelForCausalLM, AutoTokenizer
66
+
67
+ model_name = "jerryzh168/Qwen3-4B-INT4"
68
+
69
+ # load the tokenizer and the model
70
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
71
+ model = AutoModelForCausalLM.from_pretrained(
72
+ model_name,
73
+ torch_dtype="auto",
74
+ device_map="auto"
75
+ )
76
+
77
+ # prepare the model input
78
+ prompt = "Give me a short introduction to large language model."
79
+ messages = [
80
+ {"role": "user", "content": prompt}
81
+ ]
82
+ text = tokenizer.apply_chat_template(
83
+ messages,
84
+ tokenize=False,
85
+ add_generation_prompt=True,
86
+ enable_thinking=True # Switches between thinking and non-thinking modes. Default is True.
87
+ )
88
+ model_inputs = tokenizer([text], return_tensors="pt").to(model.device)
89
+
90
+ # conduct text completion
91
+ generated_ids = model.generate(
92
+ **model_inputs,
93
+ max_new_tokens=32768
94
+ )
95
+ output_ids = generated_ids[0][len(model_inputs.input_ids[0]):].tolist()
96
+
97
+ # parsing thinking content
98
+ try:
99
+ # rindex finding 151668 (</think>)
100
+ index = len(output_ids) - output_ids[::-1].index(151668)
101
+ except ValueError:
102
+ index = 0
103
+
104
+ thinking_content = tokenizer.decode(output_ids[:index], skip_special_tokens=True).strip("
105
+ ")
106
+ content = tokenizer.decode(output_ids[index:], skip_special_tokens=True).strip("
107
+ ")
108
+
109
+ print("thinking content:", thinking_content)
110
+ print("content:", content)
111
+ ```
112
+
113
+
114
+
115
+
116
+ # Quantization Recipe
117
+
118
+ Install the required packages:
119
+ ```Shell
120
+ pip install torch
121
+ pip install git+https://github.com/huggingface/transformers@main
122
+ pip install --pre torchao --index-url https://download.pytorch.org/whl/nightly/cu126
123
+ pip install accelerate
124
+ ```
125
+
126
+
127
+
128
+ Use the following code to get the quantized model:
129
+ ```Py
130
+ import torch
131
+ from transformers import AutoModelForCausalLM, AutoTokenizer, TorchAoConfig
132
+
133
+ model_id = "Qwen/Qwen3-4B"
134
+ model_to_quantize = "Qwen/Qwen3-4B"
135
+
136
+
137
+ from torchao.quantization import Int4WeightOnlyConfig
138
+ quant_config = Int4WeightOnlyConfig(group_size=128, int4_packing_format="tile_packed_to_4d", int4_choose_qparams_algorithm="hqq")
139
+ quantization_config = TorchAoConfig(quant_type=quant_config)
140
+ quantized_model = AutoModelForCausalLM.from_pretrained(model_to_quantize, device_map="auto", torch_dtype=torch.bfloat16, quantization_config=quantization_config)
141
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
142
+
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}-INT4"
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. Here we only run on mmlu for sanity check.
187
+
188
+ | Benchmark | | |
189
+ |----------------------------------|----------------|---------------------------|
190
+ | | Qwen/Qwen3-4B | jerryzh168/Qwen3-4B-INT4 |
191
+ | mmlu | To be filled | To be filled |
192
+
193
+
194
+ <details>
195
+ <summary> Reproduce Model Quality Results </summary>
196
 
197
+ Need to install lm-eval from source:
198
+ https://github.com/EleutherAI/lm-evaluation-harness#install
199
 
200
+ ## baseline
201
+ ```Shell
202
+ lm_eval --model hf --model_args pretrained=Qwen/Qwen3-4B --tasks mmlu --device cuda:0 --batch_size 8
203
+ ```
204
 
205
+ ## INT4
206
+ ```Shell
207
+ export MODEL=jerryzh168/Qwen3-4B-INT4
208
+ lm_eval --model hf --model_args pretrained=$MODEL --tasks mmlu --device cuda:0 --batch_size 8
209
+ ```
210
+ </details>
211
 
 
212
 
 
213
 
 
214
 
215
+ # Peak Memory Usage
216
+
217
+ ## Results
218
+
219
+ | Benchmark | | |
220
+ |------------------|----------------|--------------------------------|
221
+ | | Qwen/Qwen3-4B | jerryzh168/Qwen3-4B-INT4 |
222
+ | Peak Memory (GB) | To be filled | To be filled (?% reduction) |
223
+
224
 
 
 
 
 
 
 
 
225
 
226
+ <details>
227
+ <summary> Reproduce Peak Memory Usage Results </summary>
228
 
229
+ We can use the following code to get a sense of peak memory usage during inference:
230
 
231
+ ```Py
232
+ import torch
233
+ from transformers import AutoModelForCausalLM, AutoTokenizer, TorchAoConfig
234
 
235
+ # use "Qwen/Qwen3-4B" or "jerryzh168/Qwen3-4B-INT4"
236
+ model_id = "jerryzh168/Qwen3-4B-INT4"
237
+ quantized_model = AutoModelForCausalLM.from_pretrained(model_id, device_map="cuda:0", torch_dtype=torch.bfloat16)
238
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
239
 
240
+ torch.cuda.reset_peak_memory_stats()
241
 
242
+ prompt = "Hey, are you conscious? Can you talk to me?"
243
+ messages = [
244
+ {
245
+ "role": "system",
246
+ "content": "",
247
+ },
248
+ {"role": "user", "content": prompt},
249
+ ]
250
+ templated_prompt = tokenizer.apply_chat_template(
251
+ messages,
252
+ tokenize=False,
253
+ add_generation_prompt=True,
254
+ )
255
+ print("Prompt:", prompt)
256
+ print("Templated prompt:", templated_prompt)
257
+ inputs = tokenizer(
258
+ templated_prompt,
259
+ return_tensors="pt",
260
+ ).to("cuda")
261
+ generated_ids = quantized_model.generate(**inputs, max_new_tokens=128)
262
+ output_text = tokenizer.batch_decode(
263
+ generated_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False
264
+ )
265
+ print("Response:", output_text[0][len(prompt):])
266
 
267
+ mem = torch.cuda.max_memory_reserved() / 1e9
268
+ print(f"Peak Memory Usage: {mem:.02f} GB")
269
+ ```
270
 
271
+ </details>
272
 
 
273
 
 
274
 
 
275
 
276
+ # Model Performance
277
 
278
+ ## Results (A100 machine)
279
+ | Benchmark (Latency) | | |
280
+ |----------------------------------|----------------|--------------------------|
281
+ | | Qwen/Qwen3-4B | jerryzh168/Qwen3-4B-INT4 |
282
+ | latency (batch_size=1) | ?s | ?s (?x speedup) |
283
+ | latency (batch_size=256) | ?s | ?s (?x speedup) |
284
 
285
+ <details>
286
+ <summary> Reproduce Model Performance Results </summary>
287
 
288
+ ## Setup
289
 
290
+ Get vllm source code:
291
+ ```Shell
292
+ git clone [email protected]:vllm-project/vllm.git
293
+ ```
294
 
295
+ Install vllm
296
+ ```
297
+ VLLM_USE_PRECOMPILED=1 pip install --editable .
298
+ ```
299
 
300
+ Run the benchmarks under `vllm` root folder:
301
 
302
+ ## benchmark_latency
303
 
304
+ ### baseline
305
+ ```Shell
306
+ export MODEL=Qwen/Qwen3-4B
307
+ python benchmarks/benchmark_latency.py --input-len 256 --output-len 256 --model $MODEL --batch-size 1
308
+ ```
309
 
310
+ ### INT4
311
+ ```Shell
312
+ export MODEL=jerryzh168/Qwen3-4B-INT4
313
+ VLLM_DISABLE_COMPILE_CACHE=1 python benchmarks/benchmark_latency.py --input-len 256 --output-len 256 --model $MODEL --batch-size 1
314
+ ```
315
+ </details>
316
 
 
317
 
 
318
 
 
319
 
320
+ # Paper: TorchAO: PyTorch-Native Training-to-Serving Model Optimization
321
+ 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).
322
 
323
+ **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 .
324
 
325
+ # Resources
326
+ * **Official TorchAO GitHub Repository:** [https://github.com/pytorch/ao](https://github.com/pytorch/ao)
327
+ * **TorchAO Documentation:** [https://docs.pytorch.org/ao/stable/index.html](https://docs.pytorch.org/ao/stable/index.html)
328
 
 
329
 
330
+ # Disclaimer
331
+ 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.
332
 
333
+ 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.