Upload folder using huggingface_hub
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- .gitattributes +1 -0
- README.md +353 -0
- added_tokens.json +37 -0
- config.json +210 -0
- configuration.json +1 -0
- configuration_intern_vit.py +119 -0
- configuration_internvl_chat.py +115 -0
- conversation.py +391 -0
- generation_config.json +4 -0
- layer-0-ep-0-of-1.safetensors +3 -0
- layer-1-ep-0-of-1.safetensors +3 -0
- layer-10-ep-0-of-1.safetensors +3 -0
- layer-11-ep-0-of-1.safetensors +3 -0
- layer-12-ep-0-of-1.safetensors +3 -0
- layer-13-ep-0-of-1.safetensors +3 -0
- layer-14-ep-0-of-1.safetensors +3 -0
- layer-15-ep-0-of-1.safetensors +3 -0
- layer-16-ep-0-of-1.safetensors +3 -0
- layer-17-ep-0-of-1.safetensors +3 -0
- layer-18-ep-0-of-1.safetensors +3 -0
- layer-19-ep-0-of-1.safetensors +3 -0
- layer-2-ep-0-of-1.safetensors +3 -0
- layer-20-ep-0-of-1.safetensors +3 -0
- layer-21-ep-0-of-1.safetensors +3 -0
- layer-22-ep-0-of-1.safetensors +3 -0
- layer-23-ep-0-of-1.safetensors +3 -0
- layer-24-ep-0-of-1.safetensors +3 -0
- layer-25-ep-0-of-1.safetensors +3 -0
- layer-26-ep-0-of-1.safetensors +3 -0
- layer-27-ep-0-of-1.safetensors +3 -0
- layer-28-ep-0-of-1.safetensors +3 -0
- layer-29-ep-0-of-1.safetensors +3 -0
- layer-3-ep-0-of-1.safetensors +3 -0
- layer-30-ep-0-of-1.safetensors +3 -0
- layer-31-ep-0-of-1.safetensors +3 -0
- layer-32-ep-0-of-1.safetensors +3 -0
- layer-33-ep-0-of-1.safetensors +3 -0
- layer-34-ep-0-of-1.safetensors +3 -0
- layer-35-ep-0-of-1.safetensors +3 -0
- layer-36-ep-0-of-1.safetensors +3 -0
- layer-37-ep-0-of-1.safetensors +3 -0
- layer-38-ep-0-of-1.safetensors +3 -0
- layer-39-ep-0-of-1.safetensors +3 -0
- layer-4-ep-0-of-1.safetensors +3 -0
- layer-40-ep-0-of-1.safetensors +3 -0
- layer-41-ep-0-of-1.safetensors +3 -0
- layer-42-ep-0-of-1.safetensors +3 -0
- layer-43-ep-0-of-1.safetensors +3 -0
- layer-44-ep-0-of-1.safetensors +3 -0
- layer-45-ep-0-of-1.safetensors +3 -0
.gitattributes
CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
36 |
+
tokenizer.json filter=lfs diff=lfs merge=lfs -text
|
README.md
ADDED
@@ -0,0 +1,353 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---
|
2 |
+
library_name: transformers
|
3 |
+
license: apache-2.0
|
4 |
+
license_link: https://huggingface.co/Qwen/Qwen3-235B-A22B/blob/main/LICENSE
|
5 |
+
pipeline_tag: text-generation
|
6 |
+
---
|
7 |
+
|
8 |
+
# Qwen3-235B-A22B
|
9 |
+
<a href="https://chat.qwen.ai/" target="_blank" style="margin: 2px;">
|
10 |
+
<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;"/>
|
11 |
+
</a>
|
12 |
+
|
13 |
+
## Qwen3 Highlights
|
14 |
+
|
15 |
+
Qwen3 is the latest generation of large language models in Qwen series, offering a comprehensive suite of dense and mixture-of-experts (MoE) models. Built upon extensive training, Qwen3 delivers groundbreaking advancements in reasoning, instruction-following, agent capabilities, and multilingual support, with the following key features:
|
16 |
+
|
17 |
+
- **Uniquely support of seamless switching between thinking mode** (for complex logical reasoning, math, and coding) and **non-thinking mode** (for efficient, general-purpose dialogue) **within single model**, ensuring optimal performance across various scenarios.
|
18 |
+
- **Significantly enhancement in its reasoning capabilities**, surpassing previous QwQ (in thinking mode) and Qwen2.5 instruct models (in non-thinking mode) on mathematics, code generation, and commonsense logical reasoning.
|
19 |
+
- **Superior human preference alignment**, excelling in creative writing, role-playing, multi-turn dialogues, and instruction following, to deliver a more natural, engaging, and immersive conversational experience.
|
20 |
+
- **Expertise in agent capabilities**, enabling precise integration with external tools in both thinking and unthinking modes and achieving leading performance among open-source models in complex agent-based tasks.
|
21 |
+
- **Support of 100+ languages and dialects** with strong capabilities for **multilingual instruction following** and **translation**.
|
22 |
+
|
23 |
+
## Model Overview
|
24 |
+
|
25 |
+
**Qwen3-235B-A22B** has the following features:
|
26 |
+
- Type: Causal Language Models
|
27 |
+
- Training Stage: Pretraining & Post-training
|
28 |
+
- Number of Parameters: 235B in total and 22B activated
|
29 |
+
- Number of Paramaters (Non-Embedding): 234B
|
30 |
+
- Number of Layers: 94
|
31 |
+
- Number of Attention Heads (GQA): 64 for Q and 4 for KV
|
32 |
+
- Number of Experts: 128
|
33 |
+
- Number of Activated Experts: 8
|
34 |
+
- Context Length: 32,768 natively and [131,072 tokens with YaRN](#processing-long-texts).
|
35 |
+
|
36 |
+
For more details, including benchmark evaluation, hardware requirements, and inference performance, please refer to our [blog](https://qwenlm.github.io/blog/qwen3/), [GitHub](https://github.com/QwenLM/Qwen3), and [Documentation](https://qwen.readthedocs.io/en/latest/).
|
37 |
+
|
38 |
+
## Quickstart
|
39 |
+
|
40 |
+
The code of Qwen3-MoE has been in the latest Hugging Face `transformers` and we advise you to use the latest version of `transformers`.
|
41 |
+
|
42 |
+
With `transformers<4.51.0`, you will encounter the following error:
|
43 |
+
```
|
44 |
+
KeyError: 'qwen3_moe'
|
45 |
+
```
|
46 |
+
|
47 |
+
The following contains a code snippet illustrating how to use the model generate content based on given inputs.
|
48 |
+
```python
|
49 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
50 |
+
|
51 |
+
model_name = "Qwen/Qwen3-235B-A22B"
|
52 |
+
|
53 |
+
# load the tokenizer and the model
|
54 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
55 |
+
model = AutoModelForCausalLM.from_pretrained(
|
56 |
+
model_name,
|
57 |
+
torch_dtype="auto",
|
58 |
+
device_map="auto"
|
59 |
+
)
|
60 |
+
|
61 |
+
# prepare the model input
|
62 |
+
prompt = "Give me a short introduction to large language model."
|
63 |
+
messages = [
|
64 |
+
{"role": "user", "content": prompt}
|
65 |
+
]
|
66 |
+
text = tokenizer.apply_chat_template(
|
67 |
+
messages,
|
68 |
+
tokenize=False,
|
69 |
+
add_generation_prompt=True,
|
70 |
+
enable_thinking=True # Switches between thinking and non-thinking modes. Default is True.
|
71 |
+
)
|
72 |
+
model_inputs = tokenizer([text], return_tensors="pt").to(model.device)
|
73 |
+
|
74 |
+
# conduct text completion
|
75 |
+
generated_ids = model.generate(
|
76 |
+
**model_inputs,
|
77 |
+
max_new_tokens=32768
|
78 |
+
)
|
79 |
+
output_ids = generated_ids[0][len(model_inputs.input_ids[0]):].tolist()
|
80 |
+
|
81 |
+
# parsing thinking content
|
82 |
+
try:
|
83 |
+
# rindex finding 151668 (</think>)
|
84 |
+
index = len(output_ids) - output_ids[::-1].index(151668)
|
85 |
+
except ValueError:
|
86 |
+
index = 0
|
87 |
+
|
88 |
+
thinking_content = tokenizer.decode(output_ids[:index], skip_special_tokens=True).strip("\n")
|
89 |
+
content = tokenizer.decode(output_ids[index:], skip_special_tokens=True).strip("\n")
|
90 |
+
|
91 |
+
print("thinking content:", thinking_content)
|
92 |
+
print("content:", content)
|
93 |
+
```
|
94 |
+
|
95 |
+
For deployment, you can use `sglang>=0.4.6.post1` or `vllm>=0.8.5` or to create an OpenAI-compatible API endpoint:
|
96 |
+
- SGLang:
|
97 |
+
```shell
|
98 |
+
python -m sglang.launch_server --model-path Qwen/Qwen3-235B-A22B --reasoning-parser qwen3 --tp 8
|
99 |
+
```
|
100 |
+
- vLLM:
|
101 |
+
```shell
|
102 |
+
vllm serve Qwen/Qwen3-235B-A22B --enable-reasoning --reasoning-parser deepseek_r1
|
103 |
+
```
|
104 |
+
|
105 |
+
For local use, applications such as Ollama, LMStudio, MLX-LM, llama.cpp, and KTransformers have also supported Qwen3.
|
106 |
+
|
107 |
+
## Switching Between Thinking and Non-Thinking Mode
|
108 |
+
|
109 |
+
> [!TIP]
|
110 |
+
> The `enable_thinking` switch is also available in APIs created by SGLang and vLLM.
|
111 |
+
> Please refer to our documentation for [SGLang](https://qwen.readthedocs.io/en/latest/deployment/sglang.html#thinking-non-thinking-modes) and [vLLM](https://qwen.readthedocs.io/en/latest/deployment/vllm.html#thinking-non-thinking-modes) users.
|
112 |
+
|
113 |
+
### `enable_thinking=True`
|
114 |
+
|
115 |
+
By default, Qwen3 has thinking capabilities enabled, similar to QwQ-32B. This means the model will use its reasoning abilities to enhance the quality of generated responses. For example, when explicitly setting `enable_thinking=True` or leaving it as the default value in `tokenizer.apply_chat_template`, the model will engage its thinking mode.
|
116 |
+
|
117 |
+
```python
|
118 |
+
text = tokenizer.apply_chat_template(
|
119 |
+
messages,
|
120 |
+
tokenize=False,
|
121 |
+
add_generation_prompt=True,
|
122 |
+
enable_thinking=True # True is the default value for enable_thinking
|
123 |
+
)
|
124 |
+
```
|
125 |
+
|
126 |
+
In this mode, the model will generate think content wrapped in a `<think>...</think>` block, followed by the final response.
|
127 |
+
|
128 |
+
> [!NOTE]
|
129 |
+
> For thinking mode, use `Temperature=0.6`, `TopP=0.95`, `TopK=20`, and `MinP=0` (the default setting in `generation_config.json`). **DO NOT use greedy decoding**, as it can lead to performance degradation and endless repetitions. For more detailed guidance, please refer to the [Best Practices](#best-practices) section.
|
130 |
+
|
131 |
+
|
132 |
+
### `enable_thinking=False`
|
133 |
+
|
134 |
+
We provide a hard switch to strictly disable the model's thinking behavior, aligning its functionality with the previous Qwen2.5-Instruct models. This mode is particularly useful in scenarios where disabling thinking is essential for enhancing efficiency.
|
135 |
+
|
136 |
+
```python
|
137 |
+
text = tokenizer.apply_chat_template(
|
138 |
+
messages,
|
139 |
+
tokenize=False,
|
140 |
+
add_generation_prompt=True,
|
141 |
+
enable_thinking=False # Setting enable_thinking=False disables thinking mode
|
142 |
+
)
|
143 |
+
```
|
144 |
+
|
145 |
+
In this mode, the model will not generate any think content and will not include a `<think>...</think>` block.
|
146 |
+
|
147 |
+
> [!NOTE]
|
148 |
+
> For non-thinking mode, we suggest using `Temperature=0.7`, `TopP=0.8`, `TopK=20`, and `MinP=0`. For more detailed guidance, please refer to the [Best Practices](#best-practices) section.
|
149 |
+
|
150 |
+
### Advanced Usage: Switching Between Thinking and Non-Thinking Modes via User Input
|
151 |
+
|
152 |
+
We provide a soft switch mechanism that allows users to dynamically control the model's behavior when `enable_thinking=True`. Specifically, you can add `/think` and `/no_think` to user prompts or system messages to switch the model's thinking mode from turn to turn. The model will follow the most recent instruction in multi-turn conversations.
|
153 |
+
|
154 |
+
Here is an example of a multi-turn conversation:
|
155 |
+
|
156 |
+
```python
|
157 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
158 |
+
|
159 |
+
class QwenChatbot:
|
160 |
+
def __init__(self, model_name="Qwen/Qwen3-235B-A22B"):
|
161 |
+
self.tokenizer = AutoTokenizer.from_pretrained(model_name)
|
162 |
+
self.model = AutoModelForCausalLM.from_pretrained(model_name)
|
163 |
+
self.history = []
|
164 |
+
|
165 |
+
def generate_response(self, user_input):
|
166 |
+
messages = self.history + [{"role": "user", "content": user_input}]
|
167 |
+
|
168 |
+
text = self.tokenizer.apply_chat_template(
|
169 |
+
messages,
|
170 |
+
tokenize=False,
|
171 |
+
add_generation_prompt=True
|
172 |
+
)
|
173 |
+
|
174 |
+
inputs = self.tokenizer(text, return_tensors="pt")
|
175 |
+
response_ids = self.model.generate(**inputs, max_new_tokens=32768)[0][len(inputs.input_ids[0]):].tolist()
|
176 |
+
response = self.tokenizer.decode(response_ids, skip_special_tokens=True)
|
177 |
+
|
178 |
+
# Update history
|
179 |
+
self.history.append({"role": "user", "content": user_input})
|
180 |
+
self.history.append({"role": "assistant", "content": response})
|
181 |
+
|
182 |
+
return response
|
183 |
+
|
184 |
+
# Example Usage
|
185 |
+
if __name__ == "__main__":
|
186 |
+
chatbot = QwenChatbot()
|
187 |
+
|
188 |
+
# First input (without /think or /no_think tags, thinking mode is enabled by default)
|
189 |
+
user_input_1 = "How many r's in strawberries?"
|
190 |
+
print(f"User: {user_input_1}")
|
191 |
+
response_1 = chatbot.generate_response(user_input_1)
|
192 |
+
print(f"Bot: {response_1}")
|
193 |
+
print("----------------------")
|
194 |
+
|
195 |
+
# Second input with /no_think
|
196 |
+
user_input_2 = "Then, how many r's in blueberries? /no_think"
|
197 |
+
print(f"User: {user_input_2}")
|
198 |
+
response_2 = chatbot.generate_response(user_input_2)
|
199 |
+
print(f"Bot: {response_2}")
|
200 |
+
print("----------------------")
|
201 |
+
|
202 |
+
# Third input with /think
|
203 |
+
user_input_3 = "Really? /think"
|
204 |
+
print(f"User: {user_input_3}")
|
205 |
+
response_3 = chatbot.generate_response(user_input_3)
|
206 |
+
print(f"Bot: {response_3}")
|
207 |
+
```
|
208 |
+
|
209 |
+
> [!NOTE]
|
210 |
+
> For API compatibility, when `enable_thinking=True`, regardless of whether the user uses `/think` or `/no_think`, the model will always output a block wrapped in `<think>...</think>`. However, the content inside this block may be empty if thinking is disabled.
|
211 |
+
> When `enable_thinking=False`, the soft switches are not valid. Regardless of any `/think` or `/no_think` tags input by the user, the model will not generate think content and will not include a `<think>...</think>` block.
|
212 |
+
|
213 |
+
## Agentic Use
|
214 |
+
|
215 |
+
Qwen3 excels in tool calling capabilities. We recommend using [Qwen-Agent](https://github.com/QwenLM/Qwen-Agent) to make the best use of agentic ability of Qwen3. Qwen-Agent encapsulates tool-calling templates and tool-calling parsers internally, greatly reducing coding complexity.
|
216 |
+
|
217 |
+
To define the available tools, you can use the MCP configuration file, use the integrated tool of Qwen-Agent, or integrate other tools by yourself.
|
218 |
+
```python
|
219 |
+
from qwen_agent.agents import Assistant
|
220 |
+
|
221 |
+
# Define LLM
|
222 |
+
llm_cfg = {
|
223 |
+
'model': 'Qwen3-235B-A22B',
|
224 |
+
|
225 |
+
# Use the endpoint provided by Alibaba Model Studio:
|
226 |
+
# 'model_type': 'qwen_dashscope',
|
227 |
+
# 'api_key': os.getenv('DASHSCOPE_API_KEY'),
|
228 |
+
|
229 |
+
# Use a custom endpoint compatible with OpenAI API:
|
230 |
+
'model_server': 'http://localhost:8000/v1', # api_base
|
231 |
+
'api_key': 'EMPTY',
|
232 |
+
|
233 |
+
# Other parameters:
|
234 |
+
# 'generate_cfg': {
|
235 |
+
# # Add: When the response content is `<think>this is the thought</think>this is the answer;
|
236 |
+
# # Do not add: When the response has been separated by reasoning_content and content.
|
237 |
+
# 'thought_in_content': True,
|
238 |
+
# },
|
239 |
+
}
|
240 |
+
|
241 |
+
# Define Tools
|
242 |
+
tools = [
|
243 |
+
{'mcpServers': { # You can specify the MCP configuration file
|
244 |
+
'time': {
|
245 |
+
'command': 'uvx',
|
246 |
+
'args': ['mcp-server-time', '--local-timezone=Asia/Shanghai']
|
247 |
+
},
|
248 |
+
"fetch": {
|
249 |
+
"command": "uvx",
|
250 |
+
"args": ["mcp-server-fetch"]
|
251 |
+
}
|
252 |
+
}
|
253 |
+
},
|
254 |
+
'code_interpreter', # Built-in tools
|
255 |
+
]
|
256 |
+
|
257 |
+
# Define Agent
|
258 |
+
bot = Assistant(llm=llm_cfg, function_list=tools)
|
259 |
+
|
260 |
+
# Streaming generation
|
261 |
+
messages = [{'role': 'user', 'content': 'https://qwenlm.github.io/blog/ Introduce the latest developments of Qwen'}]
|
262 |
+
for responses in bot.run(messages=messages):
|
263 |
+
pass
|
264 |
+
print(responses)
|
265 |
+
```
|
266 |
+
|
267 |
+
## Processing Long Texts
|
268 |
+
|
269 |
+
Qwen3 natively supports context lengths of up to 32,768 tokens. For conversations where the total length (including both input and output) significantly exceeds this limit, we recommend using RoPE scaling techniques to handle long texts effectively. We have validated the model's performance on context lengths of up to 131,072 tokens using the [YaRN](https://arxiv.org/abs/2309.00071) method.
|
270 |
+
|
271 |
+
YaRN is currently supported by several inference frameworks, e.g., `transformers` and `llama.cpp` for local use, `vllm` and `sglang` for deployment. In general, there are two approaches to enabling YaRN for supported frameworks:
|
272 |
+
|
273 |
+
- Modifying the model files:
|
274 |
+
In the `config.json` file, add the `rope_scaling` fields:
|
275 |
+
```json
|
276 |
+
{
|
277 |
+
...,
|
278 |
+
"rope_scaling": {
|
279 |
+
"rope_type": "yarn",
|
280 |
+
"factor": 4.0,
|
281 |
+
"original_max_position_embeddings": 32768
|
282 |
+
}
|
283 |
+
}
|
284 |
+
```
|
285 |
+
For `llama.cpp`, you need to regenerate the GGUF file after the modification.
|
286 |
+
|
287 |
+
- Passing command line arguments:
|
288 |
+
|
289 |
+
For `vllm`, you can use
|
290 |
+
```shell
|
291 |
+
vllm serve ... --rope-scaling '{"rope_type":"yarn","factor":4.0,"original_max_position_embeddings":32768}' --max-model-len 131072
|
292 |
+
```
|
293 |
+
|
294 |
+
For `sglang`, you can use
|
295 |
+
```shell
|
296 |
+
python -m sglang.launch_server ... --json-model-override-args '{"rope_scaling":{"rope_type":"yarn","factor":4.0,"original_max_position_embeddings":32768}}'
|
297 |
+
```
|
298 |
+
|
299 |
+
For `llama-server` from `llama.cpp`, you can use
|
300 |
+
```shell
|
301 |
+
llama-server ... --rope-scaling yarn --rope-scale 4 --yarn-orig-ctx 32768
|
302 |
+
```
|
303 |
+
|
304 |
+
> [!IMPORTANT]
|
305 |
+
> If you encounter the following warning
|
306 |
+
> ```
|
307 |
+
> Unrecognized keys in `rope_scaling` for 'rope_type'='yarn': {'original_max_position_embeddings'}
|
308 |
+
> ```
|
309 |
+
> please upgrade `transformers>=4.51.0`.
|
310 |
+
|
311 |
+
> [!NOTE]
|
312 |
+
> All the notable open-source frameworks implement static YaRN, which means the scaling factor remains constant regardless of input length, **potentially impacting performance on shorter texts.**
|
313 |
+
> We advise adding the `rope_scaling` configuration only when processing long contexts is required.
|
314 |
+
> It is also recommended to modify the `factor` as needed. For example, if the typical context length for your application is 65,536 tokens, it would be better to set `factor` as 2.0.
|
315 |
+
|
316 |
+
> [!NOTE]
|
317 |
+
> The default `max_position_embeddings` in `config.json` is set to 40,960. This allocation includes reserving 32,768 tokens for outputs and 8,192 tokens for typical prompts, which is sufficient for most scenarios involving short text processing. If the average context length does not exceed 32,768 tokens, we do not recommend enabling YaRN in this scenario, as it may potentially degrade model performance.
|
318 |
+
|
319 |
+
> [!TIP]
|
320 |
+
> The endpoint provided by Alibaba Model Studio supports dynamic YaRN by default and no extra configuration is needed.
|
321 |
+
|
322 |
+
## Best Practices
|
323 |
+
|
324 |
+
To achieve optimal performance, we recommend the following settings:
|
325 |
+
|
326 |
+
1. **Sampling Parameters**:
|
327 |
+
- For thinking mode (`enable_thinking=True`), use `Temperature=0.6`, `TopP=0.95`, `TopK=20`, and `MinP=0`. **DO NOT use greedy decoding**, as it can lead to performance degradation and endless repetitions.
|
328 |
+
- For non-thinking mode (`enable_thinking=False`), we suggest using `Temperature=0.7`, `TopP=0.8`, `TopK=20`, and `MinP=0`.
|
329 |
+
- For supported frameworks, you can adjust the `presence_penalty` parameter between 0 and 2 to reduce endless repetitions. However, using a higher value may occasionally result in language mixing and a slight decrease in model performance.
|
330 |
+
|
331 |
+
2. **Adequate Output Length**: We recommend using an output length of 32,768 tokens for most queries. For benchmarking on highly complex problems, such as those found in math and programming competitions, we suggest setting the max output length to 38,912 tokens. This provides the model with sufficient space to generate detailed and comprehensive responses, thereby enhancing its overall performance.
|
332 |
+
|
333 |
+
3. **Standardize Output Format**: We recommend using prompts to standardize model outputs when benchmarking.
|
334 |
+
- **Math Problems**: Include "Please reason step by step, and put your final answer within \boxed{}." in the prompt.
|
335 |
+
- **Multiple-Choice Questions**: Add the following JSON structure to the prompt to standardize responses: "Please show your choice in the `answer` field with only the choice letter, e.g., `"answer": "C"`."
|
336 |
+
|
337 |
+
4. **No Thinking Content in History**: In multi-turn conversations, the historical model output should only include the final output part and does not need to include the thinking content. It is implemented in the provided chat template in Jinja2. However, for frameworks that do not directly use the Jinja2 chat template, it is up to the developers to ensure that the best practice is followed.
|
338 |
+
|
339 |
+
### Citation
|
340 |
+
|
341 |
+
If you find our work helpful, feel free to give us a cite.
|
342 |
+
|
343 |
+
```
|
344 |
+
@misc{qwen3technicalreport,
|
345 |
+
title={Qwen3 Technical Report},
|
346 |
+
author={Qwen Team},
|
347 |
+
year={2025},
|
348 |
+
eprint={2505.09388},
|
349 |
+
archivePrefix={arXiv},
|
350 |
+
primaryClass={cs.CL},
|
351 |
+
url={https://arxiv.org/abs/2505.09388},
|
352 |
+
}
|
353 |
+
```
|
added_tokens.json
ADDED
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"</box>": 151677,
|
3 |
+
"</img>": 151670,
|
4 |
+
"</quad>": 151673,
|
5 |
+
"</ref>": 151675,
|
6 |
+
"</think>": 151668,
|
7 |
+
"</tool_call>": 151658,
|
8 |
+
"</tool_response>": 151666,
|
9 |
+
"<IMG_CONTEXT>": 151671,
|
10 |
+
"<box>": 151676,
|
11 |
+
"<img>": 151669,
|
12 |
+
"<quad>": 151672,
|
13 |
+
"<ref>": 151674,
|
14 |
+
"<think>": 151667,
|
15 |
+
"<tool_call>": 151657,
|
16 |
+
"<tool_response>": 151665,
|
17 |
+
"<|box_end|>": 151649,
|
18 |
+
"<|box_start|>": 151648,
|
19 |
+
"<|endoftext|>": 151643,
|
20 |
+
"<|file_sep|>": 151664,
|
21 |
+
"<|fim_middle|>": 151660,
|
22 |
+
"<|fim_pad|>": 151662,
|
23 |
+
"<|fim_prefix|>": 151659,
|
24 |
+
"<|fim_suffix|>": 151661,
|
25 |
+
"<|im_end|>": 151645,
|
26 |
+
"<|im_start|>": 151644,
|
27 |
+
"<|image_pad|>": 151655,
|
28 |
+
"<|object_ref_end|>": 151647,
|
29 |
+
"<|object_ref_start|>": 151646,
|
30 |
+
"<|quad_end|>": 151651,
|
31 |
+
"<|quad_start|>": 151650,
|
32 |
+
"<|repo_name|>": 151663,
|
33 |
+
"<|video_pad|>": 151656,
|
34 |
+
"<|vision_end|>": 151653,
|
35 |
+
"<|vision_pad|>": 151654,
|
36 |
+
"<|vision_start|>": 151652
|
37 |
+
}
|
config.json
ADDED
@@ -0,0 +1,210 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"_commit_hash": null,
|
3 |
+
"architectures": [
|
4 |
+
"InternVLChatModel"
|
5 |
+
],
|
6 |
+
"auto_map": {
|
7 |
+
"AutoConfig": "configuration_internvl_chat.InternVLChatConfig",
|
8 |
+
"AutoModel": "modeling_internvl_chat.InternVLChatModel",
|
9 |
+
"AutoModelForCausalLM": "modeling_internvl_chat.InternVLChatModel"
|
10 |
+
},
|
11 |
+
"downsample_ratio": 0.5,
|
12 |
+
"dynamic_image_size": true,
|
13 |
+
"force_image_size": 448,
|
14 |
+
"llm_config": {
|
15 |
+
"_attn_implementation_autoset": false,
|
16 |
+
"_name_or_path": "/root/codespace/checkpoints/Qwen3-235B-A22B",
|
17 |
+
"add_cross_attention": false,
|
18 |
+
"architectures": [
|
19 |
+
"Qwen3MoeForCausalLM"
|
20 |
+
],
|
21 |
+
"attention_bias": false,
|
22 |
+
"attention_dropout": 0.0,
|
23 |
+
"bad_words_ids": null,
|
24 |
+
"begin_suppress_tokens": null,
|
25 |
+
"bos_token_id": 151643,
|
26 |
+
"chunk_size_feed_forward": 0,
|
27 |
+
"cross_attention_hidden_size": null,
|
28 |
+
"decoder_sparse_step": 1,
|
29 |
+
"decoder_start_token_id": null,
|
30 |
+
"diversity_penalty": 0.0,
|
31 |
+
"do_sample": false,
|
32 |
+
"early_stopping": false,
|
33 |
+
"encoder_no_repeat_ngram_size": 0,
|
34 |
+
"eos_token_id": 151645,
|
35 |
+
"exponential_decay_length_penalty": null,
|
36 |
+
"finetuning_task": null,
|
37 |
+
"forced_bos_token_id": null,
|
38 |
+
"forced_eos_token_id": null,
|
39 |
+
"head_dim": 128,
|
40 |
+
"hidden_act": "silu",
|
41 |
+
"hidden_size": 4096,
|
42 |
+
"id2label": {
|
43 |
+
"0": "LABEL_0",
|
44 |
+
"1": "LABEL_1"
|
45 |
+
},
|
46 |
+
"initializer_range": 0.02,
|
47 |
+
"intermediate_size": 12288,
|
48 |
+
"is_decoder": false,
|
49 |
+
"is_encoder_decoder": false,
|
50 |
+
"label2id": {
|
51 |
+
"LABEL_0": 0,
|
52 |
+
"LABEL_1": 1
|
53 |
+
},
|
54 |
+
"length_penalty": 1.0,
|
55 |
+
"max_length": 20,
|
56 |
+
"max_position_embeddings": 40960,
|
57 |
+
"max_window_layers": 94,
|
58 |
+
"min_length": 0,
|
59 |
+
"mlp_only_layers": [],
|
60 |
+
"model_type": "qwen3_moe",
|
61 |
+
"moe_intermediate_size": 1536,
|
62 |
+
"no_repeat_ngram_size": 0,
|
63 |
+
"norm_topk_prob": true,
|
64 |
+
"num_attention_heads": 64,
|
65 |
+
"num_beam_groups": 1,
|
66 |
+
"num_beams": 1,
|
67 |
+
"num_experts": 128,
|
68 |
+
"num_experts_per_tok": 8,
|
69 |
+
"num_hidden_layers": 94,
|
70 |
+
"num_key_value_heads": 4,
|
71 |
+
"num_return_sequences": 1,
|
72 |
+
"output_attentions": false,
|
73 |
+
"output_hidden_states": false,
|
74 |
+
"output_router_logits": false,
|
75 |
+
"output_scores": false,
|
76 |
+
"pad_token_id": null,
|
77 |
+
"prefix": null,
|
78 |
+
"problem_type": null,
|
79 |
+
"pruned_heads": {},
|
80 |
+
"remove_invalid_values": false,
|
81 |
+
"repetition_penalty": 1.0,
|
82 |
+
"return_dict": true,
|
83 |
+
"return_dict_in_generate": false,
|
84 |
+
"rms_norm_eps": 1e-06,
|
85 |
+
"rope_scaling": null,
|
86 |
+
"rope_theta": 1000000.0,
|
87 |
+
"router_aux_loss_coef": 0.001,
|
88 |
+
"sep_token_id": null,
|
89 |
+
"sliding_window": null,
|
90 |
+
"suppress_tokens": null,
|
91 |
+
"task_specific_params": null,
|
92 |
+
"temperature": 1.0,
|
93 |
+
"tf_legacy_loss": false,
|
94 |
+
"tie_encoder_decoder": false,
|
95 |
+
"tie_word_embeddings": false,
|
96 |
+
"tokenizer_class": null,
|
97 |
+
"top_k": 50,
|
98 |
+
"top_p": 1.0,
|
99 |
+
"torch_dtype": "bfloat16",
|
100 |
+
"torchscript": false,
|
101 |
+
"transformers_version": "4.51.1",
|
102 |
+
"typical_p": 1.0,
|
103 |
+
"use_bfloat16": false,
|
104 |
+
"use_cache": true,
|
105 |
+
"use_sliding_window": false,
|
106 |
+
"vocab_size": 151936
|
107 |
+
},
|
108 |
+
"max_dynamic_patch": 12,
|
109 |
+
"min_dynamic_patch": 1,
|
110 |
+
"model_type": "internvl_chat",
|
111 |
+
"pad2square": false,
|
112 |
+
"ps_version": "v2",
|
113 |
+
"select_layer": -1,
|
114 |
+
"template": "internvl2_5",
|
115 |
+
"tie_word_embeddings": false,
|
116 |
+
"torch_dtype": "bfloat16",
|
117 |
+
"transformers_version": null,
|
118 |
+
"use_backbone_lora": 0,
|
119 |
+
"use_llm_lora": 0,
|
120 |
+
"use_thumbnail": true,
|
121 |
+
"vision_config": {
|
122 |
+
"_attn_implementation_autoset": false,
|
123 |
+
"_name_or_path": "OpenGVLab/InternViT-6B-448px-V2_5",
|
124 |
+
"add_cross_attention": false,
|
125 |
+
"architectures": [
|
126 |
+
"InternVisionModel"
|
127 |
+
],
|
128 |
+
"attention_dropout": 0.0,
|
129 |
+
"auto_map": {
|
130 |
+
"AutoConfig": "configuration_intern_vit.InternVisionConfig",
|
131 |
+
"AutoModel": "modeling_intern_vit.InternVisionModel"
|
132 |
+
},
|
133 |
+
"bad_words_ids": null,
|
134 |
+
"begin_suppress_tokens": null,
|
135 |
+
"bos_token_id": null,
|
136 |
+
"chunk_size_feed_forward": 0,
|
137 |
+
"cross_attention_hidden_size": null,
|
138 |
+
"decoder_start_token_id": null,
|
139 |
+
"diversity_penalty": 0.0,
|
140 |
+
"do_sample": false,
|
141 |
+
"drop_path_rate": 0.1,
|
142 |
+
"dropout": 0.0,
|
143 |
+
"early_stopping": false,
|
144 |
+
"encoder_no_repeat_ngram_size": 0,
|
145 |
+
"eos_token_id": null,
|
146 |
+
"exponential_decay_length_penalty": null,
|
147 |
+
"finetuning_task": null,
|
148 |
+
"forced_bos_token_id": null,
|
149 |
+
"forced_eos_token_id": null,
|
150 |
+
"hidden_act": "gelu",
|
151 |
+
"hidden_size": 3200,
|
152 |
+
"id2label": {
|
153 |
+
"0": "LABEL_0",
|
154 |
+
"1": "LABEL_1"
|
155 |
+
},
|
156 |
+
"image_size": 448,
|
157 |
+
"initializer_factor": 0.1,
|
158 |
+
"initializer_range": 1e-10,
|
159 |
+
"intermediate_size": 12800,
|
160 |
+
"is_decoder": false,
|
161 |
+
"is_encoder_decoder": false,
|
162 |
+
"label2id": {
|
163 |
+
"LABEL_0": 0,
|
164 |
+
"LABEL_1": 1
|
165 |
+
},
|
166 |
+
"layer_norm_eps": 1e-06,
|
167 |
+
"length_penalty": 1.0,
|
168 |
+
"max_length": 20,
|
169 |
+
"min_length": 0,
|
170 |
+
"model_type": "intern_vit_6b",
|
171 |
+
"no_repeat_ngram_size": 0,
|
172 |
+
"norm_type": "rms_norm",
|
173 |
+
"num_attention_heads": 25,
|
174 |
+
"num_beam_groups": 1,
|
175 |
+
"num_beams": 1,
|
176 |
+
"num_channels": 3,
|
177 |
+
"num_hidden_layers": 45,
|
178 |
+
"num_return_sequences": 1,
|
179 |
+
"output_attentions": false,
|
180 |
+
"output_hidden_states": false,
|
181 |
+
"output_scores": false,
|
182 |
+
"pad_token_id": null,
|
183 |
+
"patch_size": 14,
|
184 |
+
"prefix": null,
|
185 |
+
"problem_type": null,
|
186 |
+
"pruned_heads": {},
|
187 |
+
"qk_normalization": true,
|
188 |
+
"qkv_bias": false,
|
189 |
+
"remove_invalid_values": false,
|
190 |
+
"repetition_penalty": 1.0,
|
191 |
+
"return_dict": true,
|
192 |
+
"return_dict_in_generate": false,
|
193 |
+
"sep_token_id": null,
|
194 |
+
"suppress_tokens": null,
|
195 |
+
"task_specific_params": null,
|
196 |
+
"temperature": 1.0,
|
197 |
+
"tf_legacy_loss": false,
|
198 |
+
"tie_encoder_decoder": false,
|
199 |
+
"tie_word_embeddings": true,
|
200 |
+
"tokenizer_class": null,
|
201 |
+
"top_k": 50,
|
202 |
+
"top_p": 1.0,
|
203 |
+
"torch_dtype": "bfloat16",
|
204 |
+
"torchscript": false,
|
205 |
+
"transformers_version": "4.51.1",
|
206 |
+
"typical_p": 1.0,
|
207 |
+
"use_bfloat16": true,
|
208 |
+
"use_flash_attn": true
|
209 |
+
}
|
210 |
+
}
|
configuration.json
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
{"framework": "pytorch", "task": "others", "allow_remote": true}
|
configuration_intern_vit.py
ADDED
@@ -0,0 +1,119 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# --------------------------------------------------------
|
2 |
+
# InternVL
|
3 |
+
# Copyright (c) 2024 OpenGVLab
|
4 |
+
# Licensed under The MIT License [see LICENSE for details]
|
5 |
+
# --------------------------------------------------------
|
6 |
+
import os
|
7 |
+
from typing import Union
|
8 |
+
|
9 |
+
from transformers.configuration_utils import PretrainedConfig
|
10 |
+
from transformers.utils import logging
|
11 |
+
|
12 |
+
logger = logging.get_logger(__name__)
|
13 |
+
|
14 |
+
|
15 |
+
class InternVisionConfig(PretrainedConfig):
|
16 |
+
r"""
|
17 |
+
This is the configuration class to store the configuration of a [`InternVisionModel`]. It is used to
|
18 |
+
instantiate a vision encoder according to the specified arguments, defining the model architecture.
|
19 |
+
|
20 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
21 |
+
documentation from [`PretrainedConfig`] for more information.
|
22 |
+
|
23 |
+
Args:
|
24 |
+
num_channels (`int`, *optional*, defaults to 3):
|
25 |
+
Number of color channels in the input images (e.g., 3 for RGB).
|
26 |
+
patch_size (`int`, *optional*, defaults to 14):
|
27 |
+
The size (resolution) of each patch.
|
28 |
+
image_size (`int`, *optional*, defaults to 224):
|
29 |
+
The size (resolution) of each image.
|
30 |
+
qkv_bias (`bool`, *optional*, defaults to `False`):
|
31 |
+
Whether to add a bias to the queries and values in the self-attention layers.
|
32 |
+
hidden_size (`int`, *optional*, defaults to 3200):
|
33 |
+
Dimensionality of the encoder layers and the pooler layer.
|
34 |
+
num_attention_heads (`int`, *optional*, defaults to 25):
|
35 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
36 |
+
intermediate_size (`int`, *optional*, defaults to 12800):
|
37 |
+
Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
|
38 |
+
qk_normalization (`bool`, *optional*, defaults to `True`):
|
39 |
+
Whether to normalize the queries and keys in the self-attention layers.
|
40 |
+
num_hidden_layers (`int`, *optional*, defaults to 48):
|
41 |
+
Number of hidden layers in the Transformer encoder.
|
42 |
+
use_flash_attn (`bool`, *optional*, defaults to `True`):
|
43 |
+
Whether to use flash attention mechanism.
|
44 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
|
45 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
46 |
+
`"relu"`, `"selu"` and `"gelu_new"` ``"gelu"` are supported.
|
47 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-6):
|
48 |
+
The epsilon used by the layer normalization layers.
|
49 |
+
dropout (`float`, *optional*, defaults to 0.0):
|
50 |
+
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
|
51 |
+
drop_path_rate (`float`, *optional*, defaults to 0.0):
|
52 |
+
Dropout rate for stochastic depth.
|
53 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
54 |
+
The dropout ratio for the attention probabilities.
|
55 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
56 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
57 |
+
initializer_factor (`float`, *optional*, defaults to 0.1):
|
58 |
+
A factor for layer scale.
|
59 |
+
"""
|
60 |
+
|
61 |
+
model_type = 'intern_vit_6b'
|
62 |
+
|
63 |
+
def __init__(
|
64 |
+
self,
|
65 |
+
num_channels=3,
|
66 |
+
patch_size=14,
|
67 |
+
image_size=224,
|
68 |
+
qkv_bias=False,
|
69 |
+
hidden_size=3200,
|
70 |
+
num_attention_heads=25,
|
71 |
+
intermediate_size=12800,
|
72 |
+
qk_normalization=True,
|
73 |
+
num_hidden_layers=48,
|
74 |
+
use_flash_attn=True,
|
75 |
+
hidden_act='gelu',
|
76 |
+
norm_type='rms_norm',
|
77 |
+
layer_norm_eps=1e-6,
|
78 |
+
dropout=0.0,
|
79 |
+
drop_path_rate=0.0,
|
80 |
+
attention_dropout=0.0,
|
81 |
+
initializer_range=0.02,
|
82 |
+
initializer_factor=0.1,
|
83 |
+
**kwargs,
|
84 |
+
):
|
85 |
+
super().__init__(**kwargs)
|
86 |
+
|
87 |
+
self.hidden_size = hidden_size
|
88 |
+
self.intermediate_size = intermediate_size
|
89 |
+
self.dropout = dropout
|
90 |
+
self.drop_path_rate = drop_path_rate
|
91 |
+
self.num_hidden_layers = num_hidden_layers
|
92 |
+
self.num_attention_heads = num_attention_heads
|
93 |
+
self.num_channels = num_channels
|
94 |
+
self.patch_size = patch_size
|
95 |
+
self.image_size = image_size
|
96 |
+
self.initializer_range = initializer_range
|
97 |
+
self.initializer_factor = initializer_factor
|
98 |
+
self.attention_dropout = attention_dropout
|
99 |
+
self.layer_norm_eps = layer_norm_eps
|
100 |
+
self.hidden_act = hidden_act
|
101 |
+
self.norm_type = norm_type
|
102 |
+
self.qkv_bias = qkv_bias
|
103 |
+
self.qk_normalization = qk_normalization
|
104 |
+
self.use_flash_attn = use_flash_attn
|
105 |
+
|
106 |
+
@classmethod
|
107 |
+
def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> 'PretrainedConfig':
|
108 |
+
config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
|
109 |
+
|
110 |
+
if 'vision_config' in config_dict:
|
111 |
+
config_dict = config_dict['vision_config']
|
112 |
+
|
113 |
+
if 'model_type' in config_dict and hasattr(cls, 'model_type') and config_dict['model_type'] != cls.model_type:
|
114 |
+
logger.warning(
|
115 |
+
f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
|
116 |
+
f'{cls.model_type}. This is not supported for all configurations of models and can yield errors.'
|
117 |
+
)
|
118 |
+
|
119 |
+
return cls.from_dict(config_dict, **kwargs)
|
configuration_internvl_chat.py
ADDED
@@ -0,0 +1,115 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# --------------------------------------------------------
|
2 |
+
# InternVL
|
3 |
+
# Copyright (c) 2024 OpenGVLab
|
4 |
+
# Licensed under The MIT License [see LICENSE for details]
|
5 |
+
# --------------------------------------------------------
|
6 |
+
|
7 |
+
import copy
|
8 |
+
from typing import Dict, Any, Optional
|
9 |
+
|
10 |
+
from transformers.configuration_utils import PretrainedConfig
|
11 |
+
from transformers.utils import logging
|
12 |
+
|
13 |
+
from .configuration_intern_vit import InternVisionConfig
|
14 |
+
|
15 |
+
logger = logging.get_logger(__name__)
|
16 |
+
|
17 |
+
|
18 |
+
class InternVLChatConfig(PretrainedConfig):
|
19 |
+
model_type = 'internvl_chat'
|
20 |
+
is_composition = True
|
21 |
+
|
22 |
+
def __init__(
|
23 |
+
self,
|
24 |
+
vision_config: Optional[Dict[str, Any]] = None,
|
25 |
+
llm_config: Optional[Dict[str, Any]] = None,
|
26 |
+
use_backbone_lora=0,
|
27 |
+
use_llm_lora=0,
|
28 |
+
select_layer=-1,
|
29 |
+
force_image_size=None,
|
30 |
+
downsample_ratio=0.5,
|
31 |
+
template=None,
|
32 |
+
dynamic_image_size=False,
|
33 |
+
use_thumbnail=False,
|
34 |
+
ps_version="v1",
|
35 |
+
min_dynamic_patch=1,
|
36 |
+
max_dynamic_patch=6,
|
37 |
+
**kwargs,
|
38 |
+
):
|
39 |
+
super().__init__(**kwargs)
|
40 |
+
|
41 |
+
if vision_config is None:
|
42 |
+
vision_config = {'architectures': ['InternVisionModel']}
|
43 |
+
logger.info('vision_config is None. Initializing the InternVisionConfig with default values.')
|
44 |
+
|
45 |
+
if llm_config is None:
|
46 |
+
llm_config = {'architectures': ['Qwen2ForCausalLM']}
|
47 |
+
logger.info('llm_config is None. Initializing the LlamaConfig config with default values (`LlamaConfig`).')
|
48 |
+
assert 'architectures' in llm_config, "Should specify architecture in llm_config"
|
49 |
+
|
50 |
+
if isinstance(vision_config, dict):
|
51 |
+
self.vision_config = InternVisionConfig(**vision_config)
|
52 |
+
else:
|
53 |
+
self.vision_config = vision_config
|
54 |
+
|
55 |
+
if isinstance(llm_config, dict):
|
56 |
+
architecture: str = llm_config['architectures'][0]
|
57 |
+
if architecture == 'LlamaForCausalLM':
|
58 |
+
from transformers import LlamaConfig
|
59 |
+
self.llm_config = LlamaConfig(**llm_config)
|
60 |
+
elif architecture == 'Qwen2ForCausalLM':
|
61 |
+
from transformers import Qwen2Config
|
62 |
+
self.llm_config = Qwen2Config(**llm_config)
|
63 |
+
elif architecture == 'Qwen3MoeForCausalLM':
|
64 |
+
from transformers import Qwen3MoeConfig
|
65 |
+
self.llm_config = Qwen3MoeConfig(**llm_config)
|
66 |
+
elif architecture == 'Qwen3ForCausalLM':
|
67 |
+
from transformers import Qwen3Config
|
68 |
+
self.llm_config = Qwen3Config(**llm_config)
|
69 |
+
else:
|
70 |
+
raise ValueError('Unsupported architecture: {}'.format(architecture))
|
71 |
+
else:
|
72 |
+
self.llm_config = llm_config
|
73 |
+
|
74 |
+
self.use_backbone_lora = use_backbone_lora
|
75 |
+
self.use_llm_lora = use_llm_lora
|
76 |
+
self.select_layer = select_layer
|
77 |
+
self.force_image_size = force_image_size
|
78 |
+
self.downsample_ratio = downsample_ratio
|
79 |
+
self.template = template
|
80 |
+
self.dynamic_image_size = dynamic_image_size
|
81 |
+
self.use_thumbnail = use_thumbnail
|
82 |
+
self.ps_version = ps_version # pixel shuffle version
|
83 |
+
self.min_dynamic_patch = min_dynamic_patch
|
84 |
+
self.max_dynamic_patch = max_dynamic_patch
|
85 |
+
self.tie_word_embeddings = self.llm_config.tie_word_embeddings
|
86 |
+
|
87 |
+
logger.info(f'vision_select_layer: {self.select_layer}')
|
88 |
+
logger.info(f'ps_version: {self.ps_version}')
|
89 |
+
logger.info(f'min_dynamic_patch: {self.min_dynamic_patch}')
|
90 |
+
logger.info(f'max_dynamic_patch: {self.max_dynamic_patch}')
|
91 |
+
|
92 |
+
def to_dict(self):
|
93 |
+
"""
|
94 |
+
Serializes this instance to a Python dictionary. Override the default [`~PretrainedConfig.to_dict`].
|
95 |
+
|
96 |
+
Returns:
|
97 |
+
`Dict[str, any]`: Dictionary of all the attributes that make up this configuration instance,
|
98 |
+
"""
|
99 |
+
output = copy.deepcopy(self.__dict__)
|
100 |
+
output['vision_config'] = self.vision_config.to_dict()
|
101 |
+
output['llm_config'] = self.llm_config.to_dict()
|
102 |
+
output['model_type'] = self.__class__.model_type
|
103 |
+
output['use_backbone_lora'] = self.use_backbone_lora
|
104 |
+
output['use_llm_lora'] = self.use_llm_lora
|
105 |
+
output['select_layer'] = self.select_layer
|
106 |
+
output['force_image_size'] = self.force_image_size
|
107 |
+
output['downsample_ratio'] = self.downsample_ratio
|
108 |
+
output['template'] = self.template
|
109 |
+
output['dynamic_image_size'] = self.dynamic_image_size
|
110 |
+
output['use_thumbnail'] = self.use_thumbnail
|
111 |
+
output['ps_version'] = self.ps_version
|
112 |
+
output['min_dynamic_patch'] = self.min_dynamic_patch
|
113 |
+
output['max_dynamic_patch'] = self.max_dynamic_patch
|
114 |
+
|
115 |
+
return output
|
conversation.py
ADDED
@@ -0,0 +1,391 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Conversation prompt templates.
|
3 |
+
|
4 |
+
We kindly request that you import fastchat instead of copying this file if you wish to use it.
|
5 |
+
If you have changes in mind, please contribute back so the community can benefit collectively and continue to maintain these valuable templates.
|
6 |
+
|
7 |
+
Modified from https://github.com/lm-sys/FastChat/blob/main/fastchat/conversation.py
|
8 |
+
"""
|
9 |
+
|
10 |
+
import dataclasses
|
11 |
+
from enum import IntEnum, auto
|
12 |
+
from typing import Dict, List, Tuple, Union
|
13 |
+
|
14 |
+
|
15 |
+
class SeparatorStyle(IntEnum):
|
16 |
+
"""Separator styles."""
|
17 |
+
|
18 |
+
ADD_COLON_SINGLE = auto()
|
19 |
+
ADD_COLON_TWO = auto()
|
20 |
+
ADD_COLON_SPACE_SINGLE = auto()
|
21 |
+
NO_COLON_SINGLE = auto()
|
22 |
+
NO_COLON_TWO = auto()
|
23 |
+
ADD_NEW_LINE_SINGLE = auto()
|
24 |
+
LLAMA2 = auto()
|
25 |
+
CHATGLM = auto()
|
26 |
+
CHATML = auto()
|
27 |
+
CHATINTERN = auto()
|
28 |
+
DOLLY = auto()
|
29 |
+
RWKV = auto()
|
30 |
+
PHOENIX = auto()
|
31 |
+
ROBIN = auto()
|
32 |
+
FALCON_CHAT = auto()
|
33 |
+
CHATGLM3 = auto()
|
34 |
+
INTERNVL_ZH = auto()
|
35 |
+
MPT = auto()
|
36 |
+
|
37 |
+
|
38 |
+
@dataclasses.dataclass
|
39 |
+
class Conversation:
|
40 |
+
"""A class that manages prompt templates and keeps all conversation history."""
|
41 |
+
|
42 |
+
# The name of this template
|
43 |
+
name: str
|
44 |
+
# The template of the system prompt
|
45 |
+
system_template: str = '{system_message}'
|
46 |
+
# The system message
|
47 |
+
system_message: str = ''
|
48 |
+
# The names of two roles
|
49 |
+
roles: Tuple[str] = ('USER', 'ASSISTANT')
|
50 |
+
# All messages. Each item is (role, message).
|
51 |
+
messages: List[List[str]] = ()
|
52 |
+
# The number of few shot examples
|
53 |
+
offset: int = 0
|
54 |
+
# The separator style and configurations
|
55 |
+
sep_style: SeparatorStyle = SeparatorStyle.ADD_COLON_SINGLE
|
56 |
+
sep: str = '\n'
|
57 |
+
sep2: str = None
|
58 |
+
# Stop criteria (the default one is EOS token)
|
59 |
+
stop_str: Union[str, List[str]] = None
|
60 |
+
# Stops generation if meeting any token in this list
|
61 |
+
stop_token_ids: List[int] = None
|
62 |
+
|
63 |
+
def get_prompt(self) -> str:
|
64 |
+
"""Get the prompt for generation."""
|
65 |
+
system_prompt = self.system_template.format(system_message=self.system_message)
|
66 |
+
if self.sep_style == SeparatorStyle.ADD_COLON_SINGLE:
|
67 |
+
ret = system_prompt + self.sep
|
68 |
+
for role, message in self.messages:
|
69 |
+
if message:
|
70 |
+
ret += role + ': ' + message + self.sep
|
71 |
+
else:
|
72 |
+
ret += role + ':'
|
73 |
+
return ret
|
74 |
+
elif self.sep_style == SeparatorStyle.ADD_COLON_TWO:
|
75 |
+
seps = [self.sep, self.sep2]
|
76 |
+
ret = system_prompt + seps[0]
|
77 |
+
for i, (role, message) in enumerate(self.messages):
|
78 |
+
if message:
|
79 |
+
ret += role + ': ' + message + seps[i % 2]
|
80 |
+
else:
|
81 |
+
ret += role + ':'
|
82 |
+
return ret
|
83 |
+
elif self.sep_style == SeparatorStyle.ADD_COLON_SPACE_SINGLE:
|
84 |
+
ret = system_prompt + self.sep
|
85 |
+
for role, message in self.messages:
|
86 |
+
if message:
|
87 |
+
ret += role + ': ' + message + self.sep
|
88 |
+
else:
|
89 |
+
ret += role + ': ' # must be end with a space
|
90 |
+
return ret
|
91 |
+
elif self.sep_style == SeparatorStyle.ADD_NEW_LINE_SINGLE:
|
92 |
+
ret = '' if system_prompt == '' else system_prompt + self.sep
|
93 |
+
for role, message in self.messages:
|
94 |
+
if message:
|
95 |
+
ret += role + '\n' + message + self.sep
|
96 |
+
else:
|
97 |
+
ret += role + '\n'
|
98 |
+
return ret
|
99 |
+
elif self.sep_style == SeparatorStyle.NO_COLON_SINGLE:
|
100 |
+
ret = system_prompt
|
101 |
+
for role, message in self.messages:
|
102 |
+
if message:
|
103 |
+
ret += role + message + self.sep
|
104 |
+
else:
|
105 |
+
ret += role
|
106 |
+
return ret
|
107 |
+
elif self.sep_style == SeparatorStyle.NO_COLON_TWO:
|
108 |
+
seps = [self.sep, self.sep2]
|
109 |
+
ret = system_prompt
|
110 |
+
for i, (role, message) in enumerate(self.messages):
|
111 |
+
if message:
|
112 |
+
ret += role + message + seps[i % 2]
|
113 |
+
else:
|
114 |
+
ret += role
|
115 |
+
return ret
|
116 |
+
elif self.sep_style == SeparatorStyle.RWKV:
|
117 |
+
ret = system_prompt
|
118 |
+
for i, (role, message) in enumerate(self.messages):
|
119 |
+
if message:
|
120 |
+
ret += (
|
121 |
+
role
|
122 |
+
+ ': '
|
123 |
+
+ message.replace('\r\n', '\n').replace('\n\n', '\n')
|
124 |
+
)
|
125 |
+
ret += '\n\n'
|
126 |
+
else:
|
127 |
+
ret += role + ':'
|
128 |
+
return ret
|
129 |
+
elif self.sep_style == SeparatorStyle.LLAMA2:
|
130 |
+
seps = [self.sep, self.sep2]
|
131 |
+
if self.system_message:
|
132 |
+
ret = system_prompt
|
133 |
+
else:
|
134 |
+
ret = '[INST] '
|
135 |
+
for i, (role, message) in enumerate(self.messages):
|
136 |
+
tag = self.roles[i % 2]
|
137 |
+
if message:
|
138 |
+
if i == 0:
|
139 |
+
ret += message + ' '
|
140 |
+
else:
|
141 |
+
ret += tag + ' ' + message + seps[i % 2]
|
142 |
+
else:
|
143 |
+
ret += tag
|
144 |
+
return ret
|
145 |
+
elif self.sep_style == SeparatorStyle.CHATGLM:
|
146 |
+
# source: https://huggingface.co/THUDM/chatglm-6b/blob/1d240ba371910e9282298d4592532d7f0f3e9f3e/modeling_chatglm.py#L1302-L1308
|
147 |
+
# source2: https://huggingface.co/THUDM/chatglm2-6b/blob/e186c891cf64310ac66ef10a87e6635fa6c2a579/modeling_chatglm.py#L926
|
148 |
+
round_add_n = 1 if self.name == 'chatglm2' else 0
|
149 |
+
if system_prompt:
|
150 |
+
ret = system_prompt + self.sep
|
151 |
+
else:
|
152 |
+
ret = ''
|
153 |
+
|
154 |
+
for i, (role, message) in enumerate(self.messages):
|
155 |
+
if i % 2 == 0:
|
156 |
+
ret += f'[Round {i//2 + round_add_n}]{self.sep}'
|
157 |
+
|
158 |
+
if message:
|
159 |
+
ret += f'{role}:{message}{self.sep}'
|
160 |
+
else:
|
161 |
+
ret += f'{role}:'
|
162 |
+
return ret
|
163 |
+
elif self.sep_style == SeparatorStyle.CHATML:
|
164 |
+
ret = '' if system_prompt == '' else system_prompt + self.sep + '\n'
|
165 |
+
for role, message in self.messages:
|
166 |
+
if message:
|
167 |
+
ret += role + '\n' + message + self.sep + '\n'
|
168 |
+
else:
|
169 |
+
ret += role + '\n'
|
170 |
+
return ret
|
171 |
+
elif self.sep_style == SeparatorStyle.CHATGLM3:
|
172 |
+
ret = ''
|
173 |
+
if self.system_message:
|
174 |
+
ret += system_prompt
|
175 |
+
for role, message in self.messages:
|
176 |
+
if message:
|
177 |
+
ret += role + '\n' + ' ' + message
|
178 |
+
else:
|
179 |
+
ret += role
|
180 |
+
return ret
|
181 |
+
elif self.sep_style == SeparatorStyle.CHATINTERN:
|
182 |
+
# source: https://huggingface.co/internlm/internlm-chat-7b-8k/blob/bd546fa984b4b0b86958f56bf37f94aa75ab8831/modeling_internlm.py#L771
|
183 |
+
seps = [self.sep, self.sep2]
|
184 |
+
ret = system_prompt
|
185 |
+
for i, (role, message) in enumerate(self.messages):
|
186 |
+
# if i % 2 == 0:
|
187 |
+
# ret += "<s>"
|
188 |
+
if message:
|
189 |
+
ret += role + ':' + message + seps[i % 2] + '\n'
|
190 |
+
else:
|
191 |
+
ret += role + ':'
|
192 |
+
return ret
|
193 |
+
elif self.sep_style == SeparatorStyle.DOLLY:
|
194 |
+
seps = [self.sep, self.sep2]
|
195 |
+
ret = system_prompt
|
196 |
+
for i, (role, message) in enumerate(self.messages):
|
197 |
+
if message:
|
198 |
+
ret += role + ':\n' + message + seps[i % 2]
|
199 |
+
if i % 2 == 1:
|
200 |
+
ret += '\n\n'
|
201 |
+
else:
|
202 |
+
ret += role + ':\n'
|
203 |
+
return ret
|
204 |
+
elif self.sep_style == SeparatorStyle.PHOENIX:
|
205 |
+
ret = system_prompt
|
206 |
+
for role, message in self.messages:
|
207 |
+
if message:
|
208 |
+
ret += role + ': ' + '<s>' + message + '</s>'
|
209 |
+
else:
|
210 |
+
ret += role + ': ' + '<s>'
|
211 |
+
return ret
|
212 |
+
elif self.sep_style == SeparatorStyle.ROBIN:
|
213 |
+
ret = system_prompt + self.sep
|
214 |
+
for role, message in self.messages:
|
215 |
+
if message:
|
216 |
+
ret += role + ':\n' + message + self.sep
|
217 |
+
else:
|
218 |
+
ret += role + ':\n'
|
219 |
+
return ret
|
220 |
+
elif self.sep_style == SeparatorStyle.FALCON_CHAT:
|
221 |
+
ret = ''
|
222 |
+
if self.system_message:
|
223 |
+
ret += system_prompt + self.sep
|
224 |
+
for role, message in self.messages:
|
225 |
+
if message:
|
226 |
+
ret += role + ': ' + message + self.sep
|
227 |
+
else:
|
228 |
+
ret += role + ':'
|
229 |
+
|
230 |
+
return ret
|
231 |
+
elif self.sep_style == SeparatorStyle.INTERNVL_ZH:
|
232 |
+
seps = [self.sep, self.sep2]
|
233 |
+
ret = self.system_message + seps[0]
|
234 |
+
for i, (role, message) in enumerate(self.messages):
|
235 |
+
if message:
|
236 |
+
ret += role + ': ' + message + seps[i % 2]
|
237 |
+
else:
|
238 |
+
ret += role + ':'
|
239 |
+
return ret
|
240 |
+
elif self.sep_style == SeparatorStyle.MPT:
|
241 |
+
ret = system_prompt + self.sep
|
242 |
+
for role, message in self.messages:
|
243 |
+
if message:
|
244 |
+
if type(message) is tuple:
|
245 |
+
message, _, _ = message
|
246 |
+
ret += role + message + self.sep
|
247 |
+
else:
|
248 |
+
ret += role
|
249 |
+
return ret
|
250 |
+
else:
|
251 |
+
raise ValueError(f'Invalid style: {self.sep_style}')
|
252 |
+
|
253 |
+
def set_system_message(self, system_message: str):
|
254 |
+
"""Set the system message."""
|
255 |
+
self.system_message = system_message
|
256 |
+
|
257 |
+
def append_message(self, role: str, message: str):
|
258 |
+
"""Append a new message."""
|
259 |
+
self.messages.append([role, message])
|
260 |
+
|
261 |
+
def update_last_message(self, message: str):
|
262 |
+
"""Update the last output.
|
263 |
+
|
264 |
+
The last message is typically set to be None when constructing the prompt,
|
265 |
+
so we need to update it in-place after getting the response from a model.
|
266 |
+
"""
|
267 |
+
self.messages[-1][1] = message
|
268 |
+
|
269 |
+
def to_gradio_chatbot(self):
|
270 |
+
"""Convert the conversation to gradio chatbot format."""
|
271 |
+
ret = []
|
272 |
+
for i, (role, msg) in enumerate(self.messages[self.offset :]):
|
273 |
+
if i % 2 == 0:
|
274 |
+
ret.append([msg, None])
|
275 |
+
else:
|
276 |
+
ret[-1][-1] = msg
|
277 |
+
return ret
|
278 |
+
|
279 |
+
def to_openai_api_messages(self):
|
280 |
+
"""Convert the conversation to OpenAI chat completion format."""
|
281 |
+
ret = [{'role': 'system', 'content': self.system_message}]
|
282 |
+
|
283 |
+
for i, (_, msg) in enumerate(self.messages[self.offset :]):
|
284 |
+
if i % 2 == 0:
|
285 |
+
ret.append({'role': 'user', 'content': msg})
|
286 |
+
else:
|
287 |
+
if msg is not None:
|
288 |
+
ret.append({'role': 'assistant', 'content': msg})
|
289 |
+
return ret
|
290 |
+
|
291 |
+
def copy(self):
|
292 |
+
return Conversation(
|
293 |
+
name=self.name,
|
294 |
+
system_template=self.system_template,
|
295 |
+
system_message=self.system_message,
|
296 |
+
roles=self.roles,
|
297 |
+
messages=[[x, y] for x, y in self.messages],
|
298 |
+
offset=self.offset,
|
299 |
+
sep_style=self.sep_style,
|
300 |
+
sep=self.sep,
|
301 |
+
sep2=self.sep2,
|
302 |
+
stop_str=self.stop_str,
|
303 |
+
stop_token_ids=self.stop_token_ids,
|
304 |
+
)
|
305 |
+
|
306 |
+
def dict(self):
|
307 |
+
return {
|
308 |
+
'template_name': self.name,
|
309 |
+
'system_message': self.system_message,
|
310 |
+
'roles': self.roles,
|
311 |
+
'messages': self.messages,
|
312 |
+
'offset': self.offset,
|
313 |
+
}
|
314 |
+
|
315 |
+
|
316 |
+
# A global registry for all conversation templates
|
317 |
+
conv_templates: Dict[str, Conversation] = {}
|
318 |
+
|
319 |
+
|
320 |
+
def register_conv_template(template: Conversation, override: bool = False):
|
321 |
+
"""Register a new conversation template."""
|
322 |
+
if not override:
|
323 |
+
assert (
|
324 |
+
template.name not in conv_templates
|
325 |
+
), f'{template.name} has been registered.'
|
326 |
+
|
327 |
+
conv_templates[template.name] = template
|
328 |
+
|
329 |
+
|
330 |
+
def get_conv_template(name: str) -> Conversation:
|
331 |
+
"""Get a conversation template."""
|
332 |
+
return conv_templates[name].copy()
|
333 |
+
|
334 |
+
|
335 |
+
# Both Hermes-2 and internlm2-chat are chatml-format conversation templates. The difference
|
336 |
+
# is that during training, the preprocessing function for the Hermes-2 template doesn't add
|
337 |
+
# <s> at the beginning of the tokenized sequence, while the internlm2-chat template does.
|
338 |
+
# Therefore, they are completely equivalent during inference.
|
339 |
+
register_conv_template(
|
340 |
+
Conversation(
|
341 |
+
name='Hermes-2',
|
342 |
+
system_template='<|im_start|>system\n{system_message}',
|
343 |
+
# note: The new system prompt was not used here to avoid changes in benchmark performance.
|
344 |
+
# system_message='我是书生·万象,英文名是InternVL,是由上海人工智能实验室、清华大学及多家合作单位联合开发的多模态大语言模型。',
|
345 |
+
system_message='你是由上海人工智能实验室联合商汤科技开发的书生多模态大模型,英文名叫InternVL, 是一个有用无害的人工智能助手。',
|
346 |
+
roles=('<|im_start|>user\n', '<|im_start|>assistant\n'),
|
347 |
+
sep_style=SeparatorStyle.MPT,
|
348 |
+
sep='<|im_end|>',
|
349 |
+
stop_str='<|endoftext|>',
|
350 |
+
)
|
351 |
+
)
|
352 |
+
|
353 |
+
|
354 |
+
register_conv_template(
|
355 |
+
Conversation(
|
356 |
+
name='internlm2-chat',
|
357 |
+
system_template='<|im_start|>system\n{system_message}',
|
358 |
+
# note: The new system prompt was not used here to avoid changes in benchmark performance.
|
359 |
+
# system_message='我是书生·万象,英文名是InternVL,是由上海人工智能实验室、清华大学及多家合作单位联合开发的多模态大语言模型。',
|
360 |
+
system_message='你是由上海人工智能实验室联合商汤科技开发的书生多模态大模型,英文名叫InternVL, 是一个有用无害的人工智能助手。',
|
361 |
+
roles=('<|im_start|>user\n', '<|im_start|>assistant\n'),
|
362 |
+
sep_style=SeparatorStyle.MPT,
|
363 |
+
sep='<|im_end|>',
|
364 |
+
)
|
365 |
+
)
|
366 |
+
|
367 |
+
|
368 |
+
register_conv_template(
|
369 |
+
Conversation(
|
370 |
+
name='phi3-chat',
|
371 |
+
system_template='<|system|>\n{system_message}',
|
372 |
+
# note: The new system prompt was not used here to avoid changes in benchmark performance.
|
373 |
+
# system_message='我是书生·万象,英文名是InternVL,是由上海人工智能实验室、清华大学及多家合作单位联合开发的多模态大语言模型。',
|
374 |
+
system_message='你是由上海人工智能实验室联合商汤科技开发的书生多模态大模型,英文名叫InternVL, 是一个有用无害的人工智能助手。',
|
375 |
+
roles=('<|user|>\n', '<|assistant|>\n'),
|
376 |
+
sep_style=SeparatorStyle.MPT,
|
377 |
+
sep='<|end|>',
|
378 |
+
)
|
379 |
+
)
|
380 |
+
|
381 |
+
|
382 |
+
register_conv_template(
|
383 |
+
Conversation(
|
384 |
+
name='internvl2_5',
|
385 |
+
system_template='<|im_start|>system\n{system_message}',
|
386 |
+
system_message='你是书生·万象,英文名是InternVL,是由上海人工智能实验室、清华大学及多家合作单位联合开发的多模态大语言模型。',
|
387 |
+
roles=('<|im_start|>user\n', '<|im_start|>assistant\n'),
|
388 |
+
sep_style=SeparatorStyle.MPT,
|
389 |
+
sep='<|im_end|>\n',
|
390 |
+
)
|
391 |
+
)
|
generation_config.json
ADDED
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"_from_model_config": true,
|
3 |
+
"transformers_version": "4.52.1"
|
4 |
+
}
|
layer-0-ep-0-of-1.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:d1c5964ec3bc0d9269e0900f12e15e8f3e885c472eb5d6999fa465f21928da72
|
3 |
+
size 4975564552
|
layer-1-ep-0-of-1.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:3c62856d71fcafa428dc1270afb37b7777ac78af7448284ac2ca51a5b4d21d68
|
3 |
+
size 4975564552
|
layer-10-ep-0-of-1.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:9bd0fa7bc3c228cd0522ea36f310f78afedad0998cfb7a4a3ba6584adaca3e25
|
3 |
+
size 4975564952
|
layer-11-ep-0-of-1.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:bcd7f6f4c5fcb25a23eb32edaf226075c6b256d0c5248945ea810c49d8d516a8
|
3 |
+
size 4975564952
|
layer-12-ep-0-of-1.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:063aed583e53fd4cf2cff704da0f083bf265ad8e88e80b417e3ef3a2af911fce
|
3 |
+
size 4975564952
|
layer-13-ep-0-of-1.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:ad8363413511f1c82d94a796d6d3a0c93d5a2f48c7439cd18eb17124567dc811
|
3 |
+
size 4975564952
|
layer-14-ep-0-of-1.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:901f6ee47fcbd810636be20dca0365d66257a1f72a055b721fee4ad0cb137738
|
3 |
+
size 4975564952
|
layer-15-ep-0-of-1.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:341403e4368e395de88e3238c7cb5b5b65a992d54d2ca8dd1e1b283bb6592b99
|
3 |
+
size 4975564952
|
layer-16-ep-0-of-1.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:9aa39f30fbfcba591a3cf9240414725b6571e29a60c9b8e672e5128a91922013
|
3 |
+
size 4975564952
|
layer-17-ep-0-of-1.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:c0b67d485c9aa9eddca515deae727ce8becf0f2b6ac82324e75743c104577389
|
3 |
+
size 4975564952
|
layer-18-ep-0-of-1.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:9f91998b9b14357214019f776963a361acabff49ff0e288245c921231093091d
|
3 |
+
size 4975564952
|
layer-19-ep-0-of-1.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:f97ca57d677295ac26e8d1490ee0d33ec2f43ce38b69da611e20fef97e29c842
|
3 |
+
size 4975564952
|
layer-2-ep-0-of-1.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:f751618fa9175b204e0e5d7c171f6c6d9312ecb3647d8bf12c8706acef2925a0
|
3 |
+
size 4975564552
|
layer-20-ep-0-of-1.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:a05c91f079ca268cabd090ded0203b4959d02daab20f409a3182eac600b91947
|
3 |
+
size 4975564952
|
layer-21-ep-0-of-1.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:8631b4153de1c67aff0f520314034ad798c0f496b796f61afa4493619ef2424b
|
3 |
+
size 4975564952
|
layer-22-ep-0-of-1.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:28760e3ad8671cde11a94214f6d4aa901b4db54b39d7d531bf3d4b3c00c17353
|
3 |
+
size 4975564952
|
layer-23-ep-0-of-1.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:ce50e31e8eb7d60784ccabebbe757c317119b22a7541730d7962e999ac23a9ad
|
3 |
+
size 4975564952
|
layer-24-ep-0-of-1.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:0513527296bd05d547b99b1443d2333ae5a28419617c26ab14dc03c6fec5c140
|
3 |
+
size 4975564952
|
layer-25-ep-0-of-1.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:9c576038ee80cd68494ae9a9b56a855631976d3a4cc87df1f43809bb296a3141
|
3 |
+
size 4975564952
|
layer-26-ep-0-of-1.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:e426c1ce0eab46760b5dd4513ae5f0f703c8574a0991422609c6a7a389bfffde
|
3 |
+
size 4975564952
|
layer-27-ep-0-of-1.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:64652ac15aca6bd110897f6141d1d10245f892acfc4c23dd8c495c757e2e0e6e
|
3 |
+
size 4975564952
|
layer-28-ep-0-of-1.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:673291af4d7dfd0e95d52ac8eb8354ab560108b68f833b7aff23f201a588b0e7
|
3 |
+
size 4975564952
|
layer-29-ep-0-of-1.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:381c6d89de9cb840a8897b2d21361bb54fd6f702fbe11dece7219714012679c9
|
3 |
+
size 4975564952
|
layer-3-ep-0-of-1.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:00e14da6e4387e58f9c869f72387789dadbc05f0e9b5c4603bfeae73e6c3543c
|
3 |
+
size 4975564552
|
layer-30-ep-0-of-1.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:094bf526a4d82dda4a8697c9fe0bb6b126512f73dad90bcd038c034d12b2a215
|
3 |
+
size 4975564952
|
layer-31-ep-0-of-1.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:2302adfd6d5c0e066404a205bb4ed5e1b0dfb6f29db55ace99c06e2376893c34
|
3 |
+
size 4975564952
|
layer-32-ep-0-of-1.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:060f7eb84619b648ed5c678e8d04909943dc767723d1649f6301454f8ae9762b
|
3 |
+
size 4975564952
|
layer-33-ep-0-of-1.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:ad4b71d14f235f93a38d1dbf9ae64978489fac23f2fd03309aebd3efc12ab0b6
|
3 |
+
size 4975564952
|
layer-34-ep-0-of-1.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:a64ab52f93bec2d37ac4e20bce66f059c1aafa342428cea45d609ebbc4ba26aa
|
3 |
+
size 4975564952
|
layer-35-ep-0-of-1.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:6342df0293fe08610756f496fa236f33650967f55912a06fd3fe495e92496fcc
|
3 |
+
size 4975564952
|
layer-36-ep-0-of-1.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:42a78a18a35bab2bbb9b41d067734c1cc02f84d84c17f373642f66eece1a8a09
|
3 |
+
size 4975564952
|
layer-37-ep-0-of-1.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:742a350713313c1b44a794413325028829e8c99197db8ac0df44b386bd164039
|
3 |
+
size 4975564952
|
layer-38-ep-0-of-1.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:19aa3fecbd18b3b72a6c95895417c12e8b1456a7cdba06886ceb969c1057da08
|
3 |
+
size 4975564952
|
layer-39-ep-0-of-1.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:a562868996299db5c731715930db1cf720d69c1161eebf262834a5e73e0946cf
|
3 |
+
size 4975564952
|
layer-4-ep-0-of-1.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:3f2994d243f5be74ec14aec95bb17861a9b21e69c9daa0e6d854c922b1bbc9f6
|
3 |
+
size 4975564552
|
layer-40-ep-0-of-1.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:d6a77b7fa59facaa6b00d7a26f0d238d2475da77a2d3dfcb4496397b4b122589
|
3 |
+
size 4975564952
|
layer-41-ep-0-of-1.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:6454066901f8a88cc422702031ad76d75d5a586198a70abf7d655e346a0f4aa9
|
3 |
+
size 4975564952
|
layer-42-ep-0-of-1.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:06ff8f4a32fc69a721cb277ab4ef60cb001865add25568544c0ebeb3502d9807
|
3 |
+
size 4975564952
|
layer-43-ep-0-of-1.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:d5706652e4a3c8815b0f3284b48cdfeaa2275a03f4e3feb91fa020a74f259665
|
3 |
+
size 4975564952
|
layer-44-ep-0-of-1.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:0ff006160dccf446077ef1d50260ae1cb7ae4885be6aa7f5eea95e924c668960
|
3 |
+
size 4975564952
|
layer-45-ep-0-of-1.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:57dcf30fd0e448253f0995c2ef0363b1ac99e26d46406efb0377ce3ea305e9b4
|
3 |
+
size 4975564952
|