q10 commited on
Commit
3149ba3
·
verified ·
1 Parent(s): fce4abd

Upload README.md with huggingface_hub

Browse files
Files changed (1) hide show
  1. README.md +190 -154
README.md CHANGED
@@ -1,199 +1,235 @@
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-Base
3
+ tags:
4
+ - transformers
5
+ - torchao
6
+ - qwen3
7
+ license: apache-2.0
8
+ language:
9
+ - en
10
  ---
11
 
12
+ # INT8-INT4 Qwen/Qwen3-8B-Base model
13
 
14
+ - **Developed by:** q10
15
+ - **License:** apache-2.0
16
+ - **Quantized from Model :** Qwen/Qwen3-8B-Base
17
+ - **Quantization Method :** INT8-INT4
18
 
19
 
20
 
 
21
 
22
+ # Running in a mobile app
23
+ (TODO: pte file name generation)
24
+ The [pte file](https://huggingface.co/q10/Qwen3-8B-Base-INT8-INT4/blob/main/qwen3-4B-INT8-INT4-1024-cxt.pte) can be run with ExecuTorch on a mobile phone. See the [instructions](https://pytorch.org/executorch/main/llm/llama-demo-ios.html) for doing this in iOS.
25
+ On iPhone 15 Pro, the model runs at (to be filled) tokens/sec and uses (to be filled) Mb of memory.
26
 
27
+ TODO: attach image
28
 
 
29
 
30
+ # Quantization Recipe
 
 
 
 
 
 
31
 
32
+ Install the required packages:
33
+ ```Shell
34
+ pip install git+https://github.com/huggingface/transformers@main
35
+ pip install --pre torchao --index-url https://download.pytorch.org/whl/nightly/cu126
36
+ pip install torch
37
+ pip install accelerate
38
+ ```
39
+
40
+
41
+ ## Untie Embedding Weights
42
+ We want to quantize the embedding and lm_head differently. Since those layers are tied, we first need to untie the model:
43
+
44
+ ```Py
45
+ from transformers import (
46
+ AutoModelForCausalLM,
47
+ AutoProcessor,
48
+ AutoTokenizer,
49
+ )
50
+ import torch
51
+
52
+ model_id = "{base_model}"
53
+ untied_model = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype="auto", device_map="auto")
54
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
55
+
56
+ print(untied_model)
57
+ from transformers.modeling_utils import find_tied_parameters
58
+ print("tied weights:", find_tied_parameters(untied_model))
59
+ if getattr(untied_model.config.get_text_config(decoder=True), "tie_word_embeddings"):
60
+ setattr(untied_model.config.get_text_config(decoder=True), "tie_word_embeddings", False)
61
+
62
+ untied_model._tied_weights_keys = []
63
+ untied_model.lm_head.weight = torch.nn.Parameter(untied_model.lm_head.weight.clone())
64
+
65
+ print("tied weights:", find_tied_parameters(untied_model))
66
+
67
+ USER_ID = "YOUR_USER_ID"
68
+ MODEL_NAME = model_id.split("/")[-1]
69
+ save_to = f"{{USER_ID}}/{{MODEL_NAME}}-untied-weights"
70
+
71
+ # save locally (we use this in the recipe)
72
+ save_to_local_path = f"{{MODEL_NAME}}-untied-weights"
73
+ untied_model.save_pretrained(save_to_local_path)
74
+ tokenizer.save_pretrained(save_to_local_path)
75
+
76
+
77
+ # or push to hub
78
+ untied_model.push_to_hub(save_to)
79
+ tokenizer.push_to_hub(save_to)
80
+ ```
81
+
82
+ Note: to `push_to_hub` you need to run
83
+ ```Shell
84
+ pip install -U "huggingface_hub[cli]"
85
+ huggingface-cli login
86
+ ```
87
+ and use a token with write access, from https://huggingface.co/settings/tokens
88
+
89
+ ## Quantization
90
+
91
+
92
+ Use the following code to get the quantized model:
93
+ ```Py
94
+ import torch
95
+ from transformers import AutoModelForCausalLM, AutoTokenizer, TorchAoConfig
96
 
97
+ model_id = "Qwen/Qwen3-8B-Base"
98
+ model_to_quantize = "f"{{MODEL_NAME}}-untied-weights""
99
 
 
 
 
100
 
101
+ from torchao.quantization.quant_api import (
102
+ IntxWeightOnlyConfig,
103
+ Int8DynamicActivationIntxWeightConfig,
104
+ ModuleFqnToConfig,
105
+ )
106
+ from torchao.quantization.granularity import PerGroup, PerAxis
107
+ embedding_config = IntxWeightOnlyConfig(
108
+ weight_dtype=torch.int8,
109
+ granularity=PerAxis(0),
110
+ )
111
+ linear_config = Int8DynamicActivationIntxWeightConfig(
112
+ weight_dtype=torch.int4,
113
+ weight_granularity=PerGroup(32),
114
+ weight_scale_dtype=torch.bfloat16,
115
+ )
116
+ quant_config = ModuleFqnToConfig({{"_default": linear_config, "model.embed_tokens": embedding_config}})
117
+ quantization_config = TorchAoConfig(quant_type=quant_config, include_embedding=True, untie_embedding_weights=True, modules_to_not_convert=[])
118
 
119
+ quantized_model = AutoModelForCausalLM.from_pretrained(model_to_quantize, device_map="auto", torch_dtype=torch.bfloat16, quantization_config=quantization_config)
120
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
121
 
122
+ # Push to hub
123
+ USER_ID = "YOUR_USER_ID"
124
+ MODEL_NAME = model_id.split("/")[-1]
125
+ save_to = f"{USER_ID}/{MODEL_NAME}-INT8-INT4"
126
+ quantized_model.push_to_hub(save_to, safe_serialization=False)
127
+ tokenizer.push_to_hub(save_to)
128
 
129
+ # Manual Testing
130
+ prompt = "Hey, are you conscious? Can you talk to me?"
131
+ messages = [
132
+ {
133
+ "role": "system",
134
+ "content": "",
135
+ },
136
+ {"role": "user", "content": prompt},
137
+ ]
138
+ templated_prompt = tokenizer.apply_chat_template(
139
+ messages,
140
+ tokenize=False,
141
+ add_generation_prompt=True,
142
+ )
143
+ print("Prompt:", prompt)
144
+ print("Templated prompt:", templated_prompt)
145
+ inputs = tokenizer(
146
+ templated_prompt,
147
+ return_tensors="pt",
148
+ ).to("cuda")
149
+ generated_ids = quantized_model.generate(**inputs, max_new_tokens=128)
150
+ output_text = tokenizer.batch_decode(
151
+ generated_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False
152
+ )
153
+ print("Response:", output_text[0][len(prompt):])
154
+ ```
155
 
156
+ Note: to `push_to_hub` you need to run
157
+ ```Shell
158
+ pip install -U "huggingface_hub[cli]"
159
+ huggingface-cli login
160
+ ```
161
+ and use a token with write access, from https://huggingface.co/settings/tokens
162
 
163
+ # Model Quality
164
+ 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.
165
 
166
+ | Benchmark | | |
167
+ |----------------------------------|----------------|---------------------------|
168
+ | | Qwen/Qwen3-8B-Base | q10/Qwen3-8B-Base-INT8-INT4 |
169
+ | mmlu | To be filled | To be filled |
170
 
 
171
 
172
+ <details>
173
+ <summary> Reproduce Model Quality Results </summary>
174
 
175
+ Need to install lm-eval from source:
176
+ https://github.com/EleutherAI/lm-evaluation-harness#install
177
 
178
+ ## baseline
179
+ ```Shell
180
+ lm_eval --model hf --model_args pretrained=Qwen/Qwen3-8B-Base --tasks mmlu --device cuda:0 --batch_size 8
181
+ ```
182
+
183
+ ## INT8-INT4
184
+ ```Shell
185
+ export MODEL=q10/Qwen3-8B-Base-INT8-INT4
186
+ lm_eval --model hf --model_args pretrained=$MODEL --tasks mmlu --device cuda:0 --batch_size 8
187
+ ```
188
+ </details>
189
 
 
190
 
 
191
 
 
192
 
 
193
 
 
194
 
 
195
 
 
196
 
 
197
 
198
+ # Exporting to ExecuTorch
199
 
200
+ We can run the quantized model on a mobile phone using [ExecuTorch](https://github.com/pytorch/executorch).
201
+ Once ExecuTorch is [set-up](https://pytorch.org/executorch/main/getting-started.html), exporting and running the model on device is a breeze.
202
+
203
+ We first convert the [quantized checkpoint](https://huggingface.co/q10/Qwen3-8B-Base-INT8-INT4/blob/main/pytorch_model.bin) to one ExecuTorch's LLM export script expects by renaming some of the checkpoint keys.
204
+ The following script does this for you. We have uploaded the converted checkpoint [pytorch_model_converted.bin](https://huggingface.co/q10/Qwen3-8B-Base-INT8-INT4/blob/main/pytorch_model_converted.bin) for convenience.
205
+ ```Shell
206
+ python -m executorch.examples.models.qwen3.convert_weights $(huggingface-cli download q10/Qwen3-8B-Base-INT8-INT4) pytorch_model_converted.bin
207
+ ```
208
 
209
+ Once the checkpoint is converted, we can export to ExecuTorch's pte format with the XNNPACK delegate.
210
+ The below command exports with a max_seq_length/max_context_length of 1024, but it can be changed as desired.
211
 
212
+ (TODO: pte file name, model config path, model name auto generation)
213
+ ```Shell
214
+ PARAMS="executorch/examples/models/qwen3/4b_config.json"
215
+ python -m executorch.examples.models.llama.export_llama --model "qwen3-4b" --checkpoint "pytorch_model_converted.bin" --params "$PARAMS" -kv --use_sdpa_with_kv_cache -d fp32
216
+ -X --metadata '{"get_bos_id":199999, "get_eos_ids":[200020,199999]}' --max_seq_length 1024 --max_context_length 1024 --output_name="qwen3-4b-INT8-INT4-1024-cxt.pte"
217
+ ```
218
 
219
+ After that you can run the model in a mobile app (see [Running in a mobile app](#running-in-a-mobile-app)).
220
 
 
221
 
222
+ # Paper: TorchAO: PyTorch-Native Training-to-Serving Model Optimization
223
+ 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).
224
 
225
+ **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 .
226
 
227
+ # Resources
228
+ * **Official TorchAO GitHub Repository:** [https://github.com/pytorch/ao](https://github.com/pytorch/ao)
229
+ * **TorchAO Documentation:** [https://docs.pytorch.org/ao/stable/index.html](https://docs.pytorch.org/ao/stable/index.html)
230
 
231
 
232
+ # Disclaimer
233
+ 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.
234
 
235
+ 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.