ramblingpolymath commited on
Commit
e69c622
·
verified ·
1 Parent(s): c4b295e

Create README.md

Browse files
Files changed (1) hide show
  1. README.md +277 -0
README.md ADDED
@@ -0,0 +1,277 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ library_name: transformers
3
+ license: apache-2.0
4
+ pipeline_tag: text-generation
5
+ base_model: Qwen/Qwen3-Coder-30B-A3B-Instruct
6
+ tags:
7
+ - quantized
8
+ - w4a16
9
+ - llm-compressor
10
+ ---
11
+
12
+ ```
13
+ ██╗ ██╗██╗ ██╗ █████╗ ██╗ ██████╗
14
+ ██║ ██║██║ ██║██╔══██╗███║██╔════╝
15
+ ██║ █╗ ██║███████║███████║╚██║███████╗
16
+ ██║███╗██║╚════██║██╔══██║ ██║██╔═══██╗
17
+ ╚███╔███╔╝ ██║██║ ██║ ██║╚██████╔╝
18
+ ╚══╝╚══╝ ╚═╝╚═╝ ╚═╝ ╚═╝ ╚═════╝
19
+ 🗜️ COMPRESSED & OPTIMIZED 🚀
20
+ ```
21
+
22
+ # Qwen3-Coder-30B-A3B-Instruct - W4A16 Quantized
23
+
24
+ W4A16 (4-bit weights, 16-bit activations) quantized version of Qwen/Qwen3-Coder-30B-A3B-Instruct using **LLM-Compressor**.
25
+
26
+ - 🗜️ **Memory**: ~75% reduction vs FP16
27
+ - 🚀 **Speed**: Faster inference on supported hardware
28
+ - 🔗 **Original model**: [link]
29
+
30
+ <details>
31
+ <summary>Click to view compression config</summary>
32
+
33
+ ```python
34
+ from datasets import load_dataset
35
+ from llmcompressor.modifiers.quantization import GPTQModifier
36
+ from llmcompressor import oneshot
37
+ from transformers import AutoModelForCausalLM, AutoTokenizer
38
+
39
+ # Load model with memory management
40
+ model_stub = "Qwen/Qwen3-Coder-30B-A3B-Instruct"
41
+ model_name = model_stub.split("/")[-1]
42
+
43
+ # Use conservative parameters
44
+ num_samples = 1024
45
+ max_seq_len = 8192
46
+
47
+ print(f"Loading model: {model_stub}")
48
+ model = AutoModelForCausalLM.from_pretrained(
49
+ model_stub,
50
+ torch_dtype="auto",
51
+ device_map="auto",
52
+ max_memory={0: "22GB", 1: "22GB", "cpu": "24GB"},
53
+ )
54
+
55
+ print("Loading tokenizer...")
56
+ tokenizer = AutoTokenizer.from_pretrained(model_stub)
57
+
58
+ print("Loading calibration dataset...")
59
+ def preprocess_fn(example):
60
+ return {"text": tokenizer.apply_chat_template(
61
+ example["messages"],
62
+ add_generation_prompt=False,
63
+ tokenize=False
64
+ )}
65
+
66
+ # Load dataset and preprocess
67
+ ds = load_dataset("neuralmagic/LLM_compression_calibration", split=f"train[:{num_samples}]")
68
+ ds = ds.map(preprocess_fn)
69
+ ds = ds.shuffle(seed=42)
70
+
71
+ # Tokenize the dataset
72
+ def tokenize(sample):
73
+ return tokenizer(
74
+ sample["text"],
75
+ padding=False,
76
+ max_length=max_seq_len,
77
+ truncation=True,
78
+ add_special_tokens=False,
79
+ )
80
+
81
+ print("Tokenizing dataset...")
82
+ ds = ds.map(tokenize, remove_columns=ds.column_names)
83
+
84
+ # Configure GPTQ with proper Qwen3 MoE ignore patterns
85
+ print("Configuring quantization recipe...")
86
+ recipe = GPTQModifier(
87
+ targets="Linear",
88
+ scheme="W4A16",
89
+ ignore=["lm_head", "re:.*mlp.gate$"], # Qwen3 MoE pattern (no shared experts)
90
+ dampening_frac=0.01,
91
+ # Remove sequential_targets - let llmcompressor handle automatically
92
+ )
93
+
94
+ # Apply quantization
95
+ print("Starting quantization process...")
96
+ oneshot(
97
+ model=model,
98
+ dataset=ds,
99
+ recipe=recipe,
100
+ max_seq_length=max_seq_len,
101
+ num_calibration_samples=num_samples,
102
+ )
103
+
104
+ # Save quantized model
105
+ save_path = model_name + "-gptq-w4a16"
106
+ print(f"Saving model to: {save_path}")
107
+ model.save_pretrained(save_path, save_compressed=True)
108
+ tokenizer.save_pretrained(save_path)
109
+
110
+ print("Quantization completed successfully!")
111
+ ```
112
+
113
+ </details>
114
+
115
+ ---
116
+
117
+ ## 📄 Original Model README
118
+
119
+ # Qwen3-Coder-30B-A3B-Instruct
120
+ <a href="https://chat.qwen.ai/" target="_blank" style="margin: 2px;">
121
+ <img alt="Chat" src="https://img.shields.io/badge/%F0%9F%92%9C%EF%B8%8F%20Qwen%20Chat%20-536af5" style="display: inline-block; vertical-align: middle;"/>
122
+ </a>
123
+
124
+ ## Highlights
125
+
126
+ **Qwen3-Coder** is available in multiple sizes. Today, we're excited to introduce **Qwen3-Coder-30B-A3B-Instruct**. This streamlined model maintains impressive performance and efficiency, featuring the following key enhancements:
127
+
128
+ - **Significant Performance** among open models on **Agentic Coding**, **Agentic Browser-Use**, and other foundational coding tasks.
129
+ - **Long-context Capabilities** with native support for **256K** tokens, extendable up to **1M** tokens using Yarn, optimized for repository-scale understanding.
130
+ - **Agentic Coding** supporting for most platform such as **Qwen Code**, **CLINE**, featuring a specially designed function call format.
131
+
132
+ ![image/jpeg](https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen3-Coder/qwen3-coder-30a3-main.jpg)
133
+
134
+ ## Model Overview
135
+
136
+ **Qwen3-Coder-30B-A3B-Instruct** has the following features:
137
+ - Type: Causal Language Models
138
+ - Training Stage: Pretraining & Post-training
139
+ - Number of Parameters: 30.5B in total and 3.3B activated
140
+ - Number of Layers: 48
141
+ - Number of Attention Heads (GQA): 32 for Q and 4 for KV
142
+ - Number of Experts: 128
143
+ - Number of Activated Experts: 8
144
+ - Context Length: **262,144 natively**.
145
+
146
+ **NOTE: This model supports only non-thinking mode and does not generate ``<think></think>`` blocks in its output. Meanwhile, specifying `enable_thinking=False` is no longer required.**
147
+
148
+ For more details, including benchmark evaluation, hardware requirements, and inference performance, please refer to our [blog](https://qwenlm.github.io/blog/qwen3-coder/), [GitHub](https://github.com/QwenLM/Qwen3-Coder), and [Documentation](https://qwen.readthedocs.io/en/latest/).
149
+
150
+
151
+ ## Quickstart
152
+
153
+ We advise you to use the latest version of `transformers`.
154
+
155
+ With `transformers<4.51.0`, you will encounter the following error:
156
+ ```
157
+ KeyError: 'qwen3_moe'
158
+ ```
159
+
160
+ The following contains a code snippet illustrating how to use the model generate content based on given inputs.
161
+ ```python
162
+ from transformers import AutoModelForCausalLM, AutoTokenizer
163
+
164
+ model_name = "Qwen/Qwen3-Coder-30B-A3B-Instruct"
165
+
166
+ # load the tokenizer and the model
167
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
168
+ model = AutoModelForCausalLM.from_pretrained(
169
+ model_name,
170
+ torch_dtype="auto",
171
+ device_map="auto"
172
+ )
173
+
174
+ # prepare the model input
175
+ prompt = "Write a quick sort algorithm."
176
+ messages = [
177
+ {"role": "user", "content": prompt}
178
+ ]
179
+ text = tokenizer.apply_chat_template(
180
+ messages,
181
+ tokenize=False,
182
+ add_generation_prompt=True,
183
+ )
184
+ model_inputs = tokenizer([text], return_tensors="pt").to(model.device)
185
+
186
+ # conduct text completion
187
+ generated_ids = model.generate(
188
+ **model_inputs,
189
+ max_new_tokens=65536
190
+ )
191
+ output_ids = generated_ids[0][len(model_inputs.input_ids[0]):].tolist()
192
+
193
+ content = tokenizer.decode(output_ids, skip_special_tokens=True)
194
+
195
+ print("content:", content)
196
+ ```
197
+
198
+ **Note: If you encounter out-of-memory (OOM) issues, consider reducing the context length to a shorter value, such as `32,768`.**
199
+
200
+ For local use, applications such as Ollama, LMStudio, MLX-LM, llama.cpp, and KTransformers have also supported Qwen3.
201
+
202
+ ## Agentic Coding
203
+
204
+ Qwen3-Coder excels in tool calling capabilities.
205
+
206
+ You can simply define or use any tools as following example.
207
+ ```python
208
+ # Your tool implementation
209
+ def square_the_number(num: float) -> dict:
210
+ return num ** 2
211
+
212
+ # Define Tools
213
+ tools=[
214
+ {
215
+ "type":"function",
216
+ "function":{
217
+ "name": "square_the_number",
218
+ "description": "output the square of the number.",
219
+ "parameters": {
220
+ "type": "object",
221
+ "required": ["input_num"],
222
+ "properties": {
223
+ 'input_num': {
224
+ 'type': 'number',
225
+ 'description': 'input_num is a number that will be squared'
226
+ }
227
+ },
228
+ }
229
+ }
230
+ }
231
+ ]
232
+
233
+ import OpenAI
234
+ # Define LLM
235
+ client = OpenAI(
236
+ # Use a custom endpoint compatible with OpenAI API
237
+ base_url='http://localhost:8000/v1', # api_base
238
+ api_key="EMPTY"
239
+ )
240
+
241
+ messages = [{'role': 'user', 'content': 'square the number 1024'}]
242
+
243
+ completion = client.chat.completions.create(
244
+ messages=messages,
245
+ model="Qwen3-Coder-30B-A3B-Instruct",
246
+ max_tokens=65536,
247
+ tools=tools,
248
+ )
249
+
250
+ print(completion.choice[0])
251
+ ```
252
+
253
+ ## Best Practices
254
+
255
+ To achieve optimal performance, we recommend the following settings:
256
+
257
+ 1. **Sampling Parameters**:
258
+ - We suggest using `temperature=0.7`, `top_p=0.8`, `top_k=20`, `repetition_penalty=1.05`.
259
+
260
+ 2. **Adequate Output Length**: We recommend using an output length of 65,536 tokens for most queries, which is adequate for instruct models.
261
+
262
+
263
+ ### Citation
264
+
265
+ If you find our work helpful, feel free to give us a cite.
266
+
267
+ ```
268
+ @misc{qwen3technicalreport,
269
+ title={Qwen3 Technical Report},
270
+ author={Qwen Team},
271
+ year={2025},
272
+ eprint={2505.09388},
273
+ archivePrefix={arXiv},
274
+ primaryClass={cs.CL},
275
+ url={https://arxiv.org/abs/2505.09388},
276
+ }
277
+ ```