YCWTG commited on
Commit
cfc1d49
·
verified ·
1 Parent(s): fc3d512

Update README_zh.md

Browse files
Files changed (1) hide show
  1. README_zh.md +268 -96
README_zh.md CHANGED
@@ -1,96 +1,268 @@
1
- base_model:
2
- - Qwen/Qwen3-Coder-Next
3
- pipeline_tag: text-generation
4
- ---
5
- <p align="center">
6
- <img src="https://cdn-uploads.huggingface.co/production/uploads/685e122d50df66f41587d406/kzCYol3JJ0nC3x3RvBZWd.png" alt="语调">
7
- </p>
8
-
9
- Language 中文|[English](https://huggingface.co/YCWTG/Qwen3-Coder-Next-int2-AutoRound-best)
10
- ## Model Details
11
-
12
- This model is an int2 model with group_size 512 and symmetric quantization of [Qwen/Qwen3-Coder-Next](https://huggingface.co/Qwen/Qwen3-Coder-Next) generated by [intel/auto-round](https://github.com/intel/auto-round). Please follow the license of the original model.
13
-
14
- ### MMLU-Pro
15
-
16
- | Model | Accuracy | Delta |
17
- |-------|----------|-------|
18
- | BF16 | 52.90% | - |
19
- | **W2A16** | **51.27%** | **-1.63%** |
20
-
21
- ## How to Use
22
-
23
- ### HF Usage
24
-
25
- ```python
26
- from transformers import AutoModelForCausalLM, AutoTokenizer
27
-
28
- model_name = "YCWTG/Qwen3-Coder-Next-int2-AutoRound-best"
29
-
30
- # load the tokenizer and the model
31
- tokenizer = AutoTokenizer.from_pretrained(model_name)
32
- model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype="auto", device_map="auto")
33
-
34
- # prepare the model input
35
- prompt = "Write a quick sort algorithm."
36
- messages = [{"role": "user", "content": prompt}]
37
- text = tokenizer.apply_chat_template(
38
- messages,
39
- tokenize=False,
40
- add_generation_prompt=True,
41
- )
42
- model_inputs = tokenizer([text], return_tensors="pt").to(model.device)
43
-
44
- # conduct text completion
45
- generated_ids = model.generate(**model_inputs, max_new_tokens=65536)
46
- output_ids = generated_ids[0][len(model_inputs.input_ids[0]) :].tolist()
47
-
48
- content = tokenizer.decode(output_ids, skip_special_tokens=True)
49
-
50
- print("content:", content)
51
- ```
52
-
53
- ### VLLM Usage
54
-
55
- ```bash
56
- vllm serve YCWTG/Qwen3-Coder-Next-int2-AutoRound-best \
57
- --trust-remote-code \
58
- --dtype bfloat16 \
59
- --tensor_parallel_size 1
60
- ```
61
-
62
- ## Generate the Model
63
-
64
- ```bash
65
- auto-round-best --model Qwen/Qwen3-Coder-Next --scheme "W2A16G32" --format "auto_round"
66
- ```
67
-
68
- ## Ethical Considerations and Limitations
69
-
70
- The model can produce factually incorrect output, and should not be relied on to produce factually accurate information. Because of the limitations of the pretrained model and the finetuning datasets, it is possible that this model could generate lewd, biased or otherwise offensive outputs.
71
- Therefore, before deploying any applications of the model, developers should perform safety testing.
72
-
73
- ## Caveats and Recommendations
74
-
75
- Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model.
76
- Here are a couple of useful links to learn more about Intel's AI software:
77
-
78
- - [Intel Neural Compressor](https://github.com/intel/neural-compressor)
79
- - [AutoRound](https://github.com/intel/auto-round)
80
-
81
- ## Disclaimer
82
-
83
- The license on this model does not constitute legal advice. We are not responsible for the actions of third parties who use this model. Please consult an attorney before using this model for commercial purposes.
84
-
85
- ## Cite
86
-
87
- ```
88
- @article{cheng2023optimize,
89
- title={Optimize weight rounding via signed gradient descent for the quantization of llms},
90
- author={Cheng, Wenhua and Zhang, Weiwei and Shen, Haihao and Cai, Yiyang and He, Xin and Lv, Kaokao and Liu, Yi},
91
- journal={arXiv preprint arXiv:2309.05516},
92
- year={2023}
93
- }
94
- ```
95
-
96
- [arxiv](https://arxiv.org/abs/2309.05516) [github](https://github.com/intel/auto-round)## Benchmark Results
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <p align="center">
2
+ <img src="https://cdn-uploads.huggingface.co/production/uploads/685e122d50df66f41587d406/kzCYol3JJ0nC3x3RvBZWd.png" alt="语调">
3
+ </p>
4
+
5
+ Language 中文|[English](https://huggingface.co/YCWTG/Qwen3-Coder-Next-int2-AutoRound-best)
6
+ ## 模型详情
7
+
8
+ 该模型是一个 **mixed-bits INT2 量化** 模型,group_size 为 512,并对 [Qwen/Qwen3-Coder-Next](https://huggingface.co/Qwen/Qwen3-Coder-Next) 采用对称量化,由 [intel/auto-round](https://github.com/intel/auto-round) 生成。请遵循原始模型的 license。
9
+
10
+ ### 量化策略(Intel MoE Recipe)
11
+
12
+ | 层类型 | Bits | 说明 |
13
+ | ---------------------------------- | ------ | ------------------- |
14
+ | Expert layers(512 个 experts) | 2-bit | MoE expert MLPs |
15
+ | Non-expert layers(attention, gate) | 16-bit | 为保证质量使用更高精度 |
16
+ | shared_expert_gate | 16-bit | 跳过(shape 不能被 32 整除) |
17
+ | lm_head | 原始精度 | 被 AutoRound 排除 |
18
+
19
+ ### 模型大小
20
+
21
+ * **原始 BF16**:约 160GB
22
+ * **mixed INT2**:约 25GB(**减少 84%↓↓**)
23
+
24
+
25
+ ## 快速开始
26
+
27
+ ### HF 使用方法
28
+
29
+ ```python
30
+ import math
31
+ import os
32
+
33
+ os.environ.setdefault(
34
+ "PYTORCH_ALLOC_CONF",
35
+ # 保持更安全的 allocator 默认设置,并透明迁移已弃用的环境变量
36
+ os.environ.pop("PYTORCH_CUDA_ALLOC_CONF", None) or "expandable_segments:True",
37
+ )
38
+
39
+ import torch
40
+ from transformers import AutoModelForCausalLM, AutoTokenizer
41
+
42
+ MODEL_NAME = "YCWTG/Qwen3-Coder-Next-int2-mixed-AutoRound"
43
+ AUTO_MAX_TOKENS = True
44
+ MANUAL_MAX_NEW_TOKENS = 128
45
+ AUTO_MAX_TOKENS_RATIO = 1.5
46
+
47
+ HAS_CUDA = torch.cuda.is_available()
48
+ # 读取一次 VRAM 总量,并据此选择默认加载模式
49
+ GPU_TOTAL_MIB = torch.cuda.get_device_properties(0).total_memory // (1024 ** 2) if HAS_CUDA else 0
50
+ # 32GB 级别 GPU 默认 False;更小显存的 GPU 默认 True
51
+ ENABLE_CPU_OFFLOAD = HAS_CUDA and GPU_TOTAL_MIB < 32000
52
+ MAX_MEMORY = {0: "18GiB", "cpu": "64GiB"} if ENABLE_CPU_OFFLOAD else {0: "22GiB", "cpu": "16GiB"}
53
+
54
+
55
+ def get_input_device(model):
56
+ # 使用 device_map="auto" 时,第一个可用设备可能不是 model.device
57
+ device_map = getattr(model, "hf_device_map", None)
58
+ cpu_device = None
59
+ if isinstance(device_map, dict):
60
+ for loc in device_map.values():
61
+ if isinstance(loc, int):
62
+ return torch.device(f"cuda:{loc}")
63
+ if isinstance(loc, str):
64
+ if loc.startswith("cuda"):
65
+ return torch.device(loc)
66
+ if loc.startswith("cpu"):
67
+ cpu_device = torch.device("cpu")
68
+ return cpu_device or next(model.parameters()).device
69
+
70
+
71
+ def load_model():
72
+ print("正在加载模型...")
73
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME, trust_remote_code=True, use_fast=True)
74
+ # 使用 EOS 作为 PAD,避免在没有 pad token 的模型上进行 chat generation 时出现警告
75
+ tokenizer.pad_token = tokenizer.pad_token or tokenizer.eos_token
76
+ tokenizer.padding_side = "left"
77
+
78
+ model_kwargs = {
79
+ "pretrained_model_name_or_path": MODEL_NAME,
80
+ "dtype": torch.bfloat16,
81
+ "trust_remote_code": True,
82
+ "low_cpu_mem_usage": True,
83
+ "device_map": "auto" if HAS_CUDA else "cpu",
84
+ }
85
+ if HAS_CUDA:
86
+ print(f"GPU 总显存: {GPU_TOTAL_MIB} MiB")
87
+ model_kwargs["max_memory"] = MAX_MEMORY
88
+ if ENABLE_CPU_OFFLOAD:
89
+ model_kwargs["offload_buffers"] = True
90
+ print("CPU offload: 开启")
91
+ else:
92
+ print("CPU offload: 关闭(优先使用 GPU,允许少量 CPU 溢出)")
93
+ else:
94
+ print("CUDA 不可用,在 CPU 上运行")
95
+
96
+ try:
97
+ model = AutoModelForCausalLM.from_pretrained(**model_kwargs)
98
+ except RuntimeError as e:
99
+ # 提供对新手更友好的提示,而不是只显示原始报错堆栈
100
+ if "out of memory" in str(e).lower():
101
+ print("\n加载模型时发生 CUDA OOM")
102
+ print("请关闭其他 GPU 程序,或设置 ENABLE_CPU_OFFLOAD = True 后重试")
103
+ raise
104
+ model.eval()
105
+ return model, tokenizer
106
+
107
+
108
+ def multiline_input():
109
+ print('用户(单独一行输入 "END" 发送,输入 "exit" 退出):')
110
+ lines = []
111
+ while True:
112
+ line = input()
113
+ text = line.strip()
114
+ if text.lower() in {"exit", "quit"}:
115
+ return None
116
+ if text == "END":
117
+ break
118
+ lines.append(line)
119
+ return "\n".join(lines)
120
+
121
+
122
+ def build_input_ids(tokenizer, messages, device):
123
+ if getattr(tokenizer, "chat_template", None):
124
+ # chat 模型的优先路径:由 tokenizer 构建 prompt 格式
125
+ prompt = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
126
+ else:
127
+ # 没有内置 chat template 时的通用回退方案
128
+ prompt = "\n".join(
129
+ [f"{'User' if m['role'] == 'user' else 'Assistant'}: {m['content']}" for m in messages]
130
+ + ["Assistant:"]
131
+ )
132
+ return tokenizer(prompt, return_tensors="pt")["input_ids"].to(device)
133
+
134
+
135
+ def chat_loop(model, tokenizer):
136
+ print("\n===== 对话已开始 =====\n")
137
+ print(f"自动 max_tokens: {'开启' if AUTO_MAX_TOKENS else '关闭'}")
138
+ if not AUTO_MAX_TOKENS:
139
+ print(f"手动 max_new_tokens: {MANUAL_MAX_NEW_TOKENS}")
140
+ print(
141
+ "提示:设置 ENABLE_CPU_OFFLOAD = False 可尝试更快的全 GPU 模式"
142
+ if ENABLE_CPU_OFFLOAD
143
+ else "提示:若 max_tokens 过大导致 CUDA OOM,可设置 ENABLE_CPU_OFFLOAD = True"
144
+ )
145
+
146
+ messages = []
147
+ device = get_input_device(model)
148
+ print(f"输入设备: {device}")
149
+
150
+ while True:
151
+ user_text = multiline_input()
152
+ if user_text is None:
153
+ break
154
+
155
+ messages.append({"role": "user", "content": user_text})
156
+ input_ids = build_input_ids(tokenizer, messages, device)
157
+ prompt_tokens = int(input_ids.shape[-1])
158
+ # 自动模式:输出长度随 prompt 长度缩放(默认 1.5 倍)
159
+ max_new_tokens = max(1, math.ceil(prompt_tokens * AUTO_MAX_TOKENS_RATIO)) if AUTO_MAX_TOKENS else int(MANUAL_MAX_NEW_TOKENS)
160
+
161
+ print(f"Prompt tokens: {prompt_tokens}")
162
+ print(f"max_new_tokens: {max_new_tokens}")
163
+
164
+ try:
165
+ with torch.inference_mode():
166
+ output_ids = model.generate(
167
+ input_ids=input_ids,
168
+ max_new_tokens=max_new_tokens,
169
+ do_sample=True,
170
+ temperature=0.9,
171
+ top_p=0.9,
172
+ top_k=40,
173
+ use_cache=False,
174
+ pad_token_id=tokenizer.pad_token_id,
175
+ eos_token_id=tokenizer.eos_token_id,
176
+ )
177
+ except RuntimeError as e:
178
+ error_text = str(e).lower()
179
+ if HAS_CUDA and ("cublas_status_alloc_failed" in error_text or "out of memory" in error_text):
180
+ # 清理 CUDA 缓存块,使下一次尝试在更干净的 CUDA 状态下开始
181
+ torch.cuda.empty_cache()
182
+ print("\n生成过程中发生 CUDA OOM")
183
+ print("请设置 ENABLE_CPU_OFFLOAD = True,或关闭 AUTO_MAX_TOKENS 并降低 MANUAL_MAX_NEW_TOKENS")
184
+ messages.pop()
185
+ continue
186
+ raise
187
+
188
+ reply_text = tokenizer.decode(output_ids[0, input_ids.shape[-1]:], skip_special_tokens=True)
189
+ print(f"\nAssistant:\n{reply_text}\n")
190
+ messages.append({"role": "assistant", "content": reply_text})
191
+
192
+
193
+ if __name__ == "__main__":
194
+ model, tokenizer = load_model()
195
+ chat_loop(model, tokenizer)
196
+ ```
197
+
198
+ ## 生成模型
199
+
200
+ ```python
201
+ from auto_round import AutoRound
202
+
203
+ model_name = "Qwen/Qwen3-Coder-Next"
204
+
205
+ # 为 mixed-bits 构建 layer config(Intel recipe)
206
+ layer_config = {}
207
+ for i in range(48): # 48 层
208
+ prefix = f"model.layers.{i}"
209
+
210
+ # Attention 层 -> 16-bit
211
+ if i in [3, 7, 11, 15, 19, 23, 27, 31, 35, 39, 43, 47]: # self_attn 层
212
+ for proj in ["q_proj", "k_proj", "v_proj", "o_proj"]:
213
+ layer_config[f"{prefix}.self_attn.{proj}"] = {"bits": 16}
214
+ else: # linear_attn 层
215
+ for proj in ["in_proj_qkvz", "in_proj_ba", "out_proj"]:
216
+ layer_config[f"{prefix}.linear_attn.{proj}"] = {"bits": 16}
217
+
218
+ # MLP gate -> 16-bit
219
+ layer_config[f"{prefix}.mlp.gate"] = {"bits": 16}
220
+
221
+ # shared_expert_gate -> 16-bit(跳过)
222
+ layer_config[f"{prefix}.mlp.shared_expert_gate"] = {"bits": 16}
223
+
224
+ autoround = AutoRound(
225
+ model_name,
226
+ bits=2, # experts 默认 2-bit
227
+ group_size=128,
228
+ sym=True,
229
+ iters=1000,
230
+ nsamples=512,
231
+ lr=2e-3,
232
+ layer_config=layer_config,
233
+ low_gpu_mem_usage=True,
234
+ enable_alg_ext=True
235
+ )
236
+ output_dir="~/.cache/model/Qwen3-Coder-Next-int2-mixed-AutoRound"
237
+ autoround.quantize_and_save(output_dir, format="auto_round")
238
+ ```
239
+
240
+ ## 伦理考量与局限性
241
+
242
+ 该模型可能会生成事实不准确的输出,因此不应被依赖用于提供绝对准确的信息。由于 pretrained model 以及 finetuning datasets 的局限性,模型可能生成带有低俗(lewd)、偏见(biased)或其他具有冒犯性的内容。
243
+ 因此,在部署任何基于该模型的应用之前,开发者应进行安全测试。
244
+
245
+
246
+
247
+ ## 注意事项与建议
248
+
249
+ 用户(包括直接用户和下游用户)应充分了解模型的风险、偏见和局限性。
250
+ 以下是一些用于进一步了解 Intel AI software 的有用链接:
251
+
252
+ * [Intel Neural Compressor](https://github.com/intel/neural-compressor)
253
+ * [AutoRound](https://github.com/intel/auto-round)
254
+
255
+
256
+
257
+ ## 免责声明
258
+
259
+ 本模型的 license 不构成法律建议。对于第三方使用本模型所产生的行为,我们不承担责任。在将该模型用于商业用途之前,请咨询律师。
260
+
261
+
262
+
263
+ ## 引用
264
+
265
+ (引用代码保持不变)
266
+
267
+ [arxiv](https://arxiv.org/abs/2309.05516)
268
+ [github](https://github.com/intel/auto-round)