Felipe97 commited on
Commit
1e18f83
·
verified ·
1 Parent(s): 4995784

Upload folder using huggingface_hub (part 7)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
.gitattributes CHANGED
@@ -51,3 +51,5 @@ build/tools/ui/dist/recommended-mcp/huggingface.ico filter=lfs diff=lfs merge=lf
51
  build/tools/ui/ui-gzip/_gzip/_app/immutable/assets/bundle.oAmIsIaD.css filter=lfs diff=lfs merge=lfs -text
52
  build/tools/ui/ui-gzip/_gzip/_app/immutable/bundle.IcoPeDQ-.js filter=lfs diff=lfs merge=lfs -text
53
  build/tools/ui/ui.cpp filter=lfs diff=lfs merge=lfs -text
 
 
 
51
  build/tools/ui/ui-gzip/_gzip/_app/immutable/assets/bundle.oAmIsIaD.css filter=lfs diff=lfs merge=lfs -text
52
  build/tools/ui/ui-gzip/_gzip/_app/immutable/bundle.IcoPeDQ-.js filter=lfs diff=lfs merge=lfs -text
53
  build/tools/ui/ui.cpp filter=lfs diff=lfs merge=lfs -text
54
+ docs/android/imported-into-android-studio.jpg filter=lfs diff=lfs merge=lfs -text
55
+ docs/development/llama-star/idea-arch.key filter=lfs diff=lfs merge=lfs -text
common/parsers/minimax-m3.cpp ADDED
@@ -0,0 +1,229 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "parsers.h"
2
+
3
+ common_chat_params common_chat_params_init_minimax_m3(const common_chat_template & tmpl,
4
+ const autoparser::generation_params & inputs) {
5
+ common_chat_params data;
6
+
7
+ data.prompt = common_chat_template_direct_apply_impl(tmpl, inputs);
8
+ data.generation_prompt = common_chat_template_generation_prompt_impl(tmpl, inputs);
9
+ data.format = COMMON_CHAT_FORMAT_PEG_MINIMAX_M3;
10
+ data.supports_thinking = true;
11
+ data.thinking_start_tag = "<mm:think>";
12
+ data.thinking_end_tags = {"</mm:think>"};
13
+
14
+ // M3 prefixes every tool tag with the namespace token "]<]minimax[>[";
15
+ // params use the parameter name as the tag (<file_path>...</file_path>).
16
+ const std::string NS = "]<]minimax[>[";
17
+ const std::string THINK_START = "<mm:think>";
18
+ const std::string THINK_END = "</mm:think>";
19
+ const std::string FC_START = NS + "<tool_call>";
20
+ const std::string FC_END = NS + "</tool_call>";
21
+ const std::string INVOKE_END = NS + "</invoke>";
22
+
23
+ data.preserved_tokens = {
24
+ NS,
25
+ "<tool_call>",
26
+ "</tool_call>",
27
+ THINK_START,
28
+ THINK_END,
29
+ };
30
+
31
+ data.message_delimiters = {
32
+ { COMMON_CHAT_ROLE_ASSISTANT, "]~b]ai" },
33
+ { COMMON_CHAT_ROLE_USER, "]~b]user" },
34
+ { COMMON_CHAT_ROLE_TOOL, "]~b]tool" },
35
+ { COMMON_CHAT_ROLE_SYSTEM, "]~b]developer" },
36
+ { COMMON_CHAT_ROLE_SYSTEM, "]~b]system" },
37
+ };
38
+
39
+ auto has_tools = inputs.tools.is_array() && !inputs.tools.empty();
40
+ auto has_response_format = !inputs.json_schema.is_null() && inputs.json_schema.is_object();
41
+ auto extract_reasoning = inputs.reasoning_format != COMMON_REASONING_FORMAT_NONE;
42
+ auto include_grammar = has_response_format || (has_tools && inputs.tool_choice != COMMON_CHAT_TOOL_CHOICE_NONE);
43
+
44
+ const std::string GEN_PROMPT = data.generation_prompt;
45
+
46
+ using mm3 = common_chat_peg_minimax_m3_mapper;
47
+
48
+ if (inputs.has_continuation()) {
49
+ const auto & msg = inputs.continue_msg;
50
+
51
+ data.generation_prompt = GEN_PROMPT + THINK_START + msg.reasoning_content;
52
+ if (inputs.continue_final_message == COMMON_CHAT_CONTINUATION_CONTENT) {
53
+ data.generation_prompt += THINK_END + msg.render_content();
54
+ }
55
+
56
+ data.prompt += data.generation_prompt;
57
+ }
58
+
59
+ auto parser = build_chat_peg_parser([&](common_chat_peg_builder & p) {
60
+ auto generation_prompt = p.prefix(GEN_PROMPT, THINK_START);
61
+ auto end = p.end();
62
+
63
+ auto reasoning = p.eps();
64
+ if (extract_reasoning) {
65
+ auto block = inputs.enable_thinking
66
+ ? p.literal(THINK_START) + p.space() +
67
+ p.ac(p.reasoning(p.until(THINK_END)) + p.literal(THINK_END), THINK_END)
68
+ : p.literal(THINK_START) + p.ac(p.until(THINK_END) + p.literal(THINK_END), THINK_END);
69
+
70
+ // A turn without reasoning is prefixed with a bare </mm:think>, written either by the
71
+ // generation prompt (thinking_mode = "disabled") or by the model itself.
72
+ reasoning = p.optional(p.choice({ block, p.literal(THINK_END) }));
73
+ }
74
+
75
+ if (has_response_format) {
76
+ auto response_format = p.rule("response-format",
77
+ p.literal("```json") + p.space() +
78
+ p.content(p.schema(p.json(), "response-format-schema", inputs.json_schema)) +
79
+ p.space() + p.literal("```"));
80
+ return generation_prompt + reasoning + response_format + end;
81
+ }
82
+
83
+ if (!has_tools || inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_NONE) {
84
+ return generation_prompt + reasoning + p.content(p.rest()) + end;
85
+ }
86
+
87
+ auto tool_choice = p.choice();
88
+ foreach_function(inputs.tools, [&](const json & tool) {
89
+ const auto & function = tool.at("function");
90
+ std::string name = function.at("name");
91
+ auto params = common_chat_tool_parameters(function);
92
+ auto doc = std::make_shared<const common_chat_schema_document>(common_chat_schema_from_json(params));
93
+
94
+ // The template expands argument values recursively in XML (see the to_xml() macro)
95
+ std::function<common_peg_parser(const common_chat_schema &, const std::string &, const std::string &)> value_of;
96
+ std::function<common_peg_parser(const common_chat_schema_object &, const std::string &)> members_of;
97
+
98
+ auto element_of = [&](const std::string & tag, const common_chat_schema & schema, const std::string & rule_name) {
99
+ const std::string close = NS + "</" + tag + ">";
100
+ return p.rule(rule_name,
101
+ p.tool_arg(
102
+ p.tool_arg_open(
103
+ p.literal(NS + "<") +
104
+ p.tool_arg_name(p.literal(tag)) +
105
+ p.literal(">")) +
106
+ value_of(schema, rule_name, close)));
107
+ };
108
+
109
+ value_of = [&](const common_chat_schema & schema,
110
+ const std::string & rule_name,
111
+ const std::string & close) -> common_peg_parser {
112
+ auto close_tag = p.tool_arg_close(p.literal(close));
113
+
114
+ // A string accepts anything, so a union with a string alternative is a string
115
+ if (schema.may_be_string()) {
116
+ return p.ac(p.tool_arg_string_value(p.until(close)) + close_tag, close);
117
+ }
118
+
119
+ if (schema.kind() == common_chat_schema::KIND_ANY_OF) {
120
+ std::vector<common_peg_parser> choices;
121
+
122
+ size_t index = 0;
123
+ for (const auto & alternative : static_cast<const common_chat_schema_any_of &>(schema).children) {
124
+ const std::string alt_name = rule_name + "-" + std::to_string(index++);
125
+
126
+ // There is a risk that this breaks streaming deltas, but that's a risk we
127
+ // assume to provide tool arg streaming.
128
+ choices.push_back(value_of(*alternative, alt_name, close));
129
+ }
130
+
131
+ return p.choice(choices);
132
+ }
133
+
134
+ if (schema.kind() == common_chat_schema::KIND_OBJECT) {
135
+ const auto & object = static_cast<const common_chat_schema_object &>(schema);
136
+ if (!object.properties.empty()) {
137
+ return p.tag(mm3::TOOL_ARG_OBJECT, members_of(object, rule_name)) + p.space() + close_tag;
138
+ }
139
+ }
140
+
141
+ if (schema.kind() == common_chat_schema::KIND_ARRAY) {
142
+ const std::string item_close = NS + "</item>";
143
+ auto item = p.rule(rule_name + "-item",
144
+ p.tag(mm3::TOOL_ARG_ITEM,
145
+ p.literal(NS + "<item>") +
146
+ value_of(*static_cast<const common_chat_schema_array &>(schema).items, rule_name + "-item", item_close)));
147
+ return p.tag(mm3::TOOL_ARG_ARRAY, p.repeat(p.space() + item, 0, -1)) + p.space() + close_tag;
148
+ }
149
+
150
+ return p.tool_arg_json_value(p.schema(p.json(), rule_name + "-schema", doc, schema)) + close_tag;
151
+ };
152
+
153
+ // Required properties in schema order, then any number of optional ones in any order.
154
+ members_of = [&](const common_chat_schema_object & object, const std::string & rule_prefix) -> common_peg_parser {
155
+ std::vector<common_peg_parser> required_elements;
156
+ std::vector<common_peg_parser> optional_elements;
157
+ for (const auto & prop : object.properties) {
158
+ auto element = element_of(prop.name, *prop.schema, rule_prefix + "-" + prop.name);
159
+ (prop.required ? required_elements : optional_elements).push_back(element);
160
+ }
161
+
162
+ common_peg_parser members = p.eps();
163
+ for (size_t i = 0; i < required_elements.size(); i++) {
164
+ if (i > 0) {
165
+ members = members + p.space();
166
+ }
167
+ members = members + required_elements[i];
168
+ }
169
+
170
+ if (!optional_elements.empty()) {
171
+ common_peg_parser any_optional = p.choice();
172
+ for (const auto & element : optional_elements) {
173
+ any_optional |= element;
174
+ }
175
+ members = members + p.repeat(p.space() + any_optional, 0, -1);
176
+ }
177
+
178
+ return members;
179
+ };
180
+
181
+ common_peg_parser invoke_body = p.eps();
182
+ if (doc->root->kind() == common_chat_schema::KIND_OBJECT) {
183
+ invoke_body = members_of(static_cast<const common_chat_schema_object &>(*doc->root), "tool-" + name + "-arg");
184
+ }
185
+
186
+ auto func_parser = p.tool(
187
+ p.tool_open(p.literal(NS + "<invoke name=\"") +
188
+ p.tool_name(p.literal(name)) + p.literal("\">")) +
189
+ p.space() + invoke_body + p.space() +
190
+ p.tool_close(p.literal(INVOKE_END)));
191
+
192
+ tool_choice |= p.rule("tool-" + name, func_parser);
193
+ });
194
+
195
+ auto require_tools = inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_REQUIRED;
196
+
197
+ common_peg_parser tool_calls = p.eps();
198
+ if (inputs.parallel_tool_calls) {
199
+ tool_calls = p.trigger_rule("tool-call",
200
+ p.literal(FC_START) + p.space() + tool_choice +
201
+ p.zero_or_more(p.space() + tool_choice) + p.space() + p.literal(FC_END));
202
+ } else {
203
+ tool_calls = p.trigger_rule("tool-call",
204
+ p.literal(FC_START) + p.space() + tool_choice + p.space() + p.literal(FC_END));
205
+ }
206
+
207
+ if (!require_tools) {
208
+ tool_calls = p.optional(tool_calls);
209
+ }
210
+
211
+ auto content_before_tools = p.content(p.until(FC_START));
212
+ return generation_prompt + reasoning + content_before_tools + tool_calls + end;
213
+ });
214
+
215
+ data.parser = parser.save();
216
+
217
+ if (include_grammar) {
218
+ data.grammar_lazy = !(has_response_format || (has_tools && inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_REQUIRED));
219
+ data.grammar = build_grammar([&](const common_grammar_builder & builder) {
220
+ parser.build_grammar(builder, data.grammar_lazy);
221
+ });
222
+
223
+ data.grammar_triggers = {
224
+ { COMMON_GRAMMAR_TRIGGER_TYPE_WORD, FC_START },
225
+ };
226
+ }
227
+
228
+ return data;
229
+ }
common/parsers/ministral3.cpp ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "parsers.h"
2
+
3
+ common_chat_params common_chat_params_init_ministral_3(const common_chat_template & tmpl,
4
+ const autoparser::generation_params & inputs) {
5
+ common_chat_params data;
6
+
7
+ // Build up messages to follow the format: https://huggingface.co/mistralai/Ministral-3-14B-Reasoning-2512/blob/main/chat_template.jinja
8
+ auto adjusted_messages = json::array();
9
+ for (const auto & msg : inputs.messages) {
10
+ auto role = msg.value("role", "");
11
+ if (role != "system" && role != "assistant") {
12
+ // Only adjust system and assistant messages. Interestingly, the system message may contain thinking.
13
+ adjusted_messages.push_back(msg);
14
+ continue;
15
+ }
16
+
17
+ auto content = json::array();
18
+
19
+ // If message contains `reasoning_content`, add it as a block of type `thinking`
20
+ if (msg.contains("reasoning_content") && msg.at("reasoning_content").is_string()) {
21
+ content.push_back({
22
+ { "type", "thinking" },
23
+ { "thinking", msg.at("reasoning_content").get<std::string>() },
24
+ });
25
+ }
26
+
27
+ // If message contains `content`, add it as a block of type `text`
28
+ if (msg.contains("content")) {
29
+ if (msg.at("content").is_string()) {
30
+ content.push_back({
31
+ { "type", "text" },
32
+ { "text", msg.at("content").get<std::string>() },
33
+ });
34
+ } else if (msg.at("content").is_array()) {
35
+ auto blocks = msg.at("content");
36
+ content.insert(blocks);
37
+ }
38
+ }
39
+
40
+ auto adjusted = msg;
41
+ adjusted["content"] = content;
42
+ adjusted.erase("reasoning_content");
43
+ adjusted_messages.push_back(adjusted);
44
+ }
45
+
46
+ auto has_tools = inputs.tools.is_array() && !inputs.tools.empty();
47
+ auto has_response_format = inputs.json_schema.is_object() && !inputs.json_schema.empty();
48
+ auto extract_reasoning = inputs.reasoning_format != COMMON_REASONING_FORMAT_NONE;
49
+ auto include_grammar = true;
50
+
51
+ data.supports_thinking = true;
52
+ data.thinking_start_tag = "[THINK]";
53
+ data.thinking_end_tags = {"[/THINK]"};
54
+ data.prompt = common_chat_template_direct_apply_impl(tmpl, inputs, /* messages_override = */ adjusted_messages);
55
+ data.generation_prompt = common_chat_template_generation_prompt_impl(tmpl, inputs, /* messages_override = */ adjusted_messages);
56
+ data.format = COMMON_CHAT_FORMAT_PEG_NATIVE;
57
+ data.preserved_tokens = {
58
+ "[THINK]",
59
+ "[/THINK]",
60
+ "[TOOL_CALLS]",
61
+ "[ARGS]",
62
+ };
63
+
64
+ if (inputs.has_continuation()) {
65
+ const auto & msg = inputs.continue_msg;
66
+
67
+ data.generation_prompt = "[THINK]" + msg.reasoning_content;
68
+ if (inputs.continue_final_message == COMMON_CHAT_CONTINUATION_CONTENT) {
69
+ data.generation_prompt += "[/THINK]" + msg.render_content();
70
+ }
71
+
72
+ data.prompt += data.generation_prompt;
73
+ }
74
+
75
+ auto parser = build_chat_peg_parser([&](common_chat_peg_builder & p) {
76
+ auto generation_prompt = p.eps();
77
+ auto reasoning =
78
+ extract_reasoning ? p.optional("[THINK]" + p.reasoning(p.until("[/THINK]")) + "[/THINK]") : p.eps();
79
+
80
+ // Response format parser
81
+ if (has_response_format) {
82
+ // Ministral wants to emit json surrounded by code fences
83
+ return generation_prompt + (reasoning << "```json" << p.content(p.schema(p.json(), "response-format", inputs.json_schema)) << "```");
84
+ }
85
+
86
+ // Tool call parser
87
+ if (has_tools && inputs.tool_choice != COMMON_CHAT_TOOL_CHOICE_NONE) {
88
+ auto tool_choice = p.choice();
89
+ foreach_function(inputs.tools, [&](const json & tool) {
90
+ const auto & function = tool.at("function");
91
+ std::string name = function.at("name");
92
+ const auto schema = common_chat_tool_parameters(function);
93
+
94
+ tool_choice |=
95
+ p.rule("tool-" + name, p.tool_open(p.tool_name(p.literal(name)) + "[ARGS]") +
96
+ p.tool_args(p.schema(p.json(), "tool-" + name + "-schema", schema)));
97
+ });
98
+
99
+ auto min_calls = inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_REQUIRED ? 1 : 0;
100
+ auto max_calls = inputs.parallel_tool_calls ? -1 : 1;
101
+ auto tool_calls = p.trigger_rule("tool-call", p.repeat("[TOOL_CALLS]" + tool_choice, min_calls, max_calls));
102
+
103
+ return generation_prompt + (reasoning << p.content(p.until("[TOOL_CALLS]")) << tool_calls);
104
+ }
105
+
106
+ // Content only parser
107
+ include_grammar = false;
108
+ return generation_prompt + (reasoning << p.content(p.rest()));
109
+ });
110
+
111
+ data.parser = parser.save();
112
+
113
+ if (include_grammar) {
114
+ data.grammar_lazy = has_tools && inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_AUTO;
115
+
116
+ data.grammar = build_grammar([&](const common_grammar_builder & builder) {
117
+ parser.build_grammar(builder, data.grammar_lazy);
118
+ });
119
+
120
+ data.grammar_triggers = {
121
+ { COMMON_GRAMMAR_TRIGGER_TYPE_WORD, "[TOOL_CALLS]" }
122
+ };
123
+ }
124
+
125
+ return data;
126
+ }
common/parsers/muse-glimmer.cpp ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "parsers.h"
2
+
3
+ // An assistant turn is rendered as one or more messages, each
4
+ // "<|start|>assistant to=<recipient><|message|>{content}{END}" where END is
5
+ // <|eom|> (more messages follow) or <|eot|> (end of turn):
6
+ // - chain-of-thought: to=self, terminated by <|eom|>
7
+ // - final answer: to=user, terminated by <|eot|>
8
+ // The generation prompt is just "<|start|>assistant"; the model emits its own
9
+ // " to=...<|message|>".
10
+ common_chat_params common_chat_params_init_muse_glimmer(const common_chat_template & tmpl,
11
+ const autoparser::generation_params & inputs) {
12
+ common_chat_params data;
13
+
14
+ data.prompt = common_chat_template_direct_apply_impl(tmpl, inputs);
15
+ data.generation_prompt = "<|start|>assistant";
16
+ data.format = COMMON_CHAT_FORMAT_PEG_NATIVE;
17
+ data.supports_thinking = true;
18
+
19
+ data.preserved_tokens = {
20
+ "<|start|>", "<|message|>", "<|eom|>", "<|eot|>",
21
+ // ATEM tool-call markup emitted on " to=<tool>" turns.
22
+ "<atem:function_calls>", "<atem:invoke", "<atem:parameter", "</atem:parameter>",
23
+ "</atem:invoke>", "</atem:function_calls>",
24
+ };
25
+
26
+ data.message_delimiters = {
27
+ { COMMON_CHAT_ROLE_ASSISTANT, "<|start|>assistant" },
28
+ { COMMON_CHAT_ROLE_USER, "<|start|>user" },
29
+ { COMMON_CHAT_ROLE_SYSTEM, "<|start|>system" },
30
+ { COMMON_CHAT_ROLE_TOOL, "<|start|>tool" },
31
+ };
32
+
33
+ if (inputs.has_continuation()) {
34
+ const auto & msg = inputs.continue_msg;
35
+
36
+ data.generation_prompt = "<|start|>assistant to=self<|message|>" + msg.reasoning_content;
37
+ if (inputs.continue_final_message == COMMON_CHAT_CONTINUATION_CONTENT) {
38
+ data.generation_prompt += "<|eom|><|start|>assistant to=user<|message|>" + msg.render_content();
39
+ }
40
+
41
+ data.prompt += data.generation_prompt;
42
+ }
43
+
44
+ auto extract_reasoning = inputs.reasoning_format != COMMON_REASONING_FORMAT_NONE;
45
+
46
+ auto has_tools = inputs.tools.is_array() && !inputs.tools.empty();
47
+ // Constrained grammar whenever tools are offered.
48
+ auto include_grammar = has_tools && inputs.tool_choice != COMMON_CHAT_TOOL_CHOICE_NONE;
49
+
50
+ auto parser = build_chat_peg_parser([&](common_chat_peg_builder & p) {
51
+ auto start = p.rule("start", p.literal("<|start|>assistant"));
52
+
53
+ if (!extract_reasoning && !include_grammar) {
54
+ return start + p.content(p.rest());
55
+ }
56
+
57
+ if (extract_reasoning) {
58
+ p.rule("analysis", p.literal(" to=self<|message|>") + p.reasoning(p.until("<|eom|>")) + p.literal("<|eom|>"));
59
+ } else {
60
+ p.rule("analysis", p.literal(" to=self<|message|>") + p.content(p.until("<|eom|>")) + p.literal("<|eom|>"));
61
+ }
62
+ auto analysis = p.ref("analysis");
63
+
64
+ auto recipient = p.optional(p.literal(" to=user"));
65
+ auto final_msg = p.rule("final", recipient + p.literal("<|message|>") +
66
+ p.content(p.until_one_of({ "<|eot|>", "<|eom|>" })));
67
+
68
+ if (has_tools && inputs.tool_choice != COMMON_CHAT_TOOL_CHOICE_NONE) {
69
+ auto string_value = p.ac(
70
+ p.tool_arg_string_value(p.until("</atem:parameter>")) + p.tool_arg_close(p.literal("</atem:parameter>")),
71
+ "</atem:parameter>");
72
+
73
+ auto tool_choice = p.choice();
74
+ foreach_function(inputs.tools, [&](const json & tool) {
75
+ const auto & function = tool.at("function");
76
+ const std::string name = function.at("name");
77
+
78
+ std::vector<common_peg_parser> arg_rules;
79
+ foreach_parameter(function, [&](const common_chat_schema_property & prop, const common_chat_schema_document_ptr & doc) {
80
+ auto value_parser = p.eps();
81
+ if (prop.schema->may_be_string()) {
82
+ value_parser = string_value;
83
+ } else {
84
+ value_parser = p.tool_arg_json_value(
85
+ p.schema(p.json(), "tool-" + name + "-arg-" + prop.name + "-schema", doc, *prop.schema))
86
+ + p.tool_arg_close(p.literal("</atem:parameter>"));
87
+ }
88
+
89
+ arg_rules.push_back(p.tool_arg(
90
+ p.tool_arg_open(p.literal("<atem:parameter name=\"") + p.tool_arg_name(p.literal(prop.name)) + p.literal("\">")) +
91
+ value_parser));
92
+ });
93
+
94
+ auto args = p.eps();
95
+ if (!arg_rules.empty()) {
96
+ args = p.zero_or_more(p.choice(arg_rules) + p.space());
97
+ }
98
+
99
+ auto tool_parser = p.tool(
100
+ p.tool_open(p.literal(" to=") + p.until("<|message|>") +
101
+ p.literal("<|message|><atem:function_calls>") + p.space() +
102
+ p.literal("<atem:invoke name=\"") + p.tool_name(p.literal(name)) + p.literal("\">") + p.space())
103
+ << p.tool_args(args)
104
+ << p.tool_close(p.literal("</atem:invoke>") + p.space() + p.literal("</atem:function_calls>")));
105
+
106
+ tool_choice |= p.rule("tool-" + name, tool_parser);
107
+ });
108
+
109
+ auto tool_calls = inputs.parallel_tool_calls
110
+ ? p.trigger_rule("tool-call", tool_choice + p.zero_or_more(p.literal("<|eom|>") + start + tool_choice))
111
+ : p.trigger_rule("tool-call", tool_choice);
112
+
113
+
114
+ if (inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_REQUIRED) {
115
+ return p.zero_or_more(start + analysis) + start + tool_calls;
116
+ }
117
+ auto trailing_calls = p.optional(p.literal("<|eom|>") + start + tool_calls);
118
+ return p.zero_or_more(start + analysis) + start + (tool_calls | (final_msg + trailing_calls));
119
+ }
120
+
121
+ return p.zero_or_more(start + analysis) + start + final_msg;
122
+ });
123
+
124
+ data.parser = parser.save();
125
+
126
+ if (include_grammar) {
127
+ data.grammar_lazy = inputs.tool_choice != COMMON_CHAT_TOOL_CHOICE_REQUIRED;
128
+ data.grammar = build_grammar([&](const common_grammar_builder & builder) {
129
+ parser.build_grammar(builder, data.grammar_lazy);
130
+ });
131
+ data.grammar_triggers = {
132
+ { COMMON_GRAMMAR_TRIGGER_TYPE_PATTERN,
133
+ "<\\|start\\|>assistant( to=(?!self<\\|message\\|>)(?!user<\\|message\\|>)[^<]*?<\\|message\\|>)" },
134
+ };
135
+ }
136
+
137
+ return data;
138
+ }
common/parsers/parsers.cpp ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "parsers.h"
2
+
3
+ #include "log.h"
4
+
5
+ void foreach_function(const json & tools, const std::function<void(const json &)> & fn) {
6
+ for (const auto & tool : tools) {
7
+ if (!tool.contains("type") || tool.at("type") != "function" || !tool.contains("function")) {
8
+ LOG_INF("Skipping tool without function: %s", tool.dump(2).c_str());
9
+ continue;
10
+ }
11
+ fn(tool);
12
+ }
13
+ }
14
+
15
+ void foreach_parameter(const json & function, const std::function<void(const common_chat_schema_property &, const common_chat_schema_document_ptr &)> & fn) {
16
+ auto params = common_chat_tool_parameters(function);
17
+ auto doc = std::make_shared<const common_chat_schema_document>(common_chat_schema_from_json(params));
18
+ const auto * object = dynamic_cast<const common_chat_schema_object *>(doc->root.get());
19
+ if (!object) {
20
+ return;
21
+ }
22
+ for (const auto & prop : object->properties) {
23
+ fn(prop, doc);
24
+ }
25
+ }
common/parsers/parsers.h ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include "chat.h"
4
+ #include "chat-auto-parser.h"
5
+ #include "chat-auto-parser-helpers.h"
6
+ #include "chat-peg-parser.h"
7
+ #include "common.h"
8
+ #include "ggml.h"
9
+ #include "json-schema-to-grammar.h"
10
+ #include "json.h"
11
+
12
+ #include <functional>
13
+ #include <optional>
14
+ #include <set>
15
+ #include <string>
16
+ #include <vector>
17
+
18
+ using json = common_json;
19
+
20
+ // iterate over the function tools of an OpenAI-style tools array
21
+ void foreach_function(const json & tools, const std::function<void(const json &)> & fn);
22
+
23
+ // iterate over the parameters of a function tool, with the document that owns them
24
+ void foreach_parameter(const json & function, const std::function<void(const common_chat_schema_property &, const common_chat_schema_document_ptr &)> & fn);
25
+
26
+ // render a template; the override arguments let a parser feed in messages, tools or context it has rewritten
27
+ std::string common_chat_template_direct_apply_impl(
28
+ const common_chat_template & tmpl,
29
+ const autoparser::generation_params & inputs,
30
+ const std::optional<json> & messages_override = std::nullopt,
31
+ const std::optional<json> & tools_override = std::nullopt,
32
+ const std::optional<json> & additional_context = std::nullopt);
33
+
34
+ // the suffix a template appends when add_generation_prompt is set
35
+ std::string common_chat_template_generation_prompt_impl(
36
+ const common_chat_template & tmpl,
37
+ const autoparser::generation_params & inputs,
38
+ const std::optional<json> & messages_override = std::nullopt,
39
+ const std::optional<json> & tools_override = std::nullopt,
40
+ const std::optional<json> & additional_context = std::nullopt);
41
+
42
+ bool is_lfm2_template(const std::string & src);
43
+
44
+ namespace workaround {
45
+
46
+ void convert_tool_responses_gemma4(json & messages);
47
+
48
+ }
49
+
50
+ common_chat_params common_chat_params_init_cohere2moe(const common_chat_template & tmpl, const autoparser::generation_params & inputs);
51
+
52
+ common_chat_params common_chat_params_init_deepseek_v3_2(const common_chat_template & tmpl, const autoparser::generation_params & inputs);
53
+
54
+ common_chat_params common_chat_params_init_functionary_v3_2(const common_chat_template & tmpl, const autoparser::generation_params & inputs);
55
+
56
+ common_chat_params common_chat_params_init_gemma4(const common_chat_template & tmpl, const autoparser::generation_params & inputs);
57
+
58
+ common_chat_params common_chat_params_init_gigachat_v3(const common_chat_template & tmpl, const autoparser::generation_params & inputs);
59
+
60
+ common_chat_params common_chat_params_init_gpt_oss(const common_chat_template & tmpl, const autoparser::generation_params & inputs);
61
+
62
+ common_chat_params common_chat_params_init_kimi_k2(const common_chat_template & tmpl, const autoparser::generation_params & inputs);
63
+
64
+ common_chat_params common_chat_params_init_kimi_k3(const common_chat_template & tmpl, const autoparser::generation_params & inputs);
65
+
66
+ // tool_list_tokens preserves the LFM2 system tool-list markers; LFM2.5 renders without them
67
+ common_chat_params common_chat_params_init_lfm2(const common_chat_template & tmpl, const autoparser::generation_params & inputs, bool tool_list_tokens);
68
+
69
+ common_chat_params common_chat_params_init_minicpm5(const common_chat_template & tmpl, const autoparser::generation_params & inputs);
70
+
71
+ common_chat_params common_chat_params_init_minimax_m3(const common_chat_template & tmpl, const autoparser::generation_params & inputs);
72
+
73
+ common_chat_params common_chat_params_init_ministral_3(const common_chat_template & tmpl, const autoparser::generation_params & inputs);
74
+
75
+ common_chat_params common_chat_params_init_muse_glimmer(const common_chat_template & tmpl, const autoparser::generation_params & inputs);
76
+
77
+ common_chat_params common_chat_params_init_qwen3_coder(const common_chat_template & tmpl, const autoparser::generation_params & inputs);
common/parsers/qwen3-coder.cpp ADDED
@@ -0,0 +1,194 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "parsers.h"
2
+
3
+ common_chat_params common_chat_params_init_qwen3_coder(const common_chat_template & tmpl,
4
+ const autoparser::generation_params & inputs) {
5
+ common_chat_params data;
6
+
7
+ const std::string GEN_PREFIX = "<|im_start|>assistant\n";
8
+
9
+ data.prompt = common_chat_template_direct_apply_impl(tmpl, inputs);
10
+ data.generation_prompt = common_chat_template_generation_prompt_impl(tmpl, inputs);
11
+ data.format = COMMON_CHAT_FORMAT_PEG_NATIVE;
12
+
13
+ auto supports_reasoning = tmpl.source().find("<think>") != std::string::npos;
14
+
15
+ data.supports_thinking = supports_reasoning;
16
+ data.preserved_tokens = {
17
+ "<tool_call>",
18
+ "</tool_call>",
19
+ };
20
+
21
+ auto is_qwen3_coder = !supports_reasoning;
22
+
23
+ if (supports_reasoning) {
24
+ data.thinking_start_tag = "<think>";
25
+ // Support both </think> and <tool_call> as reasoning end sequences.
26
+ // The newline variant comes first so it is included in the forced message
27
+ // <function= is omitted, as it is a workaround for Qwen3-Coder which is not a thinking model
28
+ data.thinking_end_tags = { "\n</think>", "</think>", "<tool_call>" };
29
+ data.preserved_tokens.insert(data.preserved_tokens.end(), { "<think>", "</think>" });
30
+ }
31
+
32
+ data.message_delimiters = {
33
+ { COMMON_CHAT_ROLE_ASSISTANT, "<|im_start|>assistant" },
34
+ { COMMON_CHAT_ROLE_TOOL, "<|im_start|>user\n<tool_response>" }, // Qwen3-Coder, Qwen3.5, Nemotron Nano 3
35
+ { COMMON_CHAT_ROLE_TOOL, "<|im_start|>tool_response" }, // StepFun-3.5-Flash
36
+ { COMMON_CHAT_ROLE_USER, "<|im_start|>user" },
37
+ { COMMON_CHAT_ROLE_SYSTEM, "<|im_start|>system" },
38
+ };
39
+
40
+ auto has_tools = inputs.tools.is_array() && !inputs.tools.empty();
41
+ auto has_response_format = inputs.json_schema.is_object() && !inputs.json_schema.empty();
42
+ auto extract_reasoning = inputs.reasoning_format != COMMON_REASONING_FORMAT_NONE;
43
+ auto include_grammar = has_response_format || (has_tools && inputs.tool_choice != COMMON_CHAT_TOOL_CHOICE_NONE);
44
+
45
+ if (inputs.has_continuation()) {
46
+ const auto & msg = inputs.continue_msg;
47
+
48
+ data.generation_prompt = GEN_PREFIX;
49
+ if (supports_reasoning) {
50
+ data.generation_prompt += "<think>\n" + msg.reasoning_content;
51
+ if (inputs.continue_final_message == COMMON_CHAT_CONTINUATION_CONTENT) {
52
+ data.generation_prompt += "\n</think>\n\n";
53
+ }
54
+ }
55
+ if (inputs.continue_final_message == COMMON_CHAT_CONTINUATION_CONTENT) {
56
+ data.generation_prompt += msg.render_content();
57
+ }
58
+
59
+ data.prompt += data.generation_prompt;
60
+ }
61
+
62
+ std::vector<std::string> tool_call_starts = { "<tool_call>" };
63
+
64
+ if (is_qwen3_coder) {
65
+ // Match complete <function=name> opener for Qwen3-Coder models that occasionally omit the
66
+ // starting <tool_call>. The model may hallucinate a tool name, but it is preferable over
67
+ // constraining on <function which may occur in valid content generation, e.g. #include <functional>
68
+ foreach_function(inputs.tools, [&](const json & tool) {
69
+ const std::string name = tool.at("function").at("name");
70
+ tool_call_starts.push_back("<function=" + name + ">");
71
+ });
72
+ }
73
+
74
+ auto parser = build_chat_peg_parser([&](common_chat_peg_builder & p) {
75
+ auto generation_prompt = p.literal(GEN_PREFIX);
76
+
77
+ auto reasoning = p.eps();
78
+ if (supports_reasoning && extract_reasoning) {
79
+ reasoning = p.optional("<think>" + p.space() +
80
+ p.reasoning(p.until_one_of({ "</think>", "<tool_call>" })) +
81
+ (p.literal("</think>") | p.peek(p.literal("<tool_call>"))));
82
+ }
83
+
84
+ // Response format parser
85
+ if (has_response_format) {
86
+ return generation_prompt + (reasoning << p.content(p.schema(p.json(), "response-format", inputs.json_schema)));
87
+ }
88
+
89
+ // Tool call parser
90
+ if (has_tools && inputs.tool_choice != COMMON_CHAT_TOOL_CHOICE_NONE) {
91
+ auto arg_close = p.tool_arg_close(p.literal("\n</parameter>\n"));
92
+ auto arg_string = p.rule("xml-arg-string",
93
+ p.ac(p.tool_arg_string_value(p.until("\n</parameter>\n")) + arg_close, "\n</parameter>\n"));
94
+
95
+ auto tool_choice = p.choice();
96
+ foreach_function(inputs.tools, [&](const json & tool) {
97
+ const auto & function = tool.at("function");
98
+ std::string name = function.at("name");
99
+
100
+ std::vector<common_peg_parser> required_args;
101
+ std::vector<common_peg_parser> optional_args;
102
+
103
+ foreach_parameter(function, [&](const common_chat_schema_property & param, const common_chat_schema_document_ptr & doc) {
104
+ auto rule_name = "tool-" + name + "-arg-" + param.name;
105
+
106
+ auto arg_open = p.tool_arg_open("<parameter=" + p.tool_arg_name(p.literal(param.name)) + ">\n");
107
+
108
+ auto types = param.schema->value_types();
109
+
110
+ auto arg_value = p.eps();
111
+ if (!types.has(common_chat_schema::TYPE_STRING)) {
112
+ arg_value = p.tool_arg_json_value(p.schema(p.json(), rule_name + "-schema", doc, *param.schema)) + arg_close;
113
+ } else if (types.is_only(common_chat_schema::TYPE_STRING)) {
114
+ arg_value = arg_string;
115
+ } else {
116
+ // The string alternative accepts any text, so the grammar only keeps the raw string
117
+ // rule. The parser still tries the JSON alternatives first to type the value.
118
+ auto json_value = p.choice();
119
+ if (types.has(common_chat_schema::TYPE_OBJECT)) {
120
+ json_value |= p.json_object();
121
+ }
122
+ if (types.has(common_chat_schema::TYPE_ARRAY)) {
123
+ json_value |= p.json_array();
124
+ }
125
+ if (types.has(common_chat_schema::TYPE_NUMBER) || types.has(common_chat_schema::TYPE_INTEGER)) {
126
+ json_value |= p.json_number();
127
+ }
128
+ if (types.has(common_chat_schema::TYPE_BOOLEAN)) {
129
+ json_value |= p.json_bool();
130
+ }
131
+ if (types.has(common_chat_schema::TYPE_NULL)) {
132
+ json_value |= p.json_null();
133
+ }
134
+ arg_value = p.gbnf(p.atomic(p.tool_arg_json_value(json_value) + arg_close) | arg_string, "xml-arg-string");
135
+ }
136
+
137
+ auto arg_rule = p.rule(rule_name, p.tool_arg(arg_open + arg_value));
138
+
139
+ (param.required ? required_args : optional_args).push_back(arg_rule);
140
+ });
141
+
142
+ // Accept required arguments in any order, as Qwen does not always adhere to the
143
+ // order provided.
144
+ auto args = p.permute("tool-" + name + "-args", required_args);
145
+ if (!optional_args.empty()) {
146
+ args = args + p.zero_or_more(p.choice(optional_args));
147
+ }
148
+
149
+ auto func = p.tool(p.tool_open("<function=" + p.tool_name(p.literal(name)) + ">\n") +
150
+ p.tool_args(args) +
151
+ p.tool_close(p.literal("</function>\n")));
152
+
153
+ tool_choice |= p.rule("tool-" + name, func);
154
+ });
155
+
156
+ auto min_calls = inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_REQUIRED ? 1 : 0;
157
+
158
+ auto tool_call_body = tool_choice + "</tool_call>" + p.space();
159
+ auto tool_call = p.rule("tool-call", "<tool_call>\n" + tool_call_body);
160
+
161
+ // Qwen3-Coder models may occasionally omit the <tool_call> token.
162
+ auto tool_call_first = is_qwen3_coder ?
163
+ p.rule("tool-call-first", p.optional(p.literal("<tool_call>\n")) + tool_call_body) :
164
+ tool_call;
165
+
166
+ auto calls = inputs.parallel_tool_calls ? tool_call_first + p.zero_or_more(tool_call) : tool_call_first;
167
+ auto tool_calls = p.trigger_rule("tool-call-root", p.repeat(calls, min_calls, 1));
168
+
169
+ return generation_prompt +
170
+ (reasoning << p.content(p.until_one_of(tool_call_starts)) << tool_calls);
171
+ }
172
+
173
+ // Content only parser
174
+ return generation_prompt + (reasoning << p.content(p.rest()));
175
+ });
176
+
177
+ data.parser = parser.save();
178
+
179
+ if (include_grammar) {
180
+ data.grammar_lazy = has_tools && inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_AUTO;
181
+
182
+ data.grammar = build_grammar([&](const common_grammar_builder & builder) {
183
+ parser.build_grammar(builder, data.grammar_lazy);
184
+ });
185
+
186
+ if (data.grammar_lazy) {
187
+ for (const auto & start : tool_call_starts) {
188
+ data.grammar_triggers.push_back({ COMMON_GRAMMAR_TRIGGER_TYPE_WORD, start });
189
+ }
190
+ }
191
+ }
192
+
193
+ return data;
194
+ }
common/parsers/sources.cmake ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Specialized chat template parsers, listed explicitly so that adding or removing one re-runs CMake instead of leaving an incremental build stale.
2
+
3
+ set(LLAMA_CHAT_PARSERS_SOURCES
4
+ ${CMAKE_CURRENT_LIST_DIR}/parsers.cpp
5
+ ${CMAKE_CURRENT_LIST_DIR}/parsers.h
6
+ ${CMAKE_CURRENT_LIST_DIR}/cohere2moe.cpp
7
+ ${CMAKE_CURRENT_LIST_DIR}/deepseek.cpp
8
+ ${CMAKE_CURRENT_LIST_DIR}/functionary-v3-2.cpp
9
+ ${CMAKE_CURRENT_LIST_DIR}/gemma4.cpp
10
+ ${CMAKE_CURRENT_LIST_DIR}/gigachat-v3.cpp
11
+ ${CMAKE_CURRENT_LIST_DIR}/gpt-oss.cpp
12
+ ${CMAKE_CURRENT_LIST_DIR}/kimi-k2.cpp
13
+ ${CMAKE_CURRENT_LIST_DIR}/kimi-k3.cpp
14
+ ${CMAKE_CURRENT_LIST_DIR}/lfm2.cpp
15
+ ${CMAKE_CURRENT_LIST_DIR}/minicpm5.cpp
16
+ ${CMAKE_CURRENT_LIST_DIR}/minimax-m3.cpp
17
+ ${CMAKE_CURRENT_LIST_DIR}/ministral3.cpp
18
+ ${CMAKE_CURRENT_LIST_DIR}/muse-glimmer.cpp
19
+ ${CMAKE_CURRENT_LIST_DIR}/qwen3-coder.cpp
20
+ )
common/peg-parser.cpp ADDED
@@ -0,0 +1,2098 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "peg-parser.h"
2
+
3
+ #include "common.h"
4
+ #include "json-schema-to-grammar.h"
5
+ #include "log.h"
6
+ #include "trie.h"
7
+ #include "unicode.h"
8
+
9
+ #include <algorithm>
10
+ #include <initializer_list>
11
+ #include <map>
12
+ #include <memory>
13
+ #include <regex>
14
+ #include <set>
15
+ #include <stdexcept>
16
+
17
+ // Trick to catch missing branches
18
+ template <typename T>
19
+ inline constexpr bool is_always_false_v = false;
20
+
21
+ const char * common_peg_parse_result_type_name(common_peg_parse_result_type type) {
22
+ switch (type) {
23
+ case COMMON_PEG_PARSE_RESULT_FAIL: return "fail";
24
+ case COMMON_PEG_PARSE_RESULT_SUCCESS: return "success";
25
+ case COMMON_PEG_PARSE_RESULT_NEED_MORE_INPUT: return "need_more_input";
26
+ default: return "unknown";
27
+ }
28
+ }
29
+
30
+ static bool is_hex_digit(const char c) {
31
+ return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F');
32
+ }
33
+
34
+ static std::pair<uint32_t, size_t> parse_hex_escape(const std::string & str, size_t pos, int hex_count) {
35
+ if (pos + hex_count > str.length()) {
36
+ return {0, 0};
37
+ }
38
+
39
+ uint32_t value = 0;
40
+ for (int i = 0; i < hex_count; i++) {
41
+ char c = str[pos + i];
42
+ if (!is_hex_digit(c)) {
43
+ return {0, 0};
44
+ }
45
+ value <<= 4;
46
+ if ('a' <= c && c <= 'f') {
47
+ value += c - 'a' + 10;
48
+ } else if ('A' <= c && c <= 'F') {
49
+ value += c - 'A' + 10;
50
+ } else if ('0' <= c && c <= '9') {
51
+ value += c - '0';
52
+ } else {
53
+ break;
54
+ }
55
+ }
56
+ return {value, static_cast<size_t>(hex_count)};
57
+ }
58
+
59
+ static std::pair<uint32_t, size_t> parse_char_class_char(const std::string & content, size_t pos) {
60
+ if (content[pos] == '\\' && pos + 1 < content.length()) {
61
+ switch (content[pos + 1]) {
62
+ case 'x': {
63
+ auto result = parse_hex_escape(content, pos + 2, 2);
64
+ if (result.second > 0) {
65
+ return {result.first, 2 + result.second};
66
+ }
67
+ // Invalid escape, treat as literal 'x'
68
+ return {static_cast<uint32_t>('x'), 2};
69
+ }
70
+ case 'u': {
71
+ auto result = parse_hex_escape(content, pos + 2, 4);
72
+ if (result.second > 0) {
73
+ return {result.first, 2 + result.second};
74
+ }
75
+ // Invalid escape, treat as literal 'u'
76
+ return {static_cast<uint32_t>('u'), 2};
77
+ }
78
+ case 'U': {
79
+ auto result = parse_hex_escape(content, pos + 2, 8);
80
+ if (result.second > 0) {
81
+ return {result.first, 2 + result.second};
82
+ }
83
+ // Invalid escape, treat as literal 'U'
84
+ return {static_cast<uint32_t>('U'), 2};
85
+ }
86
+ case 'n': return {'\n', 2};
87
+ case 't': return {'\t', 2};
88
+ case 'r': return {'\r', 2};
89
+ case '\\': return {'\\', 2};
90
+ case ']': return {']', 2};
91
+ case '[': return {'[', 2};
92
+ default: return {static_cast<uint32_t>(content[pos + 1]), 2};
93
+ }
94
+ }
95
+
96
+ // Regular character - return as codepoint
97
+ return {static_cast<uint32_t>(static_cast<unsigned char>(content[pos])), 1};
98
+ }
99
+
100
+ static std::pair<std::vector<common_peg_chars_parser::char_range>, bool> parse_char_classes(const std::string & classes) {
101
+ std::vector<common_peg_chars_parser::char_range> ranges;
102
+ bool negated = false;
103
+
104
+ std::string content = classes;
105
+ if (content.front() == '[') {
106
+ content = content.substr(1);
107
+ }
108
+
109
+ if (content.back() == ']') {
110
+ content.pop_back();
111
+ }
112
+
113
+ // Check for negation
114
+ if (!content.empty() && content.front() == '^') {
115
+ negated = true;
116
+ content = content.substr(1);
117
+ }
118
+
119
+ size_t i = 0;
120
+ while (i < content.length()) {
121
+ auto [start, start_len] = parse_char_class_char(content, i);
122
+ i += start_len;
123
+
124
+ if (i + 1 < content.length() && content[i] == '-') {
125
+ // Range detected
126
+ auto [end, end_len] = parse_char_class_char(content, i + 1);
127
+ ranges.push_back(common_peg_chars_parser::char_range{start, end});
128
+ i += 1 + end_len;
129
+ } else {
130
+ ranges.push_back(common_peg_chars_parser::char_range{start, start});
131
+ }
132
+ }
133
+
134
+ return {ranges, negated};
135
+ }
136
+
137
+ common_peg_ast_id common_peg_ast_arena::find_by_tag(const common_peg_ast_node & parent, const std::string & tag, int max_depth) const {
138
+ for (auto child_id : parent.children) {
139
+ const auto & child = get(child_id);
140
+ if (child.tag == tag) {
141
+ return child_id;
142
+ }
143
+ if (max_depth > 1) {
144
+ auto result = find_by_tag(child, tag, max_depth - 1);
145
+ if (result != COMMON_PEG_INVALID_AST_ID) {
146
+ return result;
147
+ }
148
+ }
149
+ }
150
+ return COMMON_PEG_INVALID_AST_ID;
151
+ }
152
+
153
+ common_peg_ast_id common_peg_ast_arena::find_by_rule(const common_peg_ast_node & parent, const std::string & rule, int max_depth) const {
154
+ for (auto child_id : parent.children) {
155
+ const auto & child = get(child_id);
156
+ if (child.rule == rule) {
157
+ return child_id;
158
+ }
159
+ if (max_depth > 1) {
160
+ auto result = find_by_rule(child, rule, max_depth - 1);
161
+ if (result != COMMON_PEG_INVALID_AST_ID) {
162
+ return result;
163
+ }
164
+ }
165
+ }
166
+ return COMMON_PEG_INVALID_AST_ID;
167
+ }
168
+
169
+ void common_peg_ast_arena::visit(common_peg_ast_id id, const common_peg_ast_visitor & visitor) const {
170
+ if (id == COMMON_PEG_INVALID_AST_ID) {
171
+ return;
172
+ }
173
+ const auto & node = get(id);
174
+ visitor(node);
175
+ for (const auto & child : node.children) {
176
+ visit(child, visitor);
177
+ }
178
+ }
179
+
180
+ void common_peg_ast_arena::visit(const common_peg_parse_result & result, const common_peg_ast_visitor & visitor) const {
181
+ for (const auto & node : result.nodes) {
182
+ visit(node, visitor);
183
+ }
184
+ }
185
+
186
+ struct parser_executor;
187
+
188
+ common_peg_parser_id common_peg_arena::add_parser(common_peg_parser_variant parser) {
189
+ common_peg_parser_id id = parsers_.size();
190
+ parsers_.push_back(std::move(parser));
191
+ return id;
192
+ }
193
+
194
+ void common_peg_arena::add_rule(const std::string & name, common_peg_parser_id id) {
195
+ rules_[name] = id;
196
+ }
197
+
198
+ common_peg_parser_id common_peg_arena::get_rule(const std::string & name) const {
199
+ auto it = rules_.find(name);
200
+ if (it == rules_.end()) {
201
+ throw std::runtime_error("Rule not found: " + name);
202
+ }
203
+ return it->second;
204
+ }
205
+
206
+ struct parser_executor {
207
+ const common_peg_arena & arena;
208
+ common_peg_parse_context & ctx;
209
+ size_t start_pos;
210
+
211
+ parser_executor(const common_peg_arena & arena, common_peg_parse_context & ctx, size_t start)
212
+ : arena(arena), ctx(ctx), start_pos(start) {}
213
+
214
+ std::string debug_indent() const { return std::string(ctx.parse_depth * 2, ' '); }
215
+
216
+ std::string debug_input_snippet(size_t pos, size_t len = 60) const {
217
+ if (pos >= ctx.input.size()) {
218
+ return "<EOF>";
219
+ }
220
+ auto snippet = ctx.input.substr(pos, len);
221
+ // Escape newlines for display
222
+ std::string result;
223
+ for (char c : snippet) {
224
+ if (c == '\n') {
225
+ result += "\\n";
226
+ } else if (c == '\r') {
227
+ result += "\\r";
228
+ } else if (c == '\t') {
229
+ result += "\\t";
230
+ } else {
231
+ result += c;
232
+ }
233
+ }
234
+ if (pos + len < ctx.input.size()) {
235
+ result += "...";
236
+ }
237
+ return result;
238
+ }
239
+
240
+ common_peg_parse_result operator()(const common_peg_epsilon_parser & /* p */) const {
241
+ return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_SUCCESS, start_pos);
242
+ }
243
+
244
+ common_peg_parse_result operator()(const common_peg_start_parser & /* p */) const {
245
+ return common_peg_parse_result(
246
+ start_pos == 0 ? COMMON_PEG_PARSE_RESULT_SUCCESS : COMMON_PEG_PARSE_RESULT_FAIL,
247
+ start_pos
248
+ );
249
+ }
250
+
251
+ common_peg_parse_result operator()(const common_peg_end_parser & /* p */) const {
252
+ return common_peg_parse_result(
253
+ start_pos >= ctx.input.size() ? COMMON_PEG_PARSE_RESULT_SUCCESS : COMMON_PEG_PARSE_RESULT_FAIL,
254
+ start_pos
255
+ );
256
+ }
257
+
258
+ common_peg_parse_result operator()(const common_peg_literal_parser & p) {
259
+ auto pos = start_pos;
260
+ for (auto i = 0u; i < p.literal.size(); ++i) {
261
+ if (pos >= ctx.input.size()) {
262
+ if (!ctx.is_lenient()) {
263
+ return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_FAIL, start_pos);
264
+ }
265
+ return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_NEED_MORE_INPUT, start_pos, pos);
266
+ }
267
+ if (ctx.input[pos] != p.literal[i]) {
268
+ return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_FAIL, start_pos);
269
+ }
270
+ ++pos;
271
+ }
272
+
273
+ return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_SUCCESS, start_pos, pos);
274
+ }
275
+
276
+ common_peg_parse_result operator()(const common_peg_sequence_parser & p) {
277
+ if (ctx.is_debug()) {
278
+ LOG_DBG("%sSEQ start at %zu '%s' (%zu children)\n", debug_indent().c_str(), start_pos,
279
+ debug_input_snippet(start_pos).c_str(), p.children.size());
280
+ }
281
+ ctx.parse_depth++;
282
+
283
+ auto pos = start_pos;
284
+ std::vector<common_peg_ast_id> nodes;
285
+
286
+ for (size_t i = 0; i < p.children.size(); i++) {
287
+ const auto & child_id = p.children[i];
288
+ if (ctx.is_debug()) {
289
+ fprintf(stderr, "%sSEQ child %zu: %s\n", debug_indent().c_str(), i, arena.dump(child_id).c_str());
290
+ }
291
+ auto result = arena.parse(child_id, ctx, pos);
292
+
293
+ if (ctx.is_debug()) {
294
+ fprintf(stderr, "%sSEQ child %zu: %s at %zu->%zu\n", debug_indent().c_str(), i,
295
+ common_peg_parse_result_type_name(result.type), result.start, result.end);
296
+ }
297
+
298
+ if (result.fail()) {
299
+ ctx.parse_depth--;
300
+ if (ctx.is_debug()) {
301
+ fprintf(stderr, "%sSEQ -> FAIL\n", debug_indent().c_str());
302
+ }
303
+ return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_FAIL, start_pos, result.end);
304
+ }
305
+
306
+ if (!result.nodes.empty()) {
307
+ nodes.insert(nodes.end(), result.nodes.begin(), result.nodes.end());
308
+ }
309
+
310
+ if (result.need_more_input()) {
311
+ ctx.parse_depth--;
312
+ if (ctx.is_debug()) {
313
+ fprintf(stderr, "%sSEQ -> NEED_MORE\n", debug_indent().c_str());
314
+ }
315
+ return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_NEED_MORE_INPUT, start_pos, result.end, std::move(nodes));
316
+ }
317
+
318
+ pos = result.end;
319
+ }
320
+
321
+ ctx.parse_depth--;
322
+ if (ctx.is_debug()) {
323
+ fprintf(stderr, "%sSEQ -> SUCCESS at %zu->%zu\n", debug_indent().c_str(), start_pos, pos);
324
+ }
325
+ return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_SUCCESS, start_pos, pos, std::move(nodes));
326
+ }
327
+
328
+ common_peg_parse_result operator()(const common_peg_choice_parser & p) {
329
+ if (ctx.is_debug()) {
330
+ fprintf(stderr, "%sCHOICE start at %zu '%s' (%zu options)\n", debug_indent().c_str(), start_pos,
331
+ debug_input_snippet(start_pos).c_str(), p.children.size());
332
+ }
333
+ ctx.parse_depth++;
334
+
335
+ auto pos = start_pos;
336
+ for (size_t i = 0; i < p.children.size(); i++) {
337
+ const auto & child_id = p.children[i];
338
+ if (ctx.is_debug()) {
339
+ fprintf(stderr, "%sCHOICE option %zu: %s\n", debug_indent().c_str(), i, arena.dump(child_id).c_str());
340
+ }
341
+ auto result = arena.parse(child_id, ctx, pos);
342
+ if (ctx.is_debug()) {
343
+ fprintf(stderr, "%sCHOICE option %zu: %s\n", debug_indent().c_str(), i,
344
+ common_peg_parse_result_type_name(result.type));
345
+ }
346
+ if (!result.fail()) {
347
+ ctx.parse_depth--;
348
+ if (ctx.is_debug()) {
349
+ fprintf(stderr, "%sCHOICE -> %s (option %zu)\n", debug_indent().c_str(),
350
+ common_peg_parse_result_type_name(result.type), i);
351
+ }
352
+ return result;
353
+ }
354
+ }
355
+
356
+ ctx.parse_depth--;
357
+ if (ctx.is_debug()) {
358
+ fprintf(stderr, "%sCHOICE -> FAIL (no options matched)\n", debug_indent().c_str());
359
+ }
360
+ return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_FAIL, start_pos);
361
+ }
362
+
363
+ common_peg_parse_result operator()(const common_peg_repetition_parser & p) {
364
+ if (ctx.is_debug()) {
365
+ fprintf(stderr, "%sREPEAT start at %zu '%s' (min=%d, max=%d)\n", debug_indent().c_str(), start_pos,
366
+ debug_input_snippet(start_pos).c_str(), p.min_count, p.max_count);
367
+ }
368
+ ctx.parse_depth++;
369
+
370
+ auto pos = start_pos;
371
+ int match_count = 0;
372
+ std::vector<common_peg_ast_id> nodes;
373
+
374
+ // Try to match up to max_count times (or unlimited if max_count is -1)
375
+ while (p.max_count == -1 || match_count < p.max_count) {
376
+ if (pos >= ctx.input.size()) {
377
+ if (ctx.is_debug()) {
378
+ fprintf(stderr, "%sREPEAT: at end of input, count=%d\n", debug_indent().c_str(), match_count);
379
+ }
380
+ break;
381
+ }
382
+
383
+ auto result = arena.parse(p.child, ctx, pos);
384
+
385
+ if (ctx.is_debug()) {
386
+ fprintf(stderr, "%sREPEAT iter %d: %s at %zu->%zu, nodes=%zu\n", debug_indent().c_str(), match_count,
387
+ common_peg_parse_result_type_name(result.type), result.start, result.end, result.nodes.size());
388
+ fprintf(stderr, "%sREPEAT CHILD: %s\n", debug_indent().c_str(), arena.dump(p.child).c_str());
389
+ }
390
+
391
+ if (result.success()) {
392
+ // Prevent infinite loop on empty matches
393
+ if (result.end == pos) {
394
+ if (ctx.is_debug()) {
395
+ fprintf(stderr, "%s REPEAT: empty match, stopping\n", debug_indent().c_str());
396
+ }
397
+ break;
398
+ }
399
+
400
+ if (!result.nodes.empty()) {
401
+ nodes.insert(nodes.end(), result.nodes.begin(), result.nodes.end());
402
+ }
403
+
404
+ pos = result.end;
405
+ match_count++;
406
+ continue;
407
+ }
408
+
409
+ if (result.need_more_input()) {
410
+ if (!result.nodes.empty()) {
411
+ nodes.insert(nodes.end(), result.nodes.begin(), result.nodes.end());
412
+ }
413
+
414
+ ctx.parse_depth--;
415
+ if (ctx.is_debug()) {
416
+ fprintf(stderr, "%sREPEAT -> NEED_MORE (count=%d, nodes=%zu)\n", debug_indent().c_str(),
417
+ match_count, nodes.size());
418
+ }
419
+ return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_NEED_MORE_INPUT, start_pos, result.end, std::move(nodes));
420
+ }
421
+
422
+ // Child failed - stop trying
423
+ if (ctx.is_debug()) {
424
+ fprintf(stderr, "%sREPEAT: child failed, stopping\n", debug_indent().c_str());
425
+ }
426
+ break;
427
+ }
428
+
429
+ // Check if we got enough matches
430
+ if (p.min_count > 0 && match_count < p.min_count) {
431
+ ctx.parse_depth--;
432
+ if (pos >= ctx.input.size() && ctx.is_lenient()) {
433
+ if (ctx.is_debug()) {
434
+ fprintf(stderr, "%sREPEAT -> NEED_MORE (not enough matches: %d < %d)\n", debug_indent().c_str(),
435
+ match_count, p.min_count);
436
+ }
437
+ return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_NEED_MORE_INPUT, start_pos, pos, std::move(nodes));
438
+ }
439
+ if (ctx.is_debug()) {
440
+ fprintf(stderr, "%sREPEAT -> FAIL (not enough matches: %d < %d)\n", debug_indent().c_str(), match_count,
441
+ p.min_count);
442
+ }
443
+ return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_FAIL, start_pos, pos);
444
+ }
445
+
446
+ ctx.parse_depth--;
447
+ if (ctx.is_debug()) {
448
+ fprintf(stderr, "%sREPEAT -> SUCCESS (count=%d, nodes=%zu)\n", debug_indent().c_str(), match_count,
449
+ nodes.size());
450
+ }
451
+ return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_SUCCESS, start_pos, pos, std::move(nodes));
452
+ }
453
+
454
+ common_peg_parse_result operator()(const common_peg_and_parser & p) {
455
+ auto result = arena.parse(p.child, ctx, start_pos);
456
+ // Pass result but don't consume input
457
+ return common_peg_parse_result(result.type, start_pos);
458
+ }
459
+
460
+ common_peg_parse_result operator()(const common_peg_not_parser & p) {
461
+ auto result = arena.parse(p.child, ctx, start_pos);
462
+
463
+ if (result.success()) {
464
+ // Fail if the underlying parser matches
465
+ return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_FAIL, start_pos);
466
+ }
467
+
468
+ if (result.need_more_input()) {
469
+ // Propagate - need to know what child would match before negating
470
+ return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_NEED_MORE_INPUT, start_pos);
471
+ }
472
+
473
+ // Child failed, so negation succeeds
474
+ return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_SUCCESS, start_pos);
475
+ }
476
+
477
+ common_peg_parse_result operator()(const common_peg_any_parser & /* p */) const {
478
+ // Parse a single UTF-8 codepoint (not just a single byte)
479
+ auto result = common_parse_utf8_codepoint(ctx.input, start_pos);
480
+
481
+ if (result.status == utf8_parse_result::INCOMPLETE) {
482
+ if (!ctx.is_lenient()) {
483
+ return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_FAIL, start_pos);
484
+ }
485
+ return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_NEED_MORE_INPUT, start_pos);
486
+ }
487
+ if (result.status == utf8_parse_result::INVALID) {
488
+ return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_FAIL, start_pos);
489
+ }
490
+ return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_SUCCESS, start_pos, start_pos + result.bytes_consumed);
491
+ }
492
+
493
+ common_peg_parse_result operator()(const common_peg_space_parser & /* p */) {
494
+ auto pos = start_pos;
495
+ while (pos < ctx.input.size()) {
496
+ auto c = static_cast<unsigned char>(ctx.input[pos]);
497
+ if (std::isspace(c)) {
498
+ ++pos;
499
+ } else {
500
+ break;
501
+ }
502
+ }
503
+
504
+ return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_SUCCESS, start_pos, pos);
505
+ }
506
+
507
+ common_peg_parse_result operator()(const common_peg_chars_parser & p) const {
508
+ auto pos = start_pos;
509
+ int match_count = 0;
510
+
511
+ // Try to match up to max_count times (or unlimited if max_count is -1)
512
+ while (p.max_count == -1 || match_count < p.max_count) {
513
+ auto result = common_parse_utf8_codepoint(ctx.input, pos);
514
+
515
+ if (result.status == utf8_parse_result::INCOMPLETE) {
516
+ if (match_count >= p.min_count) {
517
+ // We have enough matches, succeed with what we have
518
+ return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_SUCCESS, start_pos, pos);
519
+ }
520
+ // Not enough matches yet
521
+ if (!ctx.is_lenient()) {
522
+ return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_FAIL, start_pos);
523
+ }
524
+ return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_NEED_MORE_INPUT, start_pos, pos);
525
+ }
526
+
527
+ if (result.status == utf8_parse_result::INVALID) {
528
+ // Malformed UTF-8 in input
529
+ if (match_count >= p.min_count) {
530
+ // We have enough matches, succeed up to here
531
+ return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_SUCCESS, start_pos, pos);
532
+ }
533
+ // Not enough matches, fail
534
+ return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_FAIL, start_pos);
535
+ }
536
+
537
+ // Check if this codepoint matches our character class
538
+ bool matches = false;
539
+ for (const auto & range : p.ranges) {
540
+ if (range.contains(result.codepoint)) {
541
+ matches = true;
542
+ break;
543
+ }
544
+ }
545
+
546
+ // If negated, invert the match result
547
+ if (p.negated) {
548
+ matches = !matches;
549
+ }
550
+
551
+ if (matches) {
552
+ pos += result.bytes_consumed;
553
+ ++match_count;
554
+ } else {
555
+ // Character doesn't match, stop matching
556
+ break;
557
+ }
558
+ }
559
+
560
+ // Check if we got enough matches
561
+ if (match_count < p.min_count) {
562
+ if (pos >= ctx.input.size() && ctx.is_lenient()) {
563
+ return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_NEED_MORE_INPUT, start_pos, pos);
564
+ }
565
+ return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_FAIL, start_pos, pos);
566
+ }
567
+
568
+ return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_SUCCESS, start_pos, pos);
569
+ }
570
+
571
+ static common_peg_parse_result handle_escape_sequence(common_peg_parse_context & ctx, size_t start, size_t & pos, const char delimiter) {
572
+ auto save = pos;
573
+
574
+ ++pos; // consume '\'
575
+ if (pos >= ctx.input.size()) {
576
+ if (!ctx.is_lenient()) {
577
+ return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_FAIL, start);
578
+ }
579
+ pos = save; // suppress unmatched '\'
580
+ return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_NEED_MORE_INPUT, start, pos);
581
+ }
582
+
583
+ char c = ctx.input[pos];
584
+
585
+ if (c == delimiter || c == '\\' || c == '/' || c == 'b' || c == 'f' || c == 'n' || c == 'r' || c == 't') {
586
+ ++pos;
587
+ return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_SUCCESS, start, pos);
588
+ }
589
+
590
+ if (c == 'u') {
591
+ auto result = handle_unicode_escape(ctx, start, pos);
592
+ if (result.need_more_input()) {
593
+ pos = save; // suppress incomplete sequence
594
+ return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_NEED_MORE_INPUT, start, pos);
595
+ }
596
+ return result;
597
+ }
598
+
599
+ return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_FAIL, start);
600
+ }
601
+
602
+ static common_peg_parse_result handle_unicode_escape(common_peg_parse_context & ctx, size_t start, size_t & pos) {
603
+ ++pos; // consume 'u'
604
+ for (int i = 0; i < 4; ++i) {
605
+ if (pos >= ctx.input.size()) {
606
+ if (!ctx.is_lenient()) {
607
+ return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_FAIL, start);
608
+ }
609
+ return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_NEED_MORE_INPUT, start, pos);
610
+ }
611
+ if (!is_hex_digit(ctx.input[pos])) {
612
+ return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_FAIL, start);
613
+ }
614
+ ++pos;
615
+ }
616
+ return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_SUCCESS, start, pos);
617
+ }
618
+
619
+ common_peg_parse_result operator()(const common_peg_string_parser & p) {
620
+ auto pos = start_pos;
621
+
622
+ // Parse string content (without quotes)
623
+ while (pos < ctx.input.size()) {
624
+ char c = ctx.input[pos];
625
+
626
+ if (c == p.delimiter) {
627
+ // Found closing delimiter - success (don't consume it)
628
+ return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_SUCCESS, start_pos, pos);
629
+ }
630
+
631
+ if (c == '\\') {
632
+ auto result = handle_escape_sequence(ctx, start_pos, pos, p.delimiter);
633
+ if (!result.success()) {
634
+ return result;
635
+ }
636
+ } else {
637
+ auto utf8_result = common_parse_utf8_codepoint(ctx.input, pos);
638
+
639
+ if (utf8_result.status == utf8_parse_result::INCOMPLETE) {
640
+ if (!ctx.is_lenient()) {
641
+ return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_FAIL, start_pos);
642
+ }
643
+ return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_NEED_MORE_INPUT, start_pos, pos);
644
+ }
645
+
646
+ if (utf8_result.status == utf8_parse_result::INVALID) {
647
+ return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_FAIL, start_pos);
648
+ }
649
+
650
+ pos += utf8_result.bytes_consumed;
651
+ }
652
+ }
653
+
654
+ // Reached end without finding closing quote
655
+ if (!ctx.is_lenient()) {
656
+ return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_FAIL, start_pos, pos);
657
+ }
658
+ return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_NEED_MORE_INPUT, start_pos, pos);
659
+ }
660
+
661
+ common_peg_parse_result operator()(const common_peg_until_parser & p) const {
662
+ common_trie matcher(p.delimiters);
663
+
664
+ // Scan input and check for delimiters
665
+ size_t pos = start_pos;
666
+ size_t last_valid_pos = start_pos;
667
+
668
+ while (pos < ctx.input.size()) {
669
+ auto utf8_result = common_parse_utf8_codepoint(ctx.input, pos);
670
+
671
+ if (utf8_result.status == utf8_parse_result::INCOMPLETE) {
672
+ // Incomplete UTF-8 sequence
673
+ if (!ctx.is_lenient()) {
674
+ // Input is complete but UTF-8 is incomplete = malformed
675
+ return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_FAIL, start_pos);
676
+ }
677
+ // Return what we have so far (before incomplete sequence)
678
+ return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_NEED_MORE_INPUT, start_pos, last_valid_pos);
679
+ }
680
+
681
+ if (utf8_result.status == utf8_parse_result::INVALID) {
682
+ // Malformed UTF-8
683
+ return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_FAIL, start_pos);
684
+ }
685
+
686
+ // Check if a delimiter starts at this position
687
+ auto match = matcher.check_at(ctx.input, pos);
688
+
689
+ if (match == common_trie::COMPLETE_MATCH) {
690
+ // Found a complete delimiter, return everything before it
691
+ return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_SUCCESS, start_pos, pos);
692
+ }
693
+
694
+ if (match == common_trie::PARTIAL_MATCH) {
695
+ // Found a partial match extending to end of input, return everything before it
696
+ return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_SUCCESS, start_pos, pos);
697
+ }
698
+
699
+ pos += utf8_result.bytes_consumed;
700
+ last_valid_pos = pos;
701
+ }
702
+
703
+ if (last_valid_pos == ctx.input.size() && ctx.is_lenient()) {
704
+ // Reached the end of a partial stream, there might still be more input that we need to consume.
705
+ return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_NEED_MORE_INPUT, start_pos, last_valid_pos);
706
+ }
707
+ return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_SUCCESS, start_pos, last_valid_pos);
708
+ }
709
+
710
+ common_peg_parse_result operator()(const common_peg_schema_parser & p) {
711
+ return arena.parse(p.child, ctx, start_pos);
712
+ }
713
+
714
+ common_peg_parse_result operator()(const common_peg_rule_parser & p) {
715
+ // Parse the child
716
+ auto result = arena.parse(p.child, ctx, start_pos);
717
+
718
+ if (!result.fail()) {
719
+ std::string_view text;
720
+ if (result.start < ctx.input.size()) {
721
+ text = std::string_view(ctx.input).substr(result.start, result.end - result.start);
722
+ }
723
+
724
+ auto node_id = ctx.ast.add_node(
725
+ p.name,
726
+ "",
727
+ result.start,
728
+ result.end,
729
+ text,
730
+ std::move(result.nodes),
731
+ result.need_more_input()
732
+ );
733
+
734
+ return common_peg_parse_result(result.type, result.start, result.end, { node_id });
735
+ }
736
+
737
+ return result;
738
+ }
739
+
740
+ common_peg_parse_result operator()(const common_peg_tag_parser & p) {
741
+ // Parse the child
742
+ if (ctx.is_debug()) {
743
+ fprintf(stderr, "%sTAG: %s\n", debug_indent().c_str(), p.tag.c_str());
744
+ }
745
+ auto result = arena.parse(p.child, ctx, start_pos);
746
+
747
+ if (!result.fail()) {
748
+ std::string_view text;
749
+ if (result.start < ctx.input.size()) {
750
+ text = std::string_view(ctx.input).substr(result.start, result.end - result.start);
751
+ }
752
+
753
+ auto node_id = ctx.ast.add_node(
754
+ "",
755
+ p.tag,
756
+ result.start,
757
+ result.end,
758
+ text,
759
+ std::move(result.nodes),
760
+ result.need_more_input()
761
+ );
762
+
763
+ return common_peg_parse_result(result.type, result.start, result.end, { node_id });
764
+ }
765
+
766
+ return result;
767
+ }
768
+
769
+ common_peg_parse_result operator()(const common_peg_ref_parser & p) {
770
+ auto rule_id = arena.get_rule(p.name);
771
+ return arena.parse(rule_id, ctx, start_pos);
772
+ }
773
+
774
+ common_peg_parse_result operator()(const common_peg_atomic_parser & p) {
775
+ auto result = arena.parse(p.child, ctx, start_pos);
776
+ if (result.need_more_input()) {
777
+ // Clear nodes so they don't propagate up.
778
+ result.nodes.clear();
779
+ }
780
+ return result;
781
+ }
782
+
783
+ common_peg_parse_result operator()(const common_peg_gbnf_parser & p) {
784
+ return arena.parse(p.child, ctx, start_pos);
785
+ }
786
+
787
+ common_peg_parse_result operator()(const common_peg_ac_parser & p) {
788
+ return arena.parse(p.child, ctx, start_pos);
789
+ }
790
+ };
791
+
792
+ common_peg_parse_result common_peg_arena::parse(common_peg_parse_context & ctx, size_t start) const {
793
+ if (root_ == COMMON_PEG_INVALID_PARSER_ID) {
794
+ throw std::runtime_error("No root parser set");
795
+ }
796
+ return parse(root_, ctx, start);
797
+ }
798
+
799
+ common_peg_parse_result common_peg_arena::parse(common_peg_parser_id id, common_peg_parse_context & ctx, size_t start) const {
800
+ // Execute parser
801
+ const auto & parser = parsers_.at(id);
802
+ parser_executor exec(*this, ctx, start);
803
+ return std::visit(exec, parser);
804
+ }
805
+
806
+ common_peg_parser_id common_peg_arena::resolve_ref(common_peg_parser_id id) {
807
+ const auto & parser = parsers_.at(id);
808
+ if (auto ref = std::get_if<common_peg_ref_parser>(&parser)) {
809
+ return get_rule(ref->name);
810
+ }
811
+ return id;
812
+ }
813
+
814
+ static void bfs_node(common_peg_ast_arena &arena, std::ostringstream & oss, const common_peg_ast_node & node, int indent) {
815
+ for (int i = 0; i < indent; i++) {
816
+ oss << " ";
817
+ }
818
+ oss << "NODE " << node.id;
819
+ if (!node.rule.empty()) {
820
+ oss << " (rule " << node.rule << ")";
821
+ }
822
+ if (!node.tag.empty()) {
823
+ oss << " (tag " << node.tag << ")";
824
+ }
825
+ oss << " ['" << node.text << "']\n";
826
+ for (const auto child : node.children) {
827
+ bfs_node(arena, oss, arena.get(child), indent + 1);
828
+ }
829
+ }
830
+
831
+ std::string common_peg_ast_arena::dump() {
832
+ std::ostringstream oss;
833
+ for (auto & node : nodes_) {
834
+ bfs_node(*this, oss, node, 0);
835
+ }
836
+ return oss.str();
837
+ }
838
+
839
+ void common_peg_arena::resolve_refs() {
840
+ // Walk through all parsers and replace refs with their corresponding rule IDs
841
+ for (auto & parser : parsers_) {
842
+ std::visit([this](auto & p) {
843
+ using T = std::decay_t<decltype(p)>;
844
+
845
+ if constexpr (std::is_same_v<T, common_peg_sequence_parser>) {
846
+ for (auto & child : p.children) {
847
+ child = resolve_ref(child);
848
+ }
849
+ } else if constexpr (std::is_same_v<T, common_peg_choice_parser>) {
850
+ for (auto & child : p.children) {
851
+ child = resolve_ref(child);
852
+ }
853
+ } else if constexpr (std::is_same_v<T, common_peg_repetition_parser> ||
854
+ std::is_same_v<T, common_peg_and_parser> ||
855
+ std::is_same_v<T, common_peg_not_parser> ||
856
+ std::is_same_v<T, common_peg_tag_parser> ||
857
+ std::is_same_v<T, common_peg_atomic_parser> ||
858
+ std::is_same_v<T, common_peg_gbnf_parser> ||
859
+ std::is_same_v<T, common_peg_ac_parser>) {
860
+ p.child = resolve_ref(p.child);
861
+ } else if constexpr (std::is_same_v<T, common_peg_rule_parser>) {
862
+ p.child = resolve_ref(p.child);
863
+ } else if constexpr (std::is_same_v<T, common_peg_schema_parser>) {
864
+ p.child = resolve_ref(p.child);
865
+ } else if constexpr (std::is_same_v<T, common_peg_epsilon_parser> ||
866
+ std::is_same_v<T, common_peg_start_parser> ||
867
+ std::is_same_v<T, common_peg_end_parser> ||
868
+ std::is_same_v<T, common_peg_ref_parser> ||
869
+ std::is_same_v<T, common_peg_until_parser> ||
870
+ std::is_same_v<T, common_peg_literal_parser> ||
871
+ std::is_same_v<T, common_peg_string_parser> ||
872
+ std::is_same_v<T, common_peg_chars_parser> ||
873
+ std::is_same_v<T, common_peg_any_parser> ||
874
+ std::is_same_v<T, common_peg_space_parser>) {
875
+ // These rules do not have children
876
+ } else {
877
+ static_assert(is_always_false_v<T>);
878
+ }
879
+ }, parser);
880
+ }
881
+
882
+ // Also flatten root if it's a ref
883
+ if (root_ != COMMON_PEG_INVALID_PARSER_ID) {
884
+ root_ = resolve_ref(root_);
885
+ }
886
+ }
887
+
888
+ std::string common_peg_arena::dump(common_peg_parser_id id) const {
889
+ std::set<common_peg_parser_id> visited;
890
+ return dump_impl(id, visited);
891
+ }
892
+
893
+ std::string common_peg_arena::dump_impl(common_peg_parser_id id,
894
+ std::set<common_peg_parser_id> & visited) const {
895
+ // Check for cycles
896
+ if (visited.count(id)) {
897
+ return "[cycle]";
898
+ }
899
+ visited.insert(id);
900
+
901
+ const auto & parser = parsers_.at(id);
902
+
903
+ return std::visit([this, &visited](const auto & p) -> std::string {
904
+ using T = std::decay_t<decltype(p)>;
905
+
906
+ if constexpr (std::is_same_v<T, common_peg_epsilon_parser>) {
907
+ return "Epsilon";
908
+ } else if constexpr (std::is_same_v<T, common_peg_start_parser>) {
909
+ return "Start";
910
+ } else if constexpr (std::is_same_v<T, common_peg_end_parser>) {
911
+ return "End";
912
+ } else if constexpr (std::is_same_v<T, common_peg_literal_parser>) {
913
+ return "Literal(" + p.literal + ")";
914
+ } else if constexpr (std::is_same_v<T, common_peg_sequence_parser>) {
915
+ std::vector<std::string> parts;
916
+ for (const auto & child : p.children) {
917
+ parts.push_back(dump_impl(child, visited));
918
+ }
919
+ return "Sequence(" + string_join(parts, ", ") + ")";
920
+ } else if constexpr (std::is_same_v<T, common_peg_choice_parser>) {
921
+ std::vector<std::string> parts;
922
+ for (const auto & child : p.children) {
923
+ parts.push_back(dump_impl(child, visited));
924
+ }
925
+ return "Choice(" + string_join(parts, ", ") + ")";
926
+ } else if constexpr (std::is_same_v<T, common_peg_repetition_parser>) {
927
+ if (p.max_count == -1) {
928
+ return "Repetition(" + dump_impl(p.child, visited) + ", " + std::to_string(p.min_count) +
929
+ ", unbounded)";
930
+ }
931
+ return "Repetition(" + dump_impl(p.child, visited) + ", " + std::to_string(p.min_count) + ", " + std::to_string(p.max_count) + ")";
932
+ } else if constexpr (std::is_same_v<T, common_peg_and_parser>) {
933
+ return "And(" + dump_impl(p.child, visited) + ")";
934
+ } else if constexpr (std::is_same_v<T, common_peg_not_parser>) {
935
+ return "Not(" + dump_impl(p.child, visited) + ")";
936
+ } else if constexpr (std::is_same_v<T, common_peg_atomic_parser>) {
937
+ return "Atomic(" + dump_impl(p.child, visited) + ")";
938
+ } else if constexpr (std::is_same_v<T, common_peg_gbnf_parser>) {
939
+ return "Gbnf(" + p.grammar + ", " + dump_impl(p.child, visited) + ")";
940
+ } else if constexpr (std::is_same_v<T, common_peg_ac_parser>) {
941
+ return "Ac(" + string_join(p.delimiters, " | ") + ", " + dump_impl(p.child, visited) + ")";
942
+ } else if constexpr (std::is_same_v<T, common_peg_any_parser>) {
943
+ return "Any";
944
+ } else if constexpr (std::is_same_v<T, common_peg_space_parser>) {
945
+ return "Space";
946
+ } else if constexpr (std::is_same_v<T, common_peg_chars_parser>) {
947
+ if (p.max_count == -1) {
948
+ return "CharRepeat(" + p.pattern + ", " + std::to_string(p.min_count) + ", unbounded)";
949
+ }
950
+ return "CharRepeat(" + p.pattern + ", " + std::to_string(p.min_count) + ", " + std::to_string(p.max_count) + ")";
951
+ } else if constexpr (std::is_same_v<T, common_peg_string_parser>) {
952
+ return "String(" + std::string(1, p.delimiter) + ")";
953
+ } else if constexpr (std::is_same_v<T, common_peg_until_parser>) {
954
+ return "Until(" + string_join(p.delimiters, " | ") + ")";
955
+ } else if constexpr (std::is_same_v<T, common_peg_schema_parser>) {
956
+ return "Schema(" + dump_impl(p.child, visited) + ", " + (p.node ? common_chat_schema::kind_name(p.node->kind()) : "null") + ")";
957
+ } else if constexpr (std::is_same_v<T, common_peg_rule_parser>) {
958
+ return "Rule(" + p.name + ", " + dump_impl(p.child, visited) + ")";
959
+ } else if constexpr (std::is_same_v<T, common_peg_ref_parser>) {
960
+ return "Ref(" + p.name + ")";
961
+ } else if constexpr (std::is_same_v<T, common_peg_tag_parser>) {
962
+ return "Tag(" + p.tag + ", " + dump(p.child) + ")";
963
+ } else if constexpr (std::is_same_v<T, common_peg_atomic_parser>) {
964
+ return "Atomic(" + dump(p.child) + ")";
965
+ } else {
966
+ return "Unknown";
967
+ }
968
+ }, parser);
969
+ }
970
+
971
+ common_peg_parser & common_peg_parser::operator=(const common_peg_parser & other) {
972
+ id_ = other.id_;
973
+ return *this;
974
+ }
975
+
976
+ common_peg_parser & common_peg_parser::operator+=(const common_peg_parser & other) {
977
+ id_ = builder_.sequence({id_, other.id_});
978
+ return *this;
979
+ }
980
+
981
+ common_peg_parser & common_peg_parser::operator|=(const common_peg_parser & other) {
982
+ id_ = builder_.choice({id_, other.id_});
983
+ return *this;
984
+ }
985
+
986
+ common_peg_parser common_peg_parser::operator+(const common_peg_parser & other) const {
987
+ return builder_.sequence({id_, other.id_});
988
+ }
989
+
990
+ common_peg_parser common_peg_parser::operator|(const common_peg_parser & other) const {
991
+ return builder_.choice({id_, other.id_});
992
+ }
993
+
994
+ common_peg_parser common_peg_parser::operator<<(const common_peg_parser & other) const {
995
+ return builder_.sequence({id_, builder_.space(), other.id_});
996
+ }
997
+
998
+ common_peg_parser common_peg_parser::operator+(const char * str) const {
999
+ return *this + builder_.literal(str);
1000
+ }
1001
+
1002
+ common_peg_parser common_peg_parser::operator+(const std::string & str) const {
1003
+ return *this + builder_.literal(str);
1004
+ }
1005
+
1006
+ common_peg_parser common_peg_parser::operator<<(const char * str) const {
1007
+ return *this << builder_.literal(str);
1008
+ }
1009
+
1010
+ common_peg_parser common_peg_parser::operator<<(const std::string & str) const {
1011
+ return *this << builder_.literal(str);
1012
+ }
1013
+
1014
+ common_peg_parser common_peg_parser::operator|(const char * str) const {
1015
+ return *this | builder_.literal(str);
1016
+ }
1017
+
1018
+ common_peg_parser common_peg_parser::operator|(const std::string & str) const {
1019
+ return *this | builder_.literal(str);
1020
+ }
1021
+
1022
+ common_peg_parser operator+(const char * str, const common_peg_parser & p) {
1023
+ return p.builder().literal(str) + p;
1024
+ }
1025
+
1026
+ common_peg_parser operator+(const std::string & str, const common_peg_parser & p) {
1027
+ return operator+(str.c_str(), p);
1028
+ }
1029
+
1030
+ common_peg_parser operator<<(const char * str, const common_peg_parser & p) {
1031
+ return p.builder().literal(str) << p;
1032
+ }
1033
+
1034
+ common_peg_parser operator<<(const std::string & str, const common_peg_parser & p) {
1035
+ return operator<<(str.c_str(), p);
1036
+ }
1037
+
1038
+ common_peg_parser operator|(const char * str, const common_peg_parser & p) {
1039
+ return p.builder().literal(str) | p;
1040
+ }
1041
+
1042
+ common_peg_parser operator|(const std::string & str, const common_peg_parser & p) {
1043
+ return operator|(str.c_str(), p);
1044
+ }
1045
+
1046
+ static std::string rule_name(const std::string & name) {
1047
+ static const std::regex invalid_rule_chars_re("[^a-zA-Z0-9-]+");
1048
+ return std::regex_replace(name, invalid_rule_chars_re, "-");
1049
+ }
1050
+
1051
+ common_peg_parser_builder::common_peg_parser_builder() {}
1052
+
1053
+ common_peg_parser common_peg_parser_builder::sequence(const std::vector<common_peg_parser_id> & parsers) {
1054
+ // Flatten nested sequences
1055
+ std::vector<common_peg_parser_id> flattened;
1056
+ for (const auto & p : parsers) {
1057
+ const auto & parser = arena_.get(p);
1058
+ if (auto seq = std::get_if<common_peg_sequence_parser>(&parser)) {
1059
+ flattened.insert(flattened.end(), seq->children.begin(), seq->children.end());
1060
+ } else {
1061
+ flattened.push_back(p);
1062
+ }
1063
+ }
1064
+ return wrap(arena_.add_parser(common_peg_sequence_parser{flattened}));
1065
+ }
1066
+
1067
+ common_peg_parser common_peg_parser_builder::sequence(const std::vector<common_peg_parser> & parsers) {
1068
+ std::vector<common_peg_parser_id> ids;
1069
+ ids.reserve(parsers.size());
1070
+ for (const auto & p : parsers) {
1071
+ ids.push_back(p.id());
1072
+ }
1073
+ return sequence(ids);
1074
+ }
1075
+
1076
+ common_peg_parser common_peg_parser_builder::sequence(std::initializer_list<common_peg_parser> parsers) {
1077
+ std::vector<common_peg_parser_id> ids;
1078
+ ids.reserve(parsers.size());
1079
+ for (const auto & p : parsers) {
1080
+ ids.push_back(p.id());
1081
+ }
1082
+ return sequence(ids);
1083
+ }
1084
+
1085
+ common_peg_parser common_peg_parser_builder::choice(const std::vector<common_peg_parser_id> & parsers) {
1086
+ // Flatten nested choices
1087
+ std::vector<common_peg_parser_id> flattened;
1088
+ for (const auto & p : parsers) {
1089
+ const auto & parser = arena_.get(p);
1090
+ if (auto choice = std::get_if<common_peg_choice_parser>(&parser)) {
1091
+ flattened.insert(flattened.end(), choice->children.begin(), choice->children.end());
1092
+ } else {
1093
+ flattened.push_back(p);
1094
+ }
1095
+ }
1096
+ return wrap(arena_.add_parser(common_peg_choice_parser{flattened}));
1097
+ }
1098
+
1099
+ common_peg_parser common_peg_parser_builder::choice(const std::vector<common_peg_parser> & parsers) {
1100
+ std::vector<common_peg_parser_id> ids;
1101
+ ids.reserve(parsers.size());
1102
+ for (const auto & p : parsers) {
1103
+ ids.push_back(p.id());
1104
+ }
1105
+ return choice(ids);
1106
+ }
1107
+
1108
+ common_peg_parser common_peg_parser_builder::choice(std::initializer_list<common_peg_parser> parsers) {
1109
+ std::vector<common_peg_parser_id> ids;
1110
+ ids.reserve(parsers.size());
1111
+ for (const auto & p : parsers) {
1112
+ ids.push_back(p.id());
1113
+ }
1114
+ return choice(ids);
1115
+ }
1116
+
1117
+ common_peg_parser common_peg_parser_builder::chars(const std::string & classes, int min, int max) {
1118
+ auto [ranges, negated] = parse_char_classes(classes);
1119
+ return wrap(arena_.add_parser(common_peg_chars_parser{classes, ranges, negated, min, max}));
1120
+ }
1121
+
1122
+ common_peg_parser common_peg_parser_builder::schema(const common_peg_parser & p, const std::string & name, common_chat_schema_document_ptr doc, const common_chat_schema & node, bool raw) {
1123
+ return wrap(arena_.add_parser(common_peg_schema_parser{p.id(), name, std::move(doc), &node, raw}));
1124
+ }
1125
+
1126
+ common_peg_parser common_peg_parser_builder::schema(const common_peg_parser & p, const std::string & name, const common_json & schema, bool raw) {
1127
+ auto doc = std::make_shared<const common_chat_schema_document>(common_chat_schema_from_json(schema));
1128
+ return this->schema(p, name, doc, *doc->root, raw);
1129
+ }
1130
+
1131
+ common_peg_parser common_peg_parser_builder::rule(const std::string & name, const common_peg_parser & p, bool trigger) {
1132
+ auto clean_name = rule_name(name);
1133
+ auto rule_id = arena_.add_parser(common_peg_rule_parser{clean_name, p.id(), trigger});
1134
+ arena_.add_rule(clean_name, rule_id);
1135
+ return ref(clean_name);
1136
+ }
1137
+
1138
+ common_peg_parser common_peg_parser_builder::rule(const std::string & name, const std::function<common_peg_parser()> & builder_fn, bool trigger) {
1139
+ auto clean_name = rule_name(name);
1140
+ if (arena_.has_rule(clean_name)) {
1141
+ return ref(clean_name);
1142
+ }
1143
+
1144
+ // Create placeholder rule to allow recursive references
1145
+ auto placeholder = any(); // Temporary placeholder
1146
+ auto placeholder_rule_id = arena_.add_parser(common_peg_rule_parser{clean_name, placeholder.id(), trigger});
1147
+ arena_.add_rule(clean_name, placeholder_rule_id);
1148
+
1149
+ // Build the actual parser
1150
+ auto parser = builder_fn();
1151
+
1152
+ // Replace placeholder with actual rule
1153
+ auto rule_id = arena_.add_parser(common_peg_rule_parser{clean_name, parser.id(), trigger});
1154
+ arena_.rules_[clean_name] = rule_id;
1155
+
1156
+ return ref(clean_name);
1157
+ }
1158
+
1159
+ void common_peg_parser_builder::set_root(const common_peg_parser & p) {
1160
+ arena_.set_root(p.id());
1161
+ }
1162
+
1163
+ common_peg_arena common_peg_parser_builder::build() {
1164
+ arena_.resolve_refs();
1165
+ return std::move(arena_);
1166
+ }
1167
+
1168
+ // String primitives
1169
+
1170
+ common_peg_parser common_peg_parser_builder::string_content(char delimiter) {
1171
+ return wrap(arena_.add_parser(common_peg_string_parser{delimiter}));
1172
+ }
1173
+
1174
+ common_peg_parser common_peg_parser_builder::double_quoted_string() {
1175
+ return rule("double-quoted-string", [this]() {
1176
+ return sequence({literal("\""), string_content('"'), literal("\"")});
1177
+ });
1178
+ }
1179
+
1180
+ common_peg_parser common_peg_parser_builder::single_quoted_string() {
1181
+ return rule("single-quoted-string", [this]() {
1182
+ return sequence({literal("'"), string_content('\''), literal("'")});
1183
+ });
1184
+ }
1185
+
1186
+ common_peg_parser common_peg_parser_builder::quoted_string() {
1187
+ return rule("quoted-string", [this]() {
1188
+ return choice({double_quoted_string(), single_quoted_string()});
1189
+ });
1190
+ }
1191
+
1192
+ // JSON parsers
1193
+
1194
+ common_peg_parser common_peg_parser_builder::json_number() {
1195
+ return rule("json-number", [this]() {
1196
+ auto digit1_9 = chars("[1-9]", 1, 1);
1197
+ auto digits = chars("[0-9]");
1198
+ auto int_part = choice({literal("0"), sequence({digit1_9, chars("[0-9]", 0, -1)})});
1199
+ auto frac = sequence({literal("."), digits});
1200
+ auto exp = sequence({choice({literal("e"), literal("E")}), optional(chars("[+-]", 1, 1)), digits});
1201
+ // Negative lookahead: only commit the number when the next character can't extend it.
1202
+ // At EOF in partial mode, chars returns NEED_MORE → negate propagates NEED_MORE → number not committed.
1203
+ // This prevents premature commits of partial numbers (e.g. "3" when "3.14" is incoming).
1204
+ auto not_number_continuation = negate(chars("[0-9.eE+-]", 1, 1));
1205
+ return sequence({ optional(literal("-")), int_part, optional(frac), optional(exp), not_number_continuation });
1206
+ });
1207
+ }
1208
+
1209
+ common_peg_parser common_peg_parser_builder::json_string() {
1210
+ return rule("json-string", [this]() {
1211
+ return sequence({literal("\""), string_content('"'), literal("\"")});
1212
+ });
1213
+ }
1214
+
1215
+ common_peg_parser common_peg_parser_builder::json_bool() {
1216
+ return rule("json-bool", [this]() {
1217
+ return choice({literal("true"), literal("false")});
1218
+ });
1219
+ }
1220
+
1221
+ common_peg_parser common_peg_parser_builder::json_null() {
1222
+ return rule("json-null", [this]() {
1223
+ return literal("null");
1224
+ });
1225
+ }
1226
+
1227
+ common_peg_parser common_peg_parser_builder::json_object() {
1228
+ return rule("json-object", [this]() {
1229
+ auto ws = space();
1230
+ auto member = sequence({json_string(), ws, literal(":"), ws, json()});
1231
+ auto members = sequence({member, zero_or_more(sequence({ws, literal(","), ws, member}))});
1232
+ return sequence({
1233
+ literal("{"),
1234
+ ws,
1235
+ choice({
1236
+ literal("}"),
1237
+ sequence({members, ws, literal("}")})
1238
+ })
1239
+ });
1240
+ });
1241
+ }
1242
+
1243
+ common_peg_parser common_peg_parser_builder::json_array() {
1244
+ return rule("json-array", [this]() {
1245
+ auto ws = space();
1246
+ auto elements = sequence({json(), zero_or_more(sequence({ws, literal(","), ws, json()}))});
1247
+ return sequence({
1248
+ literal("["),
1249
+ ws,
1250
+ choice({
1251
+ literal("]"),
1252
+ sequence({elements, ws, literal("]")})
1253
+ })
1254
+ });
1255
+ });
1256
+ }
1257
+
1258
+ common_peg_parser common_peg_parser_builder::json() {
1259
+ return rule("json-value", [this]() {
1260
+ return choice({
1261
+ json_object(),
1262
+ json_array(),
1263
+ json_string(),
1264
+ json_number(),
1265
+ json_bool(),
1266
+ json_null()
1267
+ });
1268
+ });
1269
+ }
1270
+
1271
+ common_peg_parser common_peg_parser_builder::python_string() {
1272
+ return rule("python-string", [this]() {
1273
+ return choice({double_quoted_string(), single_quoted_string()});
1274
+ });
1275
+ }
1276
+
1277
+ common_peg_parser common_peg_parser_builder::python_number() {
1278
+ return json_number();
1279
+ }
1280
+
1281
+ common_peg_parser common_peg_parser_builder::python_bool() {
1282
+ return rule("python-bool", [this]() {
1283
+ return choice({literal("True"), literal("False")});
1284
+ });
1285
+ }
1286
+
1287
+ common_peg_parser common_peg_parser_builder::python_null() {
1288
+ return rule("python-none", [this]() {
1289
+ return literal("None");
1290
+ });
1291
+ }
1292
+
1293
+ common_peg_parser common_peg_parser_builder::python_dict() {
1294
+ return rule("python-dict", [this]() {
1295
+ auto ws = space();
1296
+ auto member = sequence({python_string(), ws, literal(":"), ws, python_value()});
1297
+ auto members = sequence({member, zero_or_more(sequence({ws, literal(","), ws, member}))});
1298
+ return sequence({
1299
+ literal("{"),
1300
+ ws,
1301
+ choice({
1302
+ literal("}"),
1303
+ sequence({members, ws, literal("}")})
1304
+ }),
1305
+ ws
1306
+ });
1307
+ });
1308
+ }
1309
+
1310
+ common_peg_parser common_peg_parser_builder::python_array() {
1311
+ return rule("python-array", [this]() {
1312
+ auto ws = space();
1313
+ auto elements = sequence({python_value(), zero_or_more(sequence({literal(","), ws, python_value()}))});
1314
+ return sequence({
1315
+ literal("["),
1316
+ ws,
1317
+ choice({
1318
+ literal("]"),
1319
+ sequence({elements, ws, literal("]")})
1320
+ }),
1321
+ ws
1322
+ });
1323
+ });
1324
+ }
1325
+
1326
+ common_peg_parser common_peg_parser_builder::python_value() {
1327
+ return rule("python-value", [this]() {
1328
+ return choice({
1329
+ python_dict(),
1330
+ python_array(),
1331
+ python_string(),
1332
+ python_number(),
1333
+ python_bool(),
1334
+ python_null()
1335
+ });
1336
+ });
1337
+ }
1338
+
1339
+ common_peg_parser common_peg_parser_builder::marker() {
1340
+ auto sharp_bracket_parser = literal("<") + until(">") + literal(">");
1341
+ auto square_bracket_parser = literal("[") + until("]") + literal("]");
1342
+ return choice({ sharp_bracket_parser, square_bracket_parser });
1343
+ }
1344
+
1345
+ common_peg_parser common_peg_parser_builder::json_member(const std::string & key, const common_peg_parser & p) {
1346
+ auto ws = space();
1347
+ return sequence({
1348
+ literal("\"" + key + "\""),
1349
+ ws,
1350
+ literal(":"),
1351
+ ws,
1352
+ p,
1353
+ });
1354
+ }
1355
+
1356
+ common_peg_parser common_peg_parser_builder::ac(const common_peg_parser & p, const std::vector<std::string> & delimiters) {
1357
+ if (delimiters.empty()) {
1358
+ throw std::runtime_error("ac parser requires at least one delimiter");
1359
+ }
1360
+ return add(common_peg_ac_parser{p, delimiters});
1361
+ }
1362
+
1363
+ static std::string gbnf_escape_char_class(uint32_t c) {
1364
+ if (c == '-' || c == ']' || c == '[' || c == '\\') {
1365
+ return "\\" + std::string(1, (char) c);
1366
+ }
1367
+ // Escape whitespace control characters
1368
+ if (c == '\n') {
1369
+ return "\\n";
1370
+ }
1371
+ if (c == '\t') {
1372
+ return "\\t";
1373
+ }
1374
+ if (c == '\r') {
1375
+ return "\\r";
1376
+ }
1377
+
1378
+ // Printable ASCII
1379
+ if (c >= 0x20 && c <= 0x7E) {
1380
+ return std::string(1, (char) c);
1381
+ }
1382
+
1383
+ // Hex escape
1384
+ char buf[16];
1385
+ const char * hex = "0123456789ABCDEF";
1386
+
1387
+ if (c <= 0xFF) {
1388
+ buf[0] = '\\';
1389
+ buf[1] = 'x';
1390
+ buf[2] = hex[(c >> 4) & 0xF];
1391
+ buf[3] = hex[c & 0xF];
1392
+ buf[4] = '\0';
1393
+ } else if (c <= 0xFFFF) {
1394
+ buf[0] = '\\';
1395
+ buf[1] = 'u';
1396
+ buf[2] = hex[(c >> 12) & 0xF];
1397
+ buf[3] = hex[(c >> 8) & 0xF];
1398
+ buf[4] = hex[(c >> 4) & 0xF];
1399
+ buf[5] = hex[c & 0xF];
1400
+ buf[6] = '\0';
1401
+ } else {
1402
+ buf[0] = '\\';
1403
+ buf[1] = 'U';
1404
+ for (int i = 0; i < 8; i++) {
1405
+ buf[2 + i] = hex[(c >> ((7 - i) * 4)) & 0xF];
1406
+ }
1407
+ buf[10] = '\0';
1408
+ }
1409
+
1410
+ return std::string(buf);
1411
+ }
1412
+
1413
+ static std::string gbnf_char_class(const std::vector<uint32_t> & chars, bool negate) {
1414
+ std::string s = negate ? "[^" : "[";
1415
+ for (uint32_t ch : chars) {
1416
+ s += gbnf_escape_char_class(ch);
1417
+ }
1418
+ return s + "]";
1419
+ }
1420
+
1421
+ static std::string gbnf_ac_grammar(
1422
+ const common_grammar_builder & builder,
1423
+ const std::string & prefix,
1424
+ const std::vector<std::string> & strings,
1425
+ const std::function<std::string(const std::vector<uint32_t> &,
1426
+ const std::map<size_t, std::vector<uint32_t>> &,
1427
+ const std::vector<uint32_t> &,
1428
+ const std::function<std::string(size_t)> &)> & build_rule) {
1429
+ common_aho_corasick ac(strings);
1430
+
1431
+ auto state_name = [&](size_t s) -> std::string {
1432
+ if (s == 0) {
1433
+ return prefix;
1434
+ }
1435
+ std::string num = std::to_string(s);
1436
+ num = num.size() == 1 ? ("0" + num) : num;
1437
+ return prefix + "-" + num;
1438
+ };
1439
+
1440
+ for (size_t q = 0; q < ac.num_states(); q++) {
1441
+ if (ac.is_terminal(q)) {
1442
+ continue; // match states
1443
+ }
1444
+
1445
+ std::map<size_t, std::vector<uint32_t>> buckets;
1446
+ std::vector<uint32_t> completing; // chars that complete a delimiter
1447
+ std::vector<uint32_t> specific; // chars with an explicit transition
1448
+ for (uint32_t c : ac.alphabet) {
1449
+ size_t d = ac.next(q, c);
1450
+ if (ac.is_terminal(d)) {
1451
+ completing.push_back(c);
1452
+ specific.push_back(c);
1453
+ } else if (d != 0) {
1454
+ buckets[d].push_back(c); // specific non-root destination
1455
+ specific.push_back(c);
1456
+ }
1457
+ }
1458
+
1459
+ builder.add_rule(state_name(q), build_rule(completing, buckets, specific, state_name));
1460
+ }
1461
+
1462
+ // An empty delimiter makes the start state terminal. Emit an entry rule
1463
+ // that matches the empty string so the returned reference stays valid.
1464
+ if (ac.is_terminal(0)) {
1465
+ builder.add_rule(prefix, "|");
1466
+ }
1467
+
1468
+ return state_name(0);
1469
+ }
1470
+
1471
+ // GBNF grammar matching strings that contain no string in `strings` as a
1472
+ // substring. Emits the complement of an Aho-Corasick automaton DFA and returns
1473
+ // the start state rule name.
1474
+ //
1475
+ // ref: https://github.com/ggml-org/llama.cpp/pull/24839
1476
+ static std::string gbnf_excluding_grammar(const common_grammar_builder & builder,
1477
+ const std::string & prefix,
1478
+ const std::vector<std::string> & strings) {
1479
+ return gbnf_ac_grammar(builder, prefix, strings,
1480
+ [](const std::vector<uint32_t> & /*completing*/,
1481
+ const std::map<size_t, std::vector<uint32_t>> & buckets,
1482
+ const std::vector<uint32_t> & specific,
1483
+ const std::function<std::string(size_t)> & state_name) {
1484
+ // every state is accepting and completing chars get no
1485
+ // alternative, so a forbidden string can never be matched
1486
+ std::string rhs = "|";
1487
+ for (const auto & [d, chars] : buckets) {
1488
+ rhs += " " + gbnf_char_class(chars, false) + " " + state_name(d) + " |";
1489
+ }
1490
+ rhs += " " + gbnf_char_class(specific, true) + " " + state_name(0);
1491
+ return rhs;
1492
+ });
1493
+ }
1494
+
1495
+ // GBNF grammar matching everything up to and including the first occurrence of
1496
+ // any string in `strings`. Emits the Aho-Corasick automaton DFA and returns
1497
+ // the start state rule name.
1498
+ static std::string gbnf_including_grammar(const common_grammar_builder & builder,
1499
+ const std::string & prefix,
1500
+ const std::vector<std::string> & strings) {
1501
+ return gbnf_ac_grammar(builder, prefix, strings,
1502
+ [](const std::vector<uint32_t> & completing,
1503
+ const std::map<size_t, std::vector<uint32_t>> & buckets,
1504
+ const std::vector<uint32_t> & specific,
1505
+ const std::function<std::string(size_t)> & state_name) {
1506
+ std::vector<std::string> alts;
1507
+ if (!completing.empty()) {
1508
+ alts.push_back(gbnf_char_class(completing, false)); // terminate on match
1509
+ }
1510
+ for (const auto & [d, chars] : buckets) {
1511
+ alts.push_back(gbnf_char_class(chars, false) + " " + state_name(d));
1512
+ }
1513
+ // every other character keeps scanning from the start state
1514
+ alts.push_back(gbnf_char_class(specific, true) + " " + state_name(0));
1515
+ return string_join(alts, " | ");
1516
+ });
1517
+ }
1518
+
1519
+ static std::set<std::string> collect_reachable_rules(
1520
+ const common_peg_arena & arena,
1521
+ const common_peg_parser_id & rule
1522
+ ) {
1523
+ std::set<std::string> reachable;
1524
+ std::set<std::string> visited;
1525
+
1526
+ std::function<void(common_peg_parser_id)> visit = [&](common_peg_parser_id id) {
1527
+ const auto & parser = arena.get(id);
1528
+
1529
+ std::visit([&](const auto & p) {
1530
+ using T = std::decay_t<decltype(p)>;
1531
+
1532
+ if constexpr (std::is_same_v<T, common_peg_epsilon_parser> ||
1533
+ std::is_same_v<T, common_peg_start_parser> ||
1534
+ std::is_same_v<T, common_peg_end_parser> ||
1535
+ std::is_same_v<T, common_peg_until_parser> ||
1536
+ std::is_same_v<T, common_peg_literal_parser> ||
1537
+ std::is_same_v<T, common_peg_chars_parser> ||
1538
+ std::is_same_v<T, common_peg_space_parser> ||
1539
+ std::is_same_v<T, common_peg_any_parser> ||
1540
+ std::is_same_v<T, common_peg_string_parser>) {
1541
+ // These parsers do not have any children
1542
+ } else if constexpr (std::is_same_v<T, common_peg_sequence_parser>) {
1543
+ for (auto child : p.children) {
1544
+ visit(child);
1545
+ }
1546
+ } else if constexpr (std::is_same_v<T, common_peg_choice_parser>) {
1547
+ for (auto child : p.children) {
1548
+ visit(child);
1549
+ }
1550
+ } else if constexpr (std::is_same_v<T, common_peg_repetition_parser> ||
1551
+ std::is_same_v<T, common_peg_and_parser> ||
1552
+ std::is_same_v<T, common_peg_not_parser> ||
1553
+ std::is_same_v<T, common_peg_tag_parser> ||
1554
+ std::is_same_v<T, common_peg_atomic_parser> ||
1555
+ std::is_same_v<T, common_peg_gbnf_parser> ||
1556
+ std::is_same_v<T, common_peg_ac_parser> ||
1557
+ std::is_same_v<T, common_peg_schema_parser>) {
1558
+ visit(p.child);
1559
+ } else if constexpr (std::is_same_v<T, common_peg_rule_parser>) {
1560
+ if (visited.find(p.name) == visited.end()) {
1561
+ visited.insert(p.name);
1562
+ reachable.insert(p.name);
1563
+ visit(p.child);
1564
+ }
1565
+ } else if constexpr (std::is_same_v<T, common_peg_ref_parser>) {
1566
+ // Traverse rules so we pick up everything
1567
+ auto referenced_rule = arena.get_rule(p.name);
1568
+ visit(referenced_rule);
1569
+ } else {
1570
+ static_assert(is_always_false_v<T>);
1571
+ }
1572
+ }, parser);
1573
+ };
1574
+
1575
+ visit(rule);
1576
+ return reachable;
1577
+ }
1578
+
1579
+ // GBNF generation implementation
1580
+ void common_peg_arena::build_grammar(const common_grammar_builder & builder, bool lazy) const {
1581
+ // A raw string value is parsed by the child rather than constrained by the schema
1582
+ auto schema_delegates = [](const common_peg_schema_parser & s) -> bool {
1583
+ return !s.node || (s.raw && s.node->may_be_string());
1584
+ };
1585
+
1586
+ // Unwrap the parser so we can properly check if it's a sequence or choice
1587
+ auto effective_parser = [&](common_peg_parser_id id) -> const common_peg_parser_variant & {
1588
+ while (true) {
1589
+ const auto & p = parsers_.at(id);
1590
+ if (const auto * tag = std::get_if<common_peg_tag_parser>(&p)) {
1591
+ id = tag->child;
1592
+ } else if (const auto * atomic = std::get_if<common_peg_atomic_parser>(&p)) {
1593
+ id = atomic->child;
1594
+ } else if (const auto * schema = std::get_if<common_peg_schema_parser>(&p)) {
1595
+ if (schema_delegates(*schema)) {
1596
+ id = schema->child;
1597
+ } else {
1598
+ return p;
1599
+ }
1600
+ } else {
1601
+ return p;
1602
+ }
1603
+ }
1604
+ };
1605
+
1606
+ // Generate GBNF for a parser
1607
+ std::function<std::string(common_peg_parser_id)> to_gbnf = [&](common_peg_parser_id id) -> std::string {
1608
+ const auto & parser = parsers_.at(id);
1609
+
1610
+ return std::visit([&](const auto & p) -> std::string {
1611
+ using T = std::decay_t<decltype(p)>;
1612
+
1613
+ if constexpr (std::is_same_v<T, common_peg_epsilon_parser> ||
1614
+ std::is_same_v<T, common_peg_start_parser> ||
1615
+ std::is_same_v<T, common_peg_end_parser>) {
1616
+ return "";
1617
+ } else if constexpr (std::is_same_v<T, common_peg_literal_parser>) {
1618
+ return gbnf_format_literal(p.literal);
1619
+ } else if constexpr (std::is_same_v<T, common_peg_sequence_parser>) {
1620
+ std::string s;
1621
+ for (const auto & child : p.children) {
1622
+ auto child_gbnf = to_gbnf(child);
1623
+ if (child_gbnf.empty()) {
1624
+ continue;
1625
+ }
1626
+ if (!s.empty()) {
1627
+ s += " ";
1628
+ }
1629
+ const auto & child_parser = effective_parser(child);
1630
+ if (std::holds_alternative<common_peg_choice_parser>(child_parser) ||
1631
+ std::holds_alternative<common_peg_sequence_parser>(child_parser)) {
1632
+ s += "(" + child_gbnf + ")";
1633
+ } else {
1634
+ s += child_gbnf;
1635
+ }
1636
+ }
1637
+ return s;
1638
+ } else if constexpr (std::is_same_v<T, common_peg_choice_parser>) {
1639
+ std::string s;
1640
+ for (const auto & child : p.children) {
1641
+ if (!s.empty()) {
1642
+ s += " | ";
1643
+ }
1644
+ auto child_gbnf = to_gbnf(child);
1645
+ const auto & child_parser = effective_parser(child);
1646
+ if (std::holds_alternative<common_peg_choice_parser>(child_parser)) {
1647
+ s += "(" + child_gbnf + ")";
1648
+ } else {
1649
+ s += child_gbnf;
1650
+ }
1651
+ }
1652
+ return s;
1653
+ } else if constexpr (std::is_same_v<T, common_peg_repetition_parser>) {
1654
+ auto child_gbnf = to_gbnf(p.child);
1655
+ const auto & child_parser = effective_parser(p.child);
1656
+ if (std::holds_alternative<common_peg_choice_parser>(child_parser) ||
1657
+ std::holds_alternative<common_peg_sequence_parser>(child_parser)) {
1658
+ child_gbnf = "(" + child_gbnf + ")";
1659
+ }
1660
+ if (p.min_count == 0 && p.max_count == 1) {
1661
+ return child_gbnf + "?";
1662
+ }
1663
+ if (p.min_count == 0 && p.max_count == -1) {
1664
+ return child_gbnf + "*";
1665
+ }
1666
+ if (p.min_count == 1 && p.max_count == -1) {
1667
+ return child_gbnf + "+";
1668
+ }
1669
+ if (p.max_count == -1) {
1670
+ return child_gbnf + "{" + std::to_string(p.min_count) + ",}";
1671
+ }
1672
+ if (p.min_count == p.max_count) {
1673
+ if (p.min_count == 1) {
1674
+ return child_gbnf;
1675
+ }
1676
+ return child_gbnf + "{" + std::to_string(p.min_count) + "}";
1677
+ }
1678
+ return child_gbnf + "{" + std::to_string(p.min_count) + "," + std::to_string(p.max_count) + "}";
1679
+ } else if constexpr (std::is_same_v<T, common_peg_and_parser> || std::is_same_v<T, common_peg_not_parser>) {
1680
+ return ""; // Lookahead not supported in GBNF
1681
+ } else if constexpr (std::is_same_v<T, common_peg_any_parser>) {
1682
+ return ".";
1683
+ } else if constexpr (std::is_same_v<T, common_peg_space_parser>) {
1684
+ return "space";
1685
+ } else if constexpr (std::is_same_v<T, common_peg_chars_parser>) {
1686
+ std::string result = p.pattern;
1687
+ if (p.min_count == 0 && p.max_count == 1) {
1688
+ return result + "?";
1689
+ }
1690
+ if (p.min_count == 0 && p.max_count == -1) {
1691
+ return result + "*";
1692
+ }
1693
+ if (p.min_count == 1 && p.max_count == -1) {
1694
+ return result + "+";
1695
+ }
1696
+ if (p.max_count == -1) {
1697
+ return result + "{" + std::to_string(p.min_count) + ",}";
1698
+ }
1699
+ if (p.min_count == p.max_count) {
1700
+ if (p.min_count == 1) {
1701
+ return result;
1702
+ }
1703
+ return result + "{" + std::to_string(p.min_count) + "}";
1704
+ }
1705
+ return result + "{" + std::to_string(p.min_count) + "," + std::to_string(p.max_count) + "}";
1706
+ } else if constexpr (std::is_same_v<T, common_peg_string_parser>) {
1707
+ const std::string delim(1, p.delimiter);
1708
+ return R"(( [^)" + delim + R"(\\] | "\\" ( [)" + delim + R"(\\/ bfnrt] | "u" [0-9a-fA-F]{4} ) )*)";
1709
+ } else if constexpr (std::is_same_v<T, common_peg_until_parser>) {
1710
+ if (p.delimiters.empty()) {
1711
+ return ".*";
1712
+ }
1713
+ return gbnf_excluding_grammar(builder, "until-" + std::to_string(id), p.delimiters);
1714
+ } else if constexpr (std::is_same_v<T, common_peg_schema_parser>) {
1715
+ if (schema_delegates(p)) {
1716
+ return to_gbnf(p.child);
1717
+ }
1718
+ return builder.add_schema(p.name, *p.node);
1719
+ } else if constexpr (std::is_same_v<T, common_peg_rule_parser>) {
1720
+ return p.name;
1721
+ } else if constexpr (std::is_same_v<T, common_peg_ref_parser>) {
1722
+ // Refs should not exist after flattening, but kept just in case
1723
+ return p.name;
1724
+ } else if constexpr (std::is_same_v<T, common_peg_tag_parser>) {
1725
+ return to_gbnf(p.child);
1726
+ } else if constexpr (std::is_same_v<T, common_peg_atomic_parser>) {
1727
+ return to_gbnf(p.child);
1728
+ } else if constexpr (std::is_same_v<T, common_peg_gbnf_parser>) {
1729
+ return p.grammar;
1730
+ } else if constexpr (std::is_same_v<T, common_peg_ac_parser>) {
1731
+ return gbnf_including_grammar(builder, "ac-" + std::to_string(id), p.delimiters);
1732
+ } else {
1733
+ static_assert(is_always_false_v<T>);
1734
+ }
1735
+ }, parser);
1736
+ };
1737
+
1738
+ // Collect reachable rules
1739
+ std::set<std::string> reachable_rules;
1740
+
1741
+ if (lazy) {
1742
+ // Collect rules reachable from trigger rules
1743
+ for (const auto & [name, id] : rules_) {
1744
+ const auto & parser = parsers_.at(id);
1745
+ if (auto rule = std::get_if<common_peg_rule_parser>(&parser)) {
1746
+ if (rule->trigger) {
1747
+ // Mark trigger as reachable and visit it
1748
+ reachable_rules.insert(name);
1749
+ auto add_rules = collect_reachable_rules(*this, id);
1750
+ reachable_rules.insert(add_rules.begin(), add_rules.end());
1751
+ }
1752
+ }
1753
+ }
1754
+ } else {
1755
+ // Collect rules reachable from root
1756
+ reachable_rules = collect_reachable_rules(*this, root_);
1757
+ }
1758
+
1759
+ // Create GBNF rules for all reachable rules
1760
+ for (const auto & [name, rule_id] : rules_) {
1761
+ if (reachable_rules.find(name) == reachable_rules.end()) {
1762
+ continue;
1763
+ }
1764
+
1765
+ const auto & parser = parsers_.at(rule_id);
1766
+ if (auto rule = std::get_if<common_peg_rule_parser>(&parser)) {
1767
+ builder.add_rule(rule->name, to_gbnf(rule->child));
1768
+ }
1769
+ }
1770
+
1771
+ if (lazy) {
1772
+ // Generate root rule from trigger rules only
1773
+ std::vector<std::string> trigger_names;
1774
+ for (const auto & [name, rule_id] : rules_) {
1775
+ const auto & parser = parsers_.at(rule_id);
1776
+ if (auto rule = std::get_if<common_peg_rule_parser>(&parser)) {
1777
+ if (rule->trigger) {
1778
+ trigger_names.push_back(rule->name);
1779
+ }
1780
+ }
1781
+ }
1782
+
1783
+ // Sort for predictable order
1784
+ std::sort(trigger_names.begin(), trigger_names.end());
1785
+ builder.add_rule("root", string_join(trigger_names, " | "));
1786
+ } else if (root_ != COMMON_PEG_INVALID_PARSER_ID) {
1787
+ builder.add_rule("root", to_gbnf(root_));
1788
+ }
1789
+ }
1790
+
1791
+ static common_json serialize_parser_variant(const common_peg_parser_variant & variant) {
1792
+ using json = common_json;
1793
+
1794
+ return std::visit([](const auto & p) -> json {
1795
+ using T = std::decay_t<decltype(p)>;
1796
+
1797
+ if constexpr (std::is_same_v<T, common_peg_epsilon_parser>) {
1798
+ return json{{"type", "epsilon"}};
1799
+ } else if constexpr (std::is_same_v<T, common_peg_start_parser>) {
1800
+ return json{{"type", "start"}};
1801
+ } else if constexpr (std::is_same_v<T, common_peg_end_parser>) {
1802
+ return json{{"type", "end"}};
1803
+ } else if constexpr (std::is_same_v<T, common_peg_literal_parser>) {
1804
+ return json{{"type", "literal"}, {"literal", p.literal}};
1805
+ } else if constexpr (std::is_same_v<T, common_peg_sequence_parser>) {
1806
+ return json{{"type", "sequence"}, {"children", p.children}};
1807
+ } else if constexpr (std::is_same_v<T, common_peg_choice_parser>) {
1808
+ return json{{"type", "choice"}, {"children", p.children}};
1809
+ } else if constexpr (std::is_same_v<T, common_peg_repetition_parser>) {
1810
+ return json{
1811
+ {"type", "repetition"},
1812
+ {"child", p.child},
1813
+ {"min_count", p.min_count},
1814
+ {"max_count", p.max_count}
1815
+ };
1816
+ } else if constexpr (std::is_same_v<T, common_peg_and_parser>) {
1817
+ return json{{"type", "and"}, {"child", p.child}};
1818
+ } else if constexpr (std::is_same_v<T, common_peg_not_parser>) {
1819
+ return json{{"type", "not"}, {"child", p.child}};
1820
+ } else if constexpr (std::is_same_v<T, common_peg_any_parser>) {
1821
+ return json{{"type", "any"}};
1822
+ } else if constexpr (std::is_same_v<T, common_peg_space_parser>) {
1823
+ return json{{"type", "space"}};
1824
+ } else if constexpr (std::is_same_v<T, common_peg_chars_parser>) {
1825
+ json ranges = json::array();
1826
+ for (const auto & range : p.ranges) {
1827
+ ranges.push_back({{"start", range.start}, {"end", range.end}});
1828
+ }
1829
+ return json{
1830
+ {"type", "chars"},
1831
+ {"pattern", p.pattern},
1832
+ {"ranges", ranges},
1833
+ {"negated", p.negated},
1834
+ {"min_count", p.min_count},
1835
+ {"max_count", p.max_count}
1836
+ };
1837
+ } else if constexpr (std::is_same_v<T, common_peg_string_parser>) {
1838
+ return json{{"type", "string"}, {"delimiter", std::string(1, p.delimiter)}};
1839
+ } else if constexpr (std::is_same_v<T, common_peg_until_parser>) {
1840
+ return json{{"type", "until"}, {"delimiters", p.delimiters}};
1841
+ } else if constexpr (std::is_same_v<T, common_peg_schema_parser>) {
1842
+ return json{
1843
+ {"type", "schema"},
1844
+ {"child", p.child},
1845
+ {"name", p.name},
1846
+ {"raw", p.raw}
1847
+ };
1848
+ } else if constexpr (std::is_same_v<T, common_peg_rule_parser>) {
1849
+ return json{
1850
+ {"type", "rule"},
1851
+ {"name", p.name},
1852
+ {"child", p.child},
1853
+ {"trigger", p.trigger}
1854
+ };
1855
+ } else if constexpr (std::is_same_v<T, common_peg_ref_parser>) {
1856
+ return json{{"type", "ref"}, {"name", p.name}};
1857
+ } else if constexpr (std::is_same_v<T, common_peg_atomic_parser>) {
1858
+ return json{{"type", "atomic"}, {"child", p.child}};
1859
+ } else if constexpr (std::is_same_v<T, common_peg_tag_parser>) {
1860
+ return json{
1861
+ {"type", "tag"},
1862
+ {"child", p.child},
1863
+ {"tag", p.tag}
1864
+ };
1865
+ } else if constexpr (std::is_same_v<T, common_peg_gbnf_parser>) {
1866
+ return json{{"type", "gbnf"}, {"child", p.child}, {"grammar", p.grammar}};
1867
+ } else if constexpr (std::is_same_v<T, common_peg_ac_parser>) {
1868
+ return json{{"type", "ac"}, {"child", p.child}, {"delimiters", p.delimiters}};
1869
+ }
1870
+ }, variant);
1871
+ }
1872
+
1873
+ common_json common_peg_arena::to_json() const {
1874
+ auto parsers = common_json::array();
1875
+ for (const auto & parser : parsers_) {
1876
+ parsers.push_back(serialize_parser_variant(parser));
1877
+ }
1878
+ return common_json{
1879
+ {"parsers", parsers},
1880
+ {"rules", rules_},
1881
+ {"root", root_}
1882
+ };
1883
+ }
1884
+
1885
+ static common_peg_parser_variant deserialize_parser_variant(const common_json & j) {
1886
+ if (!j.contains("type") || !j["type"].is_string()) {
1887
+ throw std::runtime_error("Parser variant JSON missing or invalid 'type' field");
1888
+ }
1889
+
1890
+ std::string type = j["type"];
1891
+
1892
+ if (type == "epsilon") {
1893
+ return common_peg_epsilon_parser{};
1894
+ }
1895
+ if (type == "start") {
1896
+ return common_peg_start_parser{};
1897
+ }
1898
+ if (type == "end") {
1899
+ return common_peg_end_parser{};
1900
+ }
1901
+ if (type == "literal") {
1902
+ if (!j.contains("literal") || !j["literal"].is_string()) {
1903
+ throw std::runtime_error("literal parser missing or invalid 'literal' field");
1904
+ }
1905
+ return common_peg_literal_parser{j["literal"]};
1906
+ }
1907
+ if (type == "sequence") {
1908
+ if (!j.contains("children") || !j["children"].is_array()) {
1909
+ throw std::runtime_error("sequence parser missing or invalid 'children' field");
1910
+ }
1911
+ return common_peg_sequence_parser{j["children"].get<std::vector<common_peg_parser_id>>()};
1912
+ }
1913
+ if (type == "choice") {
1914
+ if (!j.contains("children") || !j["children"].is_array()) {
1915
+ throw std::runtime_error("choice parser missing or invalid 'children' field");
1916
+ }
1917
+ return common_peg_choice_parser{j["children"].get<std::vector<common_peg_parser_id>>()};
1918
+ }
1919
+ if (type == "repetition") {
1920
+ if (!j.contains("child") || !j.contains("min_count") || !j.contains("max_count")) {
1921
+ throw std::runtime_error("repetition parser missing required fields");
1922
+ }
1923
+ return common_peg_repetition_parser{
1924
+ j["child"].get<common_peg_parser_id>(),
1925
+ j["min_count"].get<int>(),
1926
+ j["max_count"].get<int>()
1927
+ };
1928
+ }
1929
+ if (type == "and") {
1930
+ if (!j.contains("child")) {
1931
+ throw std::runtime_error("and parser missing 'child' field");
1932
+ }
1933
+ return common_peg_and_parser{j["child"].get<common_peg_parser_id>()};
1934
+ }
1935
+ if (type == "not") {
1936
+ if (!j.contains("child")) {
1937
+ throw std::runtime_error("not parser missing 'child' field");
1938
+ }
1939
+ return common_peg_not_parser{j["child"].get<common_peg_parser_id>()};
1940
+ }
1941
+ if (type == "any") {
1942
+ return common_peg_any_parser{};
1943
+ }
1944
+ if (type == "space") {
1945
+ return common_peg_space_parser{};
1946
+ }
1947
+ if (type == "chars") {
1948
+ if (!j.contains("pattern") || !j.contains("ranges") || !j.contains("negated") ||
1949
+ !j.contains("min_count") || !j.contains("max_count")) {
1950
+ throw std::runtime_error("chars parser missing required fields");
1951
+ }
1952
+ common_peg_chars_parser parser;
1953
+ parser.pattern = j["pattern"];
1954
+ parser.negated = j["negated"].get<bool>();
1955
+ parser.min_count = j["min_count"].get<int>();
1956
+ parser.max_count = j["max_count"].get<int>();
1957
+ for (const auto & range_json : j["ranges"]) {
1958
+ if (!range_json.contains("start") || !range_json.contains("end")) {
1959
+ throw std::runtime_error("char_range missing 'start' or 'end' field");
1960
+ }
1961
+ parser.ranges.push_back({
1962
+ range_json["start"].get<uint32_t>(),
1963
+ range_json["end"].get<uint32_t>()
1964
+ });
1965
+ }
1966
+ return parser;
1967
+ }
1968
+ if (type == "string") {
1969
+ if (!j.contains("delimiter")) {
1970
+ throw std::runtime_error("string parser missing delimiter field.");
1971
+ }
1972
+ std::string delimiter = j["delimiter"];
1973
+ if (delimiter.empty()) {
1974
+ throw std::runtime_error("string parser delimiter is empty.");
1975
+ }
1976
+ return common_peg_string_parser{delimiter[0]};
1977
+ }
1978
+ if (type == "until") {
1979
+ if (!j.contains("delimiters") || !j["delimiters"].is_array()) {
1980
+ throw std::runtime_error("until parser missing or invalid 'delimiters' field");
1981
+ }
1982
+ return common_peg_until_parser{j["delimiters"].get<std::vector<std::string>>()};
1983
+ }
1984
+ if (type == "schema") {
1985
+ if (!j.contains("child") || !j.contains("name") || !j.contains("raw")) {
1986
+ throw std::runtime_error("schema parser missing required fields");
1987
+ }
1988
+ common_peg_schema_parser parser;
1989
+ parser.child = j["child"].get<common_peg_parser_id>();
1990
+ parser.name = j["name"];
1991
+ parser.raw = j["raw"].get<bool>();
1992
+ return parser;
1993
+ }
1994
+ if (type == "rule") {
1995
+ if (!j.contains("name") || !j.contains("child") || !j.contains("trigger")) {
1996
+ throw std::runtime_error("rule parser missing required fields");
1997
+ }
1998
+ return common_peg_rule_parser{
1999
+ j["name"].get<std::string>(),
2000
+ j["child"].get<common_peg_parser_id>(),
2001
+ j["trigger"].get<bool>()
2002
+ };
2003
+ }
2004
+ if (type == "ref") {
2005
+ if (!j.contains("name") || !j["name"].is_string()) {
2006
+ throw std::runtime_error("ref parser missing or invalid 'name' field");
2007
+ }
2008
+ return common_peg_ref_parser{j["name"]};
2009
+ }
2010
+ if (type == "atomic") {
2011
+ if (!j.contains("child")) {
2012
+ throw std::runtime_error("tag parser missing required fields");
2013
+ }
2014
+ return common_peg_atomic_parser{
2015
+ j["child"].get<common_peg_parser_id>(),
2016
+ };
2017
+ }
2018
+ if (type == "tag") {
2019
+ if (!j.contains("child") || !j.contains("tag")) {
2020
+ throw std::runtime_error("tag parser missing required fields");
2021
+ }
2022
+ return common_peg_tag_parser{
2023
+ j["child"].get<common_peg_parser_id>(),
2024
+ j["tag"].get<std::string>(),
2025
+ };
2026
+ }
2027
+
2028
+ if (type == "gbnf") {
2029
+ if (!j.contains("child") || !j.contains("grammar")) {
2030
+ throw std::runtime_error("gbnf parser missing required fields");
2031
+ }
2032
+ return common_peg_gbnf_parser{
2033
+ j["child"].get<common_peg_parser_id>(),
2034
+ j["grammar"].get<std::string>(),
2035
+ };
2036
+ }
2037
+
2038
+ if (type == "ac") {
2039
+ if (!j.contains("child") || !j.contains("delimiters") || !j["delimiters"].is_array() || j["delimiters"].empty()) {
2040
+ throw std::runtime_error("ac parser requires 'child' and a non-empty 'delimiters' array");
2041
+ }
2042
+ return common_peg_ac_parser{
2043
+ j["child"].get<common_peg_parser_id>(),
2044
+ j["delimiters"].get<std::vector<std::string>>(),
2045
+ };
2046
+ }
2047
+
2048
+ throw std::runtime_error("Unknown parser type: " + type);
2049
+ }
2050
+
2051
+ common_peg_arena common_peg_arena::from_json(const common_json & j) {
2052
+ if (!j.contains("parsers") || !j["parsers"].is_array()) {
2053
+ throw std::runtime_error("JSON missing or invalid 'parsers' array");
2054
+ }
2055
+ if (!j.contains("rules") || !j["rules"].is_object()) {
2056
+ throw std::runtime_error("JSON missing or invalid 'rules' object");
2057
+ }
2058
+ if (!j.contains("root")) {
2059
+ throw std::runtime_error("JSON missing 'root' field");
2060
+ }
2061
+
2062
+ common_peg_arena arena;
2063
+
2064
+ const auto & parsers_json = j["parsers"];
2065
+ arena.parsers_.reserve(parsers_json.size());
2066
+ for (const auto & parser_json : parsers_json) {
2067
+ arena.parsers_.push_back(deserialize_parser_variant(parser_json));
2068
+ }
2069
+
2070
+ arena.rules_ = j["rules"].get<std::unordered_map<std::string, common_peg_parser_id>>();
2071
+
2072
+ for (const auto & [name, id] : arena.rules_) {
2073
+ if (id >= arena.parsers_.size()) {
2074
+ throw std::runtime_error("Rule '" + name + "' references invalid parser ID: " + std::to_string(id));
2075
+ }
2076
+ }
2077
+
2078
+ arena.root_ = j["root"].get<common_peg_parser_id>();
2079
+ if (arena.root_ != COMMON_PEG_INVALID_PARSER_ID && arena.root_ >= arena.parsers_.size()) {
2080
+ throw std::runtime_error("Root references invalid parser ID: " + std::to_string(arena.root_));
2081
+ }
2082
+
2083
+ return arena;
2084
+ }
2085
+
2086
+ std::string common_peg_arena::save() const {
2087
+ return to_json().dump();
2088
+ }
2089
+
2090
+ void common_peg_arena::load(const std::string & data) {
2091
+ *this = from_json(common_json::parse(data));
2092
+ }
2093
+
2094
+ common_peg_arena build_peg_parser(const std::function<common_peg_parser(common_peg_parser_builder & builder)> & fn) {
2095
+ common_peg_parser_builder builder;
2096
+ builder.set_root(fn(builder));
2097
+ return builder.build();
2098
+ }
common/peg-parser.h ADDED
@@ -0,0 +1,540 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include "json-schema.h"
4
+ #include "json.h"
5
+
6
+ #include <memory>
7
+ #include <set>
8
+ #include <unordered_map>
9
+ #include <string>
10
+ #include <string_view>
11
+ #include <functional>
12
+ #include <vector>
13
+ #include <variant>
14
+
15
+ struct common_grammar_builder;
16
+
17
+ class common_peg_parser_builder;
18
+
19
+ using common_peg_parser_id = size_t;
20
+ constexpr common_peg_parser_id COMMON_PEG_INVALID_PARSER_ID = static_cast<common_peg_parser_id>(-1);
21
+
22
+ using common_peg_ast_id = size_t;
23
+ constexpr common_peg_ast_id COMMON_PEG_INVALID_AST_ID = static_cast<common_peg_ast_id>(-1);
24
+
25
+ // Lightweight wrapper around common_peg_parser_id for convenience
26
+ class common_peg_parser {
27
+ common_peg_parser_id id_;
28
+ common_peg_parser_builder & builder_;
29
+
30
+ public:
31
+ common_peg_parser(const common_peg_parser & other) : id_(other.id_), builder_(other.builder_) {}
32
+ common_peg_parser(common_peg_parser_id id, common_peg_parser_builder & builder) : id_(id), builder_(builder) {}
33
+
34
+ common_peg_parser & operator=(const common_peg_parser & other);
35
+ common_peg_parser & operator+=(const common_peg_parser & other);
36
+ common_peg_parser & operator|=(const common_peg_parser & other);
37
+
38
+ operator common_peg_parser_id() const { return id_; }
39
+ common_peg_parser_id id() const { return id_; }
40
+
41
+ common_peg_parser_builder & builder() const { return builder_; }
42
+
43
+ // Creates a sequence
44
+ common_peg_parser operator+(const common_peg_parser & other) const;
45
+
46
+ // Creates a sequence separated by spaces.
47
+ common_peg_parser operator<<(const common_peg_parser & other) const;
48
+
49
+ // Creates a choice
50
+ common_peg_parser operator|(const common_peg_parser & other) const;
51
+
52
+ common_peg_parser operator+(const char * str) const;
53
+ common_peg_parser operator+(const std::string & str) const;
54
+ common_peg_parser operator<<(const char * str) const;
55
+ common_peg_parser operator<<(const std::string & str) const;
56
+ common_peg_parser operator|(const char * str) const;
57
+ common_peg_parser operator|(const std::string & str) const;
58
+ };
59
+
60
+ common_peg_parser operator+(const char * str, const common_peg_parser & p);
61
+ common_peg_parser operator+(const std::string & str, const common_peg_parser & p);
62
+ common_peg_parser operator<<(const char * str, const common_peg_parser & p);
63
+ common_peg_parser operator<<(const std::string & str, const common_peg_parser & p);
64
+ common_peg_parser operator|(const char * str, const common_peg_parser & p);
65
+ common_peg_parser operator|(const std::string & str, const common_peg_parser & p);
66
+
67
+ enum common_peg_parse_result_type {
68
+ COMMON_PEG_PARSE_RESULT_FAIL = 0,
69
+ COMMON_PEG_PARSE_RESULT_SUCCESS = 1,
70
+ COMMON_PEG_PARSE_RESULT_NEED_MORE_INPUT = 2,
71
+ };
72
+
73
+ const char * common_peg_parse_result_type_name(common_peg_parse_result_type type);
74
+
75
+ struct common_peg_ast_node {
76
+ common_peg_ast_id id;
77
+ std::string rule;
78
+ std::string tag;
79
+ size_t start;
80
+ size_t end;
81
+ std::string_view text;
82
+ std::vector<common_peg_ast_id> children;
83
+
84
+ bool is_partial = false;
85
+ };
86
+
87
+ struct common_peg_parse_result;
88
+
89
+ using common_peg_ast_visitor = std::function<void(const common_peg_ast_node & node)>;
90
+
91
+ class common_peg_ast_arena {
92
+ std::vector<common_peg_ast_node> nodes_;
93
+ public:
94
+ common_peg_ast_id add_node(
95
+ const std::string & rule,
96
+ const std::string & tag,
97
+ size_t start,
98
+ size_t end,
99
+ std::string_view text,
100
+ std::vector<common_peg_ast_id> children,
101
+ bool is_partial = false
102
+ ) {
103
+ common_peg_ast_id id = nodes_.size();
104
+ nodes_.push_back({id, rule, tag, start, end, text, std::move(children), is_partial});
105
+ return id;
106
+ }
107
+
108
+ const common_peg_ast_node & get(common_peg_ast_id id) const { return nodes_.at(id); }
109
+
110
+ common_peg_ast_id find_by_tag(const common_peg_ast_node & parent, const std::string & tag, int max_depth = 3) const;
111
+ common_peg_ast_id find_by_rule(const common_peg_ast_node & parent, const std::string & tag, int max_depth = 3) const;
112
+
113
+ size_t size() const { return nodes_.size(); }
114
+
115
+ void clear() { nodes_.clear(); }
116
+
117
+ void visit(common_peg_ast_id id, const common_peg_ast_visitor & visitor) const;
118
+ void visit(const common_peg_parse_result & result, const common_peg_ast_visitor & visitor) const;
119
+
120
+ std::string dump();
121
+ };
122
+
123
+ struct common_peg_parse_result {
124
+ common_peg_parse_result_type type = COMMON_PEG_PARSE_RESULT_FAIL;
125
+ size_t start = 0;
126
+ size_t end = 0;
127
+
128
+ std::vector<common_peg_ast_id> nodes;
129
+
130
+ common_peg_parse_result() = default;
131
+
132
+ common_peg_parse_result(common_peg_parse_result_type type, size_t start)
133
+ : type(type), start(start), end(start) {}
134
+
135
+ common_peg_parse_result(common_peg_parse_result_type type, size_t start, size_t end)
136
+ : type(type), start(start), end(end) {}
137
+
138
+ common_peg_parse_result(common_peg_parse_result_type type, size_t start, size_t end, std::vector<common_peg_ast_id> nodes)
139
+ : type(type), start(start), end(end), nodes(std::move(nodes)) {}
140
+
141
+ bool fail() const { return type == COMMON_PEG_PARSE_RESULT_FAIL; }
142
+ bool need_more_input() const { return type == COMMON_PEG_PARSE_RESULT_NEED_MORE_INPUT; }
143
+ bool success() const { return type == COMMON_PEG_PARSE_RESULT_SUCCESS; }
144
+ };
145
+
146
+ enum common_peg_parse_flags {
147
+ COMMON_PEG_PARSE_FLAG_NONE = 0,
148
+ COMMON_PEG_PARSE_FLAG_LENIENT = 1 << 0,
149
+ COMMON_PEG_PARSE_FLAG_DEBUG = 1 << 1,
150
+ };
151
+
152
+ inline common_peg_parse_flags operator|(common_peg_parse_flags a, common_peg_parse_flags b) {
153
+ return static_cast<common_peg_parse_flags>(int(a) | int(b));
154
+ }
155
+
156
+ inline common_peg_parse_flags & operator|=(common_peg_parse_flags & a, common_peg_parse_flags b) {
157
+ return a = a | b;
158
+ }
159
+
160
+ inline common_peg_parse_flags operator&(common_peg_parse_flags a, common_peg_parse_flags b) {
161
+ return static_cast<common_peg_parse_flags>(int(a) & int(b));
162
+ }
163
+
164
+ inline common_peg_parse_flags operator~(common_peg_parse_flags a) {
165
+ return static_cast<common_peg_parse_flags>(~int(a));
166
+ }
167
+
168
+ struct common_peg_parse_context {
169
+ std::string input;
170
+ common_peg_parse_flags flags;
171
+ common_peg_ast_arena ast;
172
+
173
+ int parse_depth;
174
+
175
+ common_peg_parse_context(common_peg_parse_flags flags = COMMON_PEG_PARSE_FLAG_NONE)
176
+ : flags(flags), parse_depth(0) {}
177
+
178
+ common_peg_parse_context(const std::string & input, common_peg_parse_flags flags = COMMON_PEG_PARSE_FLAG_NONE)
179
+ : input(input), flags(flags), parse_depth(0) {}
180
+
181
+ bool is_lenient() const { return flags & COMMON_PEG_PARSE_FLAG_LENIENT; }
182
+ bool is_debug() const { return flags & COMMON_PEG_PARSE_FLAG_DEBUG; }
183
+ };
184
+
185
+ class common_peg_arena;
186
+
187
+ // Parser variants
188
+ struct common_peg_epsilon_parser {};
189
+
190
+ struct common_peg_start_parser {};
191
+
192
+ struct common_peg_end_parser {};
193
+
194
+ struct common_peg_literal_parser {
195
+ std::string literal;
196
+ };
197
+
198
+ struct common_peg_sequence_parser {
199
+ std::vector<common_peg_parser_id> children;
200
+ };
201
+
202
+ struct common_peg_choice_parser {
203
+ std::vector<common_peg_parser_id> children;
204
+ };
205
+
206
+ struct common_peg_repetition_parser {
207
+ common_peg_parser_id child;
208
+ int min_count;
209
+ int max_count; // -1 for unbounded
210
+ };
211
+
212
+ struct common_peg_and_parser {
213
+ common_peg_parser_id child;
214
+ };
215
+
216
+ struct common_peg_not_parser {
217
+ common_peg_parser_id child;
218
+ };
219
+
220
+ struct common_peg_any_parser {};
221
+
222
+ struct common_peg_space_parser {};
223
+
224
+ struct common_peg_chars_parser {
225
+ struct char_range {
226
+ uint32_t start;
227
+ uint32_t end;
228
+ bool contains(uint32_t codepoint) const { return codepoint >= start && codepoint <= end; }
229
+ };
230
+
231
+ std::string pattern;
232
+ std::vector<char_range> ranges;
233
+ bool negated;
234
+ int min_count;
235
+ int max_count; // -1 for unbounded
236
+ };
237
+
238
+ struct common_peg_string_parser {
239
+ char delimiter;
240
+ };
241
+
242
+ struct common_peg_until_parser {
243
+ std::vector<std::string> delimiters;
244
+ };
245
+
246
+ struct common_peg_schema_parser {
247
+ common_peg_parser_id child;
248
+ std::string name;
249
+ common_chat_schema_document_ptr doc; // owns node
250
+ const common_chat_schema * node = nullptr;
251
+
252
+ // Indicates if the GBNF should accept a raw string that matches the schema.
253
+ bool raw;
254
+ };
255
+
256
+ struct common_peg_rule_parser {
257
+ std::string name;
258
+ common_peg_parser_id child;
259
+ bool trigger;
260
+ };
261
+
262
+ struct common_peg_ref_parser {
263
+ std::string name;
264
+ };
265
+
266
+ struct common_peg_atomic_parser {
267
+ common_peg_parser_id child;
268
+ };
269
+
270
+ struct common_peg_tag_parser {
271
+ common_peg_parser_id child;
272
+ std::string tag;
273
+ };
274
+
275
+ struct common_peg_gbnf_parser {
276
+ common_peg_parser_id child;
277
+ std::string grammar;
278
+ };
279
+
280
+ struct common_peg_ac_parser {
281
+ common_peg_parser_id child;
282
+ std::vector<std::string> delimiters;
283
+ };
284
+
285
+ // Variant holding all parser types
286
+ using common_peg_parser_variant = std::variant<
287
+ common_peg_epsilon_parser,
288
+ common_peg_start_parser,
289
+ common_peg_end_parser,
290
+ common_peg_literal_parser,
291
+ common_peg_sequence_parser,
292
+ common_peg_choice_parser,
293
+ common_peg_repetition_parser,
294
+ common_peg_and_parser,
295
+ common_peg_not_parser,
296
+ common_peg_any_parser,
297
+ common_peg_space_parser,
298
+ common_peg_chars_parser,
299
+ common_peg_string_parser,
300
+ common_peg_until_parser,
301
+ common_peg_schema_parser,
302
+ common_peg_rule_parser,
303
+ common_peg_ref_parser,
304
+ common_peg_atomic_parser,
305
+ common_peg_tag_parser,
306
+ common_peg_gbnf_parser,
307
+ common_peg_ac_parser
308
+ >;
309
+
310
+ class common_peg_arena {
311
+ std::vector<common_peg_parser_variant> parsers_;
312
+ std::unordered_map<std::string, common_peg_parser_id> rules_;
313
+ common_peg_parser_id root_ = COMMON_PEG_INVALID_PARSER_ID;
314
+
315
+ public:
316
+ const common_peg_parser_variant & get(common_peg_parser_id id) const { return parsers_.at(id); }
317
+ common_peg_parser_variant & get(common_peg_parser_id id) { return parsers_.at(id); }
318
+
319
+ size_t size() const { return parsers_.size(); }
320
+ bool empty() const { return parsers_.empty(); }
321
+
322
+ common_peg_parser_id get_rule(const std::string & name) const;
323
+ bool has_rule(const std::string & name) const { return rules_.find(name) != rules_.end(); }
324
+
325
+ common_peg_parser_id root() const { return root_; }
326
+ void set_root(common_peg_parser_id id) { root_ = id; }
327
+
328
+ common_peg_parse_result parse(common_peg_parse_context & ctx, size_t start = 0) const;
329
+ common_peg_parse_result parse(common_peg_parser_id id, common_peg_parse_context & ctx, size_t start) const;
330
+
331
+ void resolve_refs();
332
+
333
+ void build_grammar(const common_grammar_builder & builder, bool lazy = false) const;
334
+
335
+ std::string dump(common_peg_parser_id id) const;
336
+
337
+ common_json to_json() const;
338
+ static common_peg_arena from_json(const common_json & j);
339
+
340
+ std::string save() const;
341
+ void load(const std::string & data);
342
+
343
+ friend class common_peg_parser_builder;
344
+
345
+ private:
346
+ std::string dump_impl(common_peg_parser_id id, std::set<common_peg_parser_id> & visited) const;
347
+
348
+ common_peg_parser_id add_parser(common_peg_parser_variant parser);
349
+ void add_rule(const std::string & name, common_peg_parser_id id);
350
+
351
+ common_peg_parser_id resolve_ref(common_peg_parser_id id);
352
+ };
353
+
354
+ class common_peg_parser_builder {
355
+ common_peg_arena arena_;
356
+
357
+ common_peg_parser wrap(common_peg_parser_id id) { return common_peg_parser(id, *this); }
358
+ common_peg_parser add(const common_peg_parser_variant & p) { return wrap(arena_.add_parser(p)); }
359
+
360
+ public:
361
+ common_peg_parser_builder();
362
+
363
+ // Match nothing, always succeed.
364
+ // S -> ε
365
+ common_peg_parser eps() { return add(common_peg_epsilon_parser{}); }
366
+
367
+ // Matches the start of the input.
368
+ // S -> ^
369
+ common_peg_parser start() { return add(common_peg_start_parser{}); }
370
+
371
+ // Matches the end of the input.
372
+ // S -> $
373
+ common_peg_parser end() { return add(common_peg_end_parser{}); }
374
+
375
+ // Matches an exact literal string.
376
+ // S -> "hello"
377
+ common_peg_parser literal(const std::string & literal) { return add(common_peg_literal_parser{literal}); }
378
+
379
+ // Matches a sequence of parsers in order, all must succeed.
380
+ // S -> A B C
381
+ common_peg_parser sequence() { return add(common_peg_sequence_parser{}); }
382
+ common_peg_parser sequence(const std::vector<common_peg_parser_id> & parsers);
383
+ common_peg_parser sequence(const std::vector<common_peg_parser> & parsers);
384
+ common_peg_parser sequence(std::initializer_list<common_peg_parser> parsers);
385
+
386
+ // Matches the first parser that succeeds from a list of alternatives.
387
+ // S -> A | B | C
388
+ common_peg_parser choice() { return add(common_peg_choice_parser{}); }
389
+ common_peg_parser choice(const std::vector<common_peg_parser_id> & parsers);
390
+ common_peg_parser choice(const std::vector<common_peg_parser> & parsers);
391
+ common_peg_parser choice(std::initializer_list<common_peg_parser> parsers);
392
+
393
+ // Matches one or more repetitions of a parser.
394
+ // S -> A+
395
+ common_peg_parser one_or_more(const common_peg_parser & p) { return repeat(p, 1, -1); }
396
+
397
+ // Matches zero or more repetitions of a parser, always succeeds.
398
+ // S -> A*
399
+ common_peg_parser zero_or_more(const common_peg_parser & p) { return repeat(p, 0, -1); }
400
+
401
+ // Matches zero or one occurrence of a parser, always succeeds.
402
+ // S -> A?
403
+ common_peg_parser optional(const common_peg_parser & p) { return repeat(p, 0, 1); }
404
+
405
+ // Positive lookahead: succeeds if child parser succeeds, consumes no input.
406
+ // S -> &A
407
+ common_peg_parser peek(const common_peg_parser & p) { return add(common_peg_and_parser{p}); }
408
+
409
+ // Negative lookahead: succeeds if child parser fails, consumes no input.
410
+ // S -> !A
411
+ common_peg_parser negate(const common_peg_parser & p) { return add(common_peg_not_parser{p}); }
412
+
413
+ // Matches any single character.
414
+ // S -> .
415
+ common_peg_parser any() { return add(common_peg_any_parser{}); }
416
+
417
+ // Matches between min and max repetitions of characters from a character class.
418
+ // S -> [a-z]{m,n}
419
+ //
420
+ // Use -1 for max to represent unbounded repetition (equivalent to {m,})
421
+ common_peg_parser chars(const std::string & classes, int min = 1, int max = -1);
422
+
423
+ // Creates a lightweight reference to a named rule (resolved during build()).
424
+ // Use this for forward references in recursive grammars.
425
+ // expr_ref -> expr
426
+ common_peg_parser ref(const std::string & name) { return add(common_peg_ref_parser{name}); }
427
+
428
+ // Matches zero or more whitespace characters (space, tab, newline).
429
+ // S -> [ \t\n]*
430
+ common_peg_parser space() { return add(common_peg_space_parser{}); }
431
+
432
+ // Matches all characters until a delimiter is found (delimiter not consumed).
433
+ // S -> (!delim .)*
434
+ common_peg_parser until(const std::string & delimiter) { return add(common_peg_until_parser{{delimiter}}); }
435
+
436
+ // Matches all characters until one of the delimiters in the list is found (delimiter not consumed).
437
+ // S -> (!delim .)*
438
+ common_peg_parser until_one_of(const std::vector<std::string> & delimiters) { return add(common_peg_until_parser{delimiters}); }
439
+
440
+ // Matches everything
441
+ // S -> .*
442
+ common_peg_parser rest() { return until_one_of({}); }
443
+
444
+ // Matches between min and max repetitions of a parser (inclusive).
445
+ // S -> A{m,n}
446
+ // Use -1 for max to represent unbounded repetition (equivalent to {m,})
447
+ common_peg_parser repeat(const common_peg_parser & p, int min, int max) { return add(common_peg_repetition_parser{p, min,max}); }
448
+
449
+ // Matches exactly n repetitions of a parser.
450
+ // S -> A{n}
451
+ common_peg_parser repeat(const common_peg_parser & p, int n) { return repeat(p, n, n); }
452
+
453
+ // Matches a double-quoted string: '"' content '"' space
454
+ common_peg_parser double_quoted_string();
455
+
456
+ // Matches a single-quoted string: "'" content "'" space
457
+ common_peg_parser single_quoted_string();
458
+
459
+ // Matches a string that accepts both double-quoted and single-quoted styles.
460
+ common_peg_parser quoted_string();
461
+
462
+ // Matches string content without the surrounding delimiter.
463
+ common_peg_parser string_content(char delimiter);
464
+
465
+ // Creates a complete JSON parser supporting objects, arrays, strings, numbers, booleans, and null.
466
+ // value -> object | array | string | number | true | false | null
467
+ common_peg_parser json();
468
+ common_peg_parser json_object();
469
+ common_peg_parser json_string();
470
+ common_peg_parser json_array();
471
+ common_peg_parser json_number();
472
+ common_peg_parser json_bool();
473
+ common_peg_parser json_null();
474
+
475
+ // Matches a JSON object member with a key and associated parser as the
476
+ // value.
477
+ common_peg_parser json_member(const std::string & key, const common_peg_parser & p);
478
+
479
+ // Creates a complete Python format parser supporting dicts, arrays, strings, numbers, booleans, and None.
480
+ // Differs from JSON: uses True/False/None, accepts both single and double-quoted strings.
481
+ // value -> dict | array | string | number | True | False | None
482
+ common_peg_parser python_value();
483
+ common_peg_parser python_dict();
484
+ common_peg_parser python_string();
485
+ common_peg_parser python_array();
486
+ common_peg_parser python_number();
487
+ common_peg_parser python_bool();
488
+ common_peg_parser python_null();
489
+
490
+ // A marker, i.e. text delimited by a pair of <> or []
491
+ common_peg_parser marker();
492
+
493
+ // Wraps a parser with the schema its GBNF is generated from, a node of the document that owns it
494
+ common_peg_parser schema(const common_peg_parser & p, const std::string & name, common_chat_schema_document_ptr doc, const common_chat_schema & node, bool raw = false);
495
+
496
+ // Parses the JSON schema into a document of its own
497
+ common_peg_parser schema(const common_peg_parser & p, const std::string & name, const common_json & schema, bool raw = false);
498
+
499
+ // Creates a named rule, stores it in the grammar, and returns a ref.
500
+ // If trigger=true, marks this rule as an entry point for lazy grammar generation.
501
+ // auto json = p.rule("json", json_obj | json_arr | ...)
502
+ common_peg_parser rule(const std::string & name, const common_peg_parser & p, bool trigger = false);
503
+
504
+ // Creates a named rule using a builder function, and returns a ref.
505
+ // If trigger=true, marks this rule as an entry point for lazy grammar generation.
506
+ // auto json = p.rule("json", [&]() { return json_object() | json_array() | ... })
507
+ common_peg_parser rule(const std::string & name, const std::function<common_peg_parser()> & builder, bool trigger = false);
508
+
509
+ // Creates a trigger rule. When generating a lazy grammar from the parser,
510
+ // only trigger rules and descendents are emitted.
511
+ common_peg_parser trigger_rule(const std::string & name, const common_peg_parser & p) { return rule(name, p, true); }
512
+ common_peg_parser trigger_rule(const std::string & name, const std::function<common_peg_parser()> & builder) { return rule(name, builder, true); }
513
+
514
+ // Creates an atomic parser. Atomic parsers do not create an AST node if
515
+ // the child results in a partial parse, i.e. NEEDS_MORE_INPUT. This is
516
+ // intended for situations where partial output is undesirable.
517
+ common_peg_parser atomic(const common_peg_parser & p) { return add(common_peg_atomic_parser{p}); }
518
+
519
+ // Tags create nodes in the generated AST for semantic purposes.
520
+ // Unlike rules, you can tag multiple nodes with the same tag.
521
+ common_peg_parser tag(const std::string & tag, const common_peg_parser & p) { return add(common_peg_tag_parser{p.id(), tag}); }
522
+
523
+ // Wraps a child parser but emits a custom GBNF grammar string instead of
524
+ // the child's grammar. Parsing delegates entirely to the child.
525
+ common_peg_parser gbnf(const common_peg_parser & p, const std::string & grammar) { return add(common_peg_gbnf_parser{p, grammar}); }
526
+
527
+ // Wraps a child parser but emits a GBNF grammar built from the Aho-Corasick
528
+ // automaton of `delimiters`, matching everything up to and including the
529
+ // first delimiter. Parsing delegates entirely to the child, which is
530
+ // responsible for consuming the delimiter (e.g. until(D) + literal(D)).
531
+ common_peg_parser ac(const common_peg_parser & p, const std::vector<std::string> & delimiters);
532
+ common_peg_parser ac(const common_peg_parser & p, const std::string & delimiter) { return ac(p, std::vector<std::string>{delimiter}); }
533
+
534
+ void set_root(const common_peg_parser & p);
535
+
536
+ common_peg_arena build();
537
+ };
538
+
539
+ // Helper function for building parsers
540
+ common_peg_arena build_peg_parser(const std::function<common_peg_parser(common_peg_parser_builder & builder)> & fn);
common/preset.cpp ADDED
@@ -0,0 +1,501 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "arg.h"
2
+ #include "preset.h"
3
+ #include "peg-parser.h"
4
+ #include "log.h"
5
+ #include "download.h"
6
+
7
+ #include <fstream>
8
+ #include <sstream>
9
+ #include <filesystem>
10
+ #include <regex>
11
+
12
+ static std::string rm_leading_dashes(const std::string & str) {
13
+ size_t pos = 0;
14
+ while (pos < str.size() && str[pos] == '-') {
15
+ ++pos;
16
+ }
17
+ return str.substr(pos);
18
+ }
19
+
20
+ static std::string canonical_tag(const std::string & tag) {
21
+ static const std::regex re_tag("[-.]([A-Z0-9_]+)$", std::regex::icase);
22
+ std::smatch m;
23
+ if (std::regex_search(tag, m, re_tag)) {
24
+ std::string canon = m[1].str();
25
+ for (char & c : canon) {
26
+ c = (char) std::toupper((unsigned char) c);
27
+ }
28
+ return canon;
29
+ }
30
+ std::string upper = tag;
31
+ for (char & c : upper) {
32
+ c = (char) std::toupper((unsigned char) c);
33
+ }
34
+ return upper;
35
+ }
36
+
37
+ std::vector<std::string> common_preset::to_args(const std::string & bin_path) const {
38
+ std::vector<std::string> args;
39
+
40
+ if (!bin_path.empty()) {
41
+ args.push_back(bin_path);
42
+ }
43
+
44
+ for (const auto & [opt, value] : options) {
45
+ if (opt.is_preset_only) {
46
+ continue; // skip preset-only options (they are not CLI args)
47
+ }
48
+
49
+ // use the last arg as the main arg (i.e. --long-form)
50
+ args.push_back(opt.args.back());
51
+
52
+ // handle value(s)
53
+ if (opt.value_hint == nullptr && opt.value_hint_2 == nullptr) {
54
+ // flag option, no value
55
+ if (common_arg_utils::is_falsey(value)) {
56
+ // use negative arg if available
57
+ if (!opt.args_neg.empty()) {
58
+ args.back() = opt.args_neg.back();
59
+ } else {
60
+ // otherwise, skip the flag
61
+ // TODO: maybe throw an error instead?
62
+ args.pop_back();
63
+ }
64
+ }
65
+ }
66
+ if (opt.value_hint != nullptr) {
67
+ // single value
68
+ args.push_back(value);
69
+ }
70
+ if (opt.value_hint != nullptr && opt.value_hint_2 != nullptr) {
71
+ throw std::runtime_error(string_format(
72
+ "common_preset::to_args(): option '%s' has two values, which is not supported yet",
73
+ opt.args.back()
74
+ ));
75
+ }
76
+ }
77
+
78
+ return args;
79
+ }
80
+
81
+ std::string common_preset::to_ini() const {
82
+ std::ostringstream ss;
83
+
84
+ ss << "[" << name << "]\n";
85
+ for (const auto & [opt, value] : options) {
86
+ auto espaced_value = value;
87
+ string_replace_all(espaced_value, "\n", "\\\n");
88
+ ss << rm_leading_dashes(opt.args.back()) << " = ";
89
+ ss << espaced_value << "\n";
90
+ }
91
+ ss << "\n";
92
+
93
+ return ss.str();
94
+ }
95
+
96
+ void common_preset::set_option(const common_preset_context & ctx, const std::string & env, const std::string & value) {
97
+ // try if option exists, update it
98
+ for (auto & [opt, val] : options) {
99
+ if (opt.env && env == opt.env) {
100
+ val = value;
101
+ return;
102
+ }
103
+ }
104
+ // if option does not exist, we need to add it
105
+ if (ctx.key_to_opt.find(env) == ctx.key_to_opt.end()) {
106
+ throw std::runtime_error(string_format(
107
+ "%s: option with env '%s' not found in ctx_params",
108
+ __func__, env.c_str()
109
+ ));
110
+ }
111
+ options[ctx.key_to_opt.at(env)] = value;
112
+ }
113
+
114
+ void common_preset::unset_option(const std::string & env) {
115
+ for (auto it = options.begin(); it != options.end(); ) {
116
+ const common_arg & opt = it->first;
117
+ if (opt.env && env == opt.env) {
118
+ it = options.erase(it);
119
+ return;
120
+ } else {
121
+ ++it;
122
+ }
123
+ }
124
+ }
125
+
126
+ bool common_preset::get_option(const std::string & env, std::string & value) const {
127
+ for (const auto & [opt, val] : options) {
128
+ if (opt.env && env == opt.env) {
129
+ value = val;
130
+ return true;
131
+ }
132
+ }
133
+ return false;
134
+ }
135
+
136
+ void common_preset::merge(const common_preset & other) {
137
+ for (const auto & [opt, val] : other.options) {
138
+ options[opt] = val; // overwrite existing options
139
+ }
140
+ }
141
+
142
+ void common_preset::apply_to_params(common_params & params, const std::set<std::string> & handled_keys) const {
143
+ for (const auto & [opt, val] : options) {
144
+ if (!handled_keys.empty()) {
145
+ if (!opt.env || handled_keys.find(opt.env) == handled_keys.end()) {
146
+ continue;
147
+ }
148
+ }
149
+ // apply each option to params
150
+ if (opt.handler_string) {
151
+ opt.handler_string(params, val);
152
+ } else if (opt.handler_int) {
153
+ opt.handler_int(params, std::stoi(val));
154
+ } else if (opt.handler_bool) {
155
+ opt.handler_bool(params, common_arg_utils::is_truthy(val));
156
+ } else if (opt.handler_str_str) {
157
+ // not supported yet
158
+ throw std::runtime_error(string_format(
159
+ "%s: option with two values is not supported yet",
160
+ __func__
161
+ ));
162
+ } else if (opt.handler_void) {
163
+ opt.handler_void(params);
164
+ } else {
165
+ GGML_ABORT("unknown handler type");
166
+ }
167
+ }
168
+ }
169
+
170
+ static std::map<std::string, std::map<std::string, std::string>> parse_ini_from_file(const std::string & path) {
171
+ std::map<std::string, std::map<std::string, std::string>> parsed;
172
+
173
+ if (!std::filesystem::exists(path)) {
174
+ throw std::runtime_error("preset file does not exist: " + path);
175
+ }
176
+
177
+ std::ifstream file(path);
178
+ if (!file.good()) {
179
+ throw std::runtime_error("failed to open server preset file: " + path);
180
+ }
181
+
182
+ std::string contents((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
183
+
184
+ static const auto parser = build_peg_parser([](auto & p) {
185
+ // newline ::= "\r\n" / "\n" / "\r"
186
+ auto newline = p.rule("newline", p.literal("\r\n") | p.literal("\n") | p.literal("\r"));
187
+
188
+ // ws ::= [ \t]*
189
+ auto ws = p.rule("ws", p.chars("[ \t]", 0, -1));
190
+
191
+ // comment ::= [;#] (!newline .)*
192
+ auto comment = p.rule("comment", p.chars("[;#]", 1, 1) + p.zero_or_more(p.negate(newline) + p.any()));
193
+
194
+ // eol ::= ws comment? (newline / EOF)
195
+ auto eol = p.rule("eol", ws + p.optional(comment) + (newline | p.end()));
196
+
197
+ // ident ::= [a-zA-Z_] [a-zA-Z0-9_.-]*
198
+ auto ident = p.rule("ident", p.chars("[a-zA-Z_]", 1, 1) + p.chars("[a-zA-Z0-9_.-]", 0, -1));
199
+
200
+ // value ::= (!eol-start .)*
201
+ auto eol_start = p.rule("eol-start", ws + (p.chars("[;#]", 1, 1) | newline | p.end()));
202
+ auto value = p.rule("value", p.zero_or_more(p.negate(eol_start) + p.any()));
203
+
204
+ // header-line ::= "[" ws ident ws "]" eol
205
+ auto header_line = p.rule("header-line", "[" + ws + p.tag("section-name", p.chars("[^]]")) + ws + "]" + eol);
206
+
207
+ // kv-line ::= ident ws "=" ws value eol
208
+ auto kv_line = p.rule("kv-line", p.tag("key", ident) + ws + "=" + ws + p.tag("value", value) + eol);
209
+
210
+ // comment-line ::= ws comment (newline / EOF)
211
+ auto comment_line = p.rule("comment-line", ws + comment + (newline | p.end()));
212
+
213
+ // blank-line ::= ws (newline / EOF)
214
+ auto blank_line = p.rule("blank-line", ws + (newline | p.end()));
215
+
216
+ // line ::= header-line / kv-line / comment-line / blank-line
217
+ auto line = p.rule("line", header_line | kv_line | comment_line | blank_line);
218
+
219
+ // ini ::= line* EOF
220
+ auto ini = p.rule("ini", p.zero_or_more(line) + p.end());
221
+
222
+ return ini;
223
+ });
224
+
225
+ common_peg_parse_context ctx(contents);
226
+ const auto result = parser.parse(ctx);
227
+ if (!result.success()) {
228
+ throw std::runtime_error("failed to parse server config file: " + path);
229
+ }
230
+
231
+ std::string current_section = COMMON_PRESET_DEFAULT_NAME;
232
+ std::string current_key;
233
+
234
+ ctx.ast.visit(result, [&](const auto & node) {
235
+ if (node.tag == "section-name") {
236
+ const std::string section = std::string(node.text);
237
+ current_section = section;
238
+ parsed[current_section] = {};
239
+ } else if (node.tag == "key") {
240
+ const std::string key = std::string(node.text);
241
+ current_key = key;
242
+ } else if (node.tag == "value" && !current_key.empty() && !current_section.empty()) {
243
+ parsed[current_section][current_key] = std::string(node.text);
244
+ current_key.clear();
245
+ }
246
+ });
247
+
248
+ return parsed;
249
+ }
250
+
251
+ static std::map<std::string, common_arg> get_map_key_opt(common_params_context & ctx_params) {
252
+ std::map<std::string, common_arg> mapping;
253
+ for (const auto & opt : ctx_params.options) {
254
+ for (const auto & env : opt.get_env()) {
255
+ mapping[env] = opt;
256
+ }
257
+ for (const auto & arg : opt.get_args()) {
258
+ mapping[rm_leading_dashes(arg)] = opt;
259
+ }
260
+ }
261
+ return mapping;
262
+ }
263
+
264
+ static bool is_bool_arg(const common_arg & arg) {
265
+ return !arg.args_neg.empty();
266
+ }
267
+
268
+ static std::string parse_bool_arg(const common_arg & arg, const std::string & key, const std::string & value) {
269
+ // if this is a negated arg, we need to reverse the value
270
+ for (const auto & neg_arg : arg.args_neg) {
271
+ if (rm_leading_dashes(neg_arg) == key) {
272
+ return common_arg_utils::is_truthy(value) ? "false" : "true";
273
+ }
274
+ }
275
+ // otherwise, not negated
276
+ return value;
277
+ }
278
+
279
+ common_preset_context::common_preset_context(llama_example ex)
280
+ : ctx_params(common_params_parser_init(default_params, ex)) {
281
+ common_params_add_preset_options(ctx_params.options);
282
+ key_to_opt = get_map_key_opt(ctx_params);
283
+ }
284
+
285
+ common_presets common_preset_context::load_from_ini(const std::string & path, common_preset & global) const {
286
+ common_presets out;
287
+ auto ini_data = parse_ini_from_file(path);
288
+
289
+ for (auto section : ini_data) {
290
+ common_preset preset;
291
+ std::string section_name = section.first.empty() ? std::string(COMMON_PRESET_DEFAULT_NAME) : section.first;
292
+ if (section_name != "*" && section_name != COMMON_PRESET_DEFAULT_NAME) {
293
+ auto colon_idx = section_name.rfind(':');
294
+ if (colon_idx != std::string::npos) {
295
+ std::string tag = section_name.substr(colon_idx + 1);
296
+ std::string canon_tag = canonical_tag(tag);
297
+ if (canon_tag != tag) {
298
+ section_name = section_name.substr(0, colon_idx + 1) + canon_tag;
299
+ }
300
+ }
301
+ }
302
+ preset.name = section_name;
303
+ LOG_DBG("loading preset: %s\n", preset.name.c_str());
304
+ for (const auto & [key, value] : section.second) {
305
+ if (key == "version") {
306
+ // skip version key (reserved for future use)
307
+ continue;
308
+ }
309
+
310
+ LOG_DBG("option: %s = %s\n", key.c_str(), value.c_str());
311
+ if (filter_allowed_keys && allowed_keys.find(key) == allowed_keys.end()) {
312
+ throw std::runtime_error(string_format(
313
+ "option '%s' is not allowed in remote presets",
314
+ key.c_str()
315
+ ));
316
+ }
317
+ if (key_to_opt.find(key) != key_to_opt.end()) {
318
+ const auto & opt = key_to_opt.at(key);
319
+ if (is_bool_arg(opt)) {
320
+ preset.options[opt] = parse_bool_arg(opt, key, value);
321
+ } else {
322
+ preset.options[opt] = value;
323
+ }
324
+ LOG_DBG("accepted option: %s = %s\n", key.c_str(), preset.options[opt].c_str());
325
+ } else if (ignore_unknown_keys) {
326
+ LOG_WRN("ignoring option '%s' from %s: not supported by this program\n", key.c_str(), path.c_str());
327
+ } else {
328
+ throw std::runtime_error(string_format(
329
+ "option '%s' not recognized in preset '%s'",
330
+ key.c_str(), preset.name.c_str()
331
+ ));
332
+ }
333
+ }
334
+
335
+ if (preset.name == COMMON_PRESET_DEFAULT_NAME && preset.options.empty()) {
336
+ continue;
337
+ }
338
+
339
+ if (preset.name == "*") {
340
+ // handle global preset
341
+ global = preset;
342
+ } else {
343
+ out[preset.name] = preset;
344
+ }
345
+ }
346
+
347
+ return out;
348
+ }
349
+
350
+ common_presets common_preset_context::load_from_cache() const {
351
+ common_presets out;
352
+
353
+ auto cached_models = common_list_cached_models();
354
+ for (const auto & model : cached_models) {
355
+ common_preset preset;
356
+ preset.name = model.to_string();
357
+ preset.set_option(*this, "LLAMA_ARG_HF_REPO", model.to_string());
358
+ out[preset.name] = preset;
359
+ }
360
+
361
+ return out;
362
+ }
363
+
364
+ struct local_model {
365
+ std::string name;
366
+ std::string path;
367
+ std::string path_mmproj;
368
+ std::string path_draft;
369
+ };
370
+
371
+ // TODO @ngxson: handle "eagle3-" when it's supported by common_speculative_types_from_gguf()
372
+ static const char * draft_prefixes[] = { "mtp-", "dspark-", "dflash-" };
373
+
374
+ static bool is_mmproj_file(const std::string & fname) {
375
+ return fname.find("mmproj") != std::string::npos;
376
+ }
377
+
378
+ static bool is_draft_file(const std::string & fname) {
379
+ for (const auto & prefix : draft_prefixes) {
380
+ if (fname.rfind(prefix, 0) == 0) {
381
+ return true;
382
+ }
383
+ }
384
+ return false;
385
+ }
386
+
387
+ common_presets common_preset_context::load_from_models_dir(const std::string & models_dir) const {
388
+ if (!std::filesystem::exists(models_dir) || !std::filesystem::is_directory(models_dir)) {
389
+ throw std::runtime_error(string_format("error: '%s' does not exist or is not a directory\n", models_dir.c_str()));
390
+ }
391
+
392
+ std::vector<local_model> models;
393
+ auto scan_subdir = [&models](const std::string & subdir_path, const std::string & name) {
394
+ auto files = fs_list(subdir_path, false);
395
+ common_file_info model_file;
396
+ common_file_info first_shard_file;
397
+ common_file_info mmproj_file;
398
+ common_file_info draft_file;
399
+ for (const auto & file : files) {
400
+ if (string_ends_with(file.name, ".gguf")) {
401
+ if (is_mmproj_file(file.name)) {
402
+ mmproj_file = file;
403
+ } else if (is_draft_file(file.name)) {
404
+ if (draft_file.path.empty()) {
405
+ draft_file = file; // first sidecar found wins
406
+ }
407
+ } else if (file.name.find("-00001-of-") != std::string::npos) {
408
+ first_shard_file = file;
409
+ } else {
410
+ model_file = file;
411
+ }
412
+ }
413
+ }
414
+ // single file model
415
+ local_model model{
416
+ /* name */ name,
417
+ /* path */ first_shard_file.path.empty() ? model_file.path : first_shard_file.path,
418
+ /* path_mmproj */ mmproj_file.path, // can be empty
419
+ /* path_draft */ draft_file.path // can be empty
420
+ };
421
+ if (!model.path.empty()) {
422
+ models.push_back(model);
423
+ }
424
+ };
425
+
426
+ auto files = fs_list(models_dir, true);
427
+ for (const auto & file : files) {
428
+ if (file.is_dir) {
429
+ scan_subdir(file.path, file.name);
430
+ } else if (string_ends_with(file.name, ".gguf")) {
431
+ if (is_mmproj_file(file.name) || is_draft_file(file.name)) {
432
+ continue; // companion file, cannot be loaded as a model on its own
433
+ }
434
+ // single file model
435
+ std::string name = file.name;
436
+ string_replace_all(name, ".gguf", "");
437
+ local_model model{
438
+ /* name */ name,
439
+ /* path */ file.path,
440
+ /* path_mmproj */ "",
441
+ /* path_draft */ ""
442
+ };
443
+ models.push_back(model);
444
+ }
445
+ }
446
+
447
+ // convert local models to presets
448
+ common_presets out;
449
+ for (const auto & model : models) {
450
+ common_preset preset;
451
+ preset.name = model.name;
452
+ preset.set_option(*this, "LLAMA_ARG_MODEL", model.path);
453
+ if (!model.path_mmproj.empty()) {
454
+ preset.set_option(*this, "LLAMA_ARG_MMPROJ", model.path_mmproj);
455
+ }
456
+ if (!model.path_draft.empty()) {
457
+ preset.set_option(*this, "LLAMA_ARG_SPEC_DRAFT_MODEL", model.path_draft);
458
+ }
459
+ out[preset.name] = preset;
460
+ }
461
+
462
+ return out;
463
+ }
464
+
465
+ common_preset common_preset_context::load_from_args(int argc, char ** argv) const {
466
+ common_preset preset;
467
+ preset.name = COMMON_PRESET_DEFAULT_NAME;
468
+
469
+ bool ok = common_params_to_map(argc, argv, ctx_params.ex, preset.options);
470
+ if (!ok) {
471
+ throw std::runtime_error("failed to parse CLI arguments into preset");
472
+ }
473
+
474
+ return preset;
475
+ }
476
+
477
+ common_presets common_preset_context::cascade(const common_presets & base, const common_presets & added) const {
478
+ common_presets out = base; // copy
479
+ for (const auto & [name, preset_added] : added) {
480
+ if (out.find(name) != out.end()) {
481
+ // if exists, merge
482
+ common_preset & target = out[name];
483
+ target.merge(preset_added);
484
+ } else {
485
+ // otherwise, add directly
486
+ out[name] = preset_added;
487
+ }
488
+ }
489
+ return out;
490
+ }
491
+
492
+ common_presets common_preset_context::cascade(const common_preset & base, const common_presets & presets) const {
493
+ common_presets out;
494
+ for (const auto & [name, preset] : presets) {
495
+ common_preset tmp = base; // copy
496
+ tmp.name = name;
497
+ tmp.merge(preset);
498
+ out[name] = std::move(tmp);
499
+ }
500
+ return out;
501
+ }
common/preset.h ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include "common.h"
4
+ #include "arg.h"
5
+
6
+ #include <string>
7
+ #include <vector>
8
+ #include <map>
9
+ #include <set>
10
+
11
+ //
12
+ // INI preset parser and writer
13
+ //
14
+
15
+ constexpr const char * COMMON_PRESET_DEFAULT_NAME = "default";
16
+
17
+ struct common_preset_context;
18
+
19
+ struct common_preset {
20
+ std::string name;
21
+
22
+ // options are stored as common_arg to string mapping, representing CLI arg and its value
23
+ std::map<common_arg, std::string> options;
24
+
25
+ // convert preset to CLI argument list
26
+ std::vector<std::string> to_args(const std::string & bin_path = "") const;
27
+
28
+ // convert preset to INI format string
29
+ std::string to_ini() const;
30
+
31
+ // TODO: maybe implement to_env() if needed
32
+
33
+ // modify preset options where argument is identified by its env variable
34
+ void set_option(const common_preset_context & ctx, const std::string & env, const std::string & value);
35
+
36
+ // unset option by its env variable
37
+ void unset_option(const std::string & env);
38
+
39
+ // get option value by its env variable, return false if not found
40
+ bool get_option(const std::string & env, std::string & value) const;
41
+
42
+ // merge another preset into this one, overwriting existing options
43
+ void merge(const common_preset & other);
44
+
45
+ // apply preset options to common_params
46
+ // optionally specify handled_keys to only apply a subset of options (identified by their env), if empty, apply all options
47
+ void apply_to_params(common_params & params, const std::set<std::string> & handled_keys = std::set<std::string>()) const;
48
+ };
49
+
50
+ // interface for multiple presets in one file
51
+ using common_presets = std::map<std::string, common_preset>;
52
+
53
+ // context for loading and editing presets
54
+ struct common_preset_context {
55
+ common_params default_params; // unused for now
56
+ common_params_context ctx_params;
57
+ std::map<std::string, common_arg> key_to_opt;
58
+
59
+ bool filter_allowed_keys = false;
60
+ std::set<std::string> allowed_keys;
61
+
62
+ // if true, options unknown to the current example are skipped instead of being an error
63
+ // used for config files shared by all binaries, where each binary only knows a subset of options
64
+ bool ignore_unknown_keys = false;
65
+
66
+ // if only_remote_allowed is true, only accept whitelisted keys
67
+ common_preset_context(llama_example ex);
68
+
69
+ // load presets from INI file
70
+ common_presets load_from_ini(const std::string & path, common_preset & global) const;
71
+
72
+ // generate presets from cached models
73
+ common_presets load_from_cache() const;
74
+
75
+ // generate presets from local models directory
76
+ // for the directory structure, see "Using multiple models" in server/README.md
77
+ common_presets load_from_models_dir(const std::string & models_dir) const;
78
+
79
+ // generate one preset from CLI arguments
80
+ common_preset load_from_args(int argc, char ** argv) const;
81
+
82
+ // cascade multiple presets if exist on both: base < added
83
+ // if preset does not exist in base, it will be added without modification
84
+ common_presets cascade(const common_presets & base, const common_presets & added) const;
85
+
86
+ // apply presets over a base preset (same idea as CSS cascading)
87
+ common_presets cascade(const common_preset & base, const common_presets & presets) const;
88
+ };
common/reasoning-budget.cpp ADDED
@@ -0,0 +1,310 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "reasoning-budget.h"
2
+ #include "common.h"
3
+ #include "trie.h"
4
+ #include "unicode.h"
5
+
6
+ #include "log.h"
7
+
8
+ #include <algorithm>
9
+ #include <cmath>
10
+ #include <cstdint>
11
+ #include <string>
12
+ #include <vector>
13
+
14
+ struct token_matcher {
15
+ std::vector<llama_tokens> seqs;
16
+ common_aho_corasick ac;
17
+ size_t state = 0;
18
+
19
+ token_matcher(const std::vector<llama_tokens> & seqs) : seqs(collect(seqs)), ac(build_trie(this->seqs)) {}
20
+
21
+ static std::vector<llama_tokens> collect(const std::vector<llama_tokens> & seqs) {
22
+ std::vector<llama_tokens> res;
23
+ for (const auto & seq : seqs) {
24
+ if (!seq.empty() && std::find(res.begin(), res.end(), seq) == res.end()) {
25
+ res.push_back(seq);
26
+ }
27
+ }
28
+ return res;
29
+ }
30
+
31
+ static common_trie build_trie(const std::vector<llama_tokens> & seqs) {
32
+ common_trie t;
33
+ for (const auto & seq : seqs) {
34
+ t.insert(std::vector<uint32_t>(seq.begin(), seq.end()));
35
+ }
36
+ return t;
37
+ }
38
+
39
+ // returns the index into seqs of the longest sequence ending at this token, or -1
40
+ int32_t advance(llama_token token) {
41
+ state = ac.next(state, (uint32_t) token);
42
+ const int32_t p = ac.match_pattern(state);
43
+ if (p >= 0) {
44
+ state = 0;
45
+ }
46
+ return p;
47
+ }
48
+
49
+ void reset() { state = 0; }
50
+ };
51
+
52
+ struct common_reasoning_budget_ctx {
53
+ const llama_vocab * vocab;
54
+
55
+ token_matcher start_matcher;
56
+ token_matcher end_matcher;
57
+ llama_tokens forced_tokens;
58
+
59
+ int32_t budget; // maximum tokens in reasoning block
60
+ int32_t remaining; // tokens remaining in budget
61
+
62
+ common_reasoning_budget_state state;
63
+
64
+ // for forcing
65
+ size_t force_pos; // next position in forced_tokens to force
66
+
67
+ int32_t end_match; // index into end_matcher.seqs of the sequence that transitioned to DONE, -1 if none
68
+ };
69
+
70
+ static const char * common_reasoning_budget_name(const struct llama_sampler * /*smpl*/) {
71
+ return "reasoning-budget";
72
+ }
73
+
74
+ static void common_reasoning_budget_accept(struct llama_sampler * smpl, llama_token token) {
75
+ auto * ctx = (common_reasoning_budget_ctx *) smpl->ctx;
76
+
77
+ switch (ctx->state) {
78
+ case REASONING_BUDGET_IDLE:
79
+ {
80
+ if (ctx->start_matcher.advance(token) >= 0) {
81
+ ctx->state = REASONING_BUDGET_COUNTING;
82
+ ctx->remaining = ctx->budget;
83
+ COM_TRC("activated, budget=%d tokens\n", ctx->budget);
84
+
85
+ if (ctx->remaining <= 0) {
86
+ ctx->state = REASONING_BUDGET_FORCING;
87
+ ctx->force_pos = 0;
88
+ COM_TRC("%s", "budget=0, forcing immediately\n");
89
+ }
90
+ }
91
+ break;
92
+ }
93
+ case REASONING_BUDGET_COUNTING:
94
+ case REASONING_BUDGET_WAITING_UTF8:
95
+ {
96
+ const int32_t match = ctx->end_matcher.advance(token);
97
+ if (match >= 0) {
98
+ ctx->state = REASONING_BUDGET_DONE;
99
+ ctx->end_match = match;
100
+ COM_TRC("%s", "deactivated (natural end)\n");
101
+ break;
102
+ }
103
+
104
+ bool utf8_complete = true;
105
+ if (ctx->vocab != nullptr) {
106
+ const std::string piece = common_token_to_piece(ctx->vocab, token, false);
107
+ utf8_complete = common_utf8_is_complete(piece);
108
+ }
109
+
110
+ if (ctx->state == REASONING_BUDGET_WAITING_UTF8) {
111
+ if (utf8_complete) {
112
+ ctx->state = REASONING_BUDGET_FORCING;
113
+ ctx->force_pos = 0;
114
+ ctx->end_matcher.reset();
115
+ COM_TRC("%s", "UTF-8 complete, now forcing end sequence\n");
116
+ }
117
+ } else if (ctx->state == REASONING_BUDGET_COUNTING) {
118
+ ctx->remaining--;
119
+ if (ctx->remaining <= 0) {
120
+ if (utf8_complete) {
121
+ ctx->state = REASONING_BUDGET_FORCING;
122
+ ctx->force_pos = 0;
123
+ ctx->end_matcher.reset();
124
+ COM_TRC("%s", "budget exhausted, forcing end sequence\n");
125
+ } else {
126
+ ctx->state = REASONING_BUDGET_WAITING_UTF8;
127
+ ctx->end_matcher.reset();
128
+ COM_TRC("%s", "budget exhausted, waiting for UTF-8 completion\n");
129
+ }
130
+ }
131
+ }
132
+ break;
133
+ }
134
+ case REASONING_BUDGET_FORCING:
135
+ {
136
+ // track the end sequence within forced_tokens so it is also reported on DONE
137
+ const int32_t match = ctx->end_matcher.advance(token);
138
+ ctx->force_pos++;
139
+ if (ctx->force_pos >= ctx->forced_tokens.size()) {
140
+ ctx->state = REASONING_BUDGET_DONE;
141
+ ctx->end_match = match;
142
+ COM_TRC("%s", "forced sequence complete, done\n");
143
+ }
144
+ break;
145
+ }
146
+ case REASONING_BUDGET_DONE:
147
+ // Re-arm on a new start tag: some models emit multiple <think> blocks
148
+ // per response, and each should get a fresh budget window.
149
+ if (ctx->start_matcher.advance(token) >= 0) {
150
+ ctx->state = REASONING_BUDGET_COUNTING;
151
+ ctx->remaining = ctx->budget;
152
+ ctx->end_matcher.reset();
153
+ ctx->end_match = -1;
154
+ COM_TRC("re-activated on new start tag, budget=%d tokens\n", ctx->budget);
155
+
156
+ if (ctx->remaining <= 0) {
157
+ ctx->state = REASONING_BUDGET_FORCING;
158
+ ctx->force_pos = 0;
159
+ COM_TRC("%s", "budget=0, forcing immediately\n");
160
+ }
161
+ }
162
+ break;
163
+ }
164
+ }
165
+
166
+ static void common_reasoning_budget_apply(struct llama_sampler * smpl, llama_token_data_array * cur_p) {
167
+ auto * ctx = (common_reasoning_budget_ctx *) smpl->ctx;
168
+
169
+ if (ctx->state != REASONING_BUDGET_FORCING) {
170
+ // passthrough — don't modify logits
171
+ return;
172
+ }
173
+
174
+ if (ctx->force_pos >= ctx->forced_tokens.size()) {
175
+ return;
176
+ }
177
+
178
+ const llama_token forced = ctx->forced_tokens[ctx->force_pos];
179
+
180
+ // set all logits to -inf except the forced token
181
+ for (size_t i = 0; i < cur_p->size; i++) {
182
+ if (cur_p->data[i].id != forced) {
183
+ cur_p->data[i].logit = -INFINITY;
184
+ }
185
+ }
186
+ }
187
+
188
+ static void common_reasoning_budget_reset(struct llama_sampler * smpl) {
189
+ auto * ctx = (common_reasoning_budget_ctx *) smpl->ctx;
190
+ ctx->state = REASONING_BUDGET_IDLE;
191
+ ctx->remaining = ctx->budget;
192
+ ctx->start_matcher.reset();
193
+ ctx->end_matcher.reset();
194
+ ctx->force_pos = 0;
195
+ ctx->end_match = -1;
196
+ }
197
+
198
+ static struct llama_sampler * common_reasoning_budget_init_state(
199
+ const struct llama_vocab * vocab, const std::vector<llama_tokens> & start_seqs,
200
+ const std::vector<llama_tokens> & end_seqs, const llama_tokens & forced_tokens,
201
+ int32_t budget, common_reasoning_budget_state initial_state);
202
+
203
+ static struct llama_sampler * common_reasoning_budget_clone(const struct llama_sampler * smpl);
204
+
205
+ static void common_reasoning_budget_free(struct llama_sampler * smpl) {
206
+ delete (common_reasoning_budget_ctx *) smpl->ctx;
207
+ }
208
+
209
+ static struct llama_sampler_i common_reasoning_budget_i = {
210
+ /* .name = */ common_reasoning_budget_name,
211
+ /* .accept = */ common_reasoning_budget_accept,
212
+ /* .apply = */ common_reasoning_budget_apply,
213
+ /* .reset = */ common_reasoning_budget_reset,
214
+ /* .clone = */ common_reasoning_budget_clone,
215
+ /* .free = */ common_reasoning_budget_free,
216
+ /* .backend_init = */ nullptr,
217
+ /* .backend_accept = */ nullptr,
218
+ /* .backend_apply = */ nullptr,
219
+ /* .backend_set_input = */ nullptr,
220
+ /* .backend_reset = */ nullptr,
221
+ /* .copy_state = */ nullptr,
222
+ };
223
+
224
+ static struct llama_sampler * common_reasoning_budget_clone(const struct llama_sampler * smpl) {
225
+ const auto * ctx = (const common_reasoning_budget_ctx *) smpl->ctx;
226
+
227
+ return llama_sampler_init(
228
+ /* .iface = */ &common_reasoning_budget_i,
229
+ /* .ctx = */ new common_reasoning_budget_ctx(*ctx)
230
+ );
231
+ }
232
+
233
+ static struct llama_sampler * common_reasoning_budget_init_state(
234
+ const struct llama_vocab * vocab,
235
+ const std::vector<llama_tokens> & start_seqs,
236
+ const std::vector<llama_tokens> & end_seqs,
237
+ const llama_tokens & forced_tokens,
238
+ int32_t budget,
239
+ common_reasoning_budget_state initial_state) {
240
+ // promote COUNTING with budget <= 0 to FORCING
241
+ if (initial_state == REASONING_BUDGET_COUNTING && budget <= 0) {
242
+ initial_state = REASONING_BUDGET_FORCING;
243
+ }
244
+
245
+ return llama_sampler_init(
246
+ /* .iface = */ &common_reasoning_budget_i,
247
+ /* .ctx = */ new common_reasoning_budget_ctx {
248
+ /* .vocab = */ vocab,
249
+ /* .start_matcher = */ token_matcher(start_seqs),
250
+ /* .end_matcher = */ token_matcher(end_seqs),
251
+ /* .forced_tokens = */ forced_tokens,
252
+ /* .budget = */ budget,
253
+ /* .remaining = */ budget,
254
+ /* .state = */ initial_state,
255
+ /* .force_pos = */ 0,
256
+ /* .end_match = */ -1,
257
+ }
258
+ );
259
+ }
260
+
261
+ struct llama_sampler * common_reasoning_budget_init(
262
+ const struct llama_vocab * vocab,
263
+ const std::vector<llama_tokens> & start_seqs,
264
+ const std::vector<llama_tokens> & end_seqs,
265
+ const llama_tokens & forced_tokens,
266
+ int32_t budget,
267
+ common_reasoning_budget_state initial_state) {
268
+ return common_reasoning_budget_init_state(vocab, start_seqs, end_seqs, forced_tokens, budget, initial_state);
269
+ }
270
+
271
+ common_reasoning_budget_state common_reasoning_budget_get_state(const struct llama_sampler * smpl) {
272
+ if (!smpl) {
273
+ return REASONING_BUDGET_IDLE;
274
+ }
275
+ return ((const common_reasoning_budget_ctx *)smpl->ctx)->state;
276
+ }
277
+
278
+ const llama_tokens * common_reasoning_budget_get_end_match(const struct llama_sampler * smpl) {
279
+ if (!smpl) {
280
+ return nullptr;
281
+ }
282
+
283
+ const auto * ctx = (const common_reasoning_budget_ctx *) smpl->ctx;
284
+ if (ctx->end_match < 0) {
285
+ return nullptr;
286
+ }
287
+
288
+ return &ctx->end_matcher.seqs[ctx->end_match];
289
+ }
290
+
291
+ bool common_reasoning_budget_force(struct llama_sampler * smpl) {
292
+ if (!smpl) {
293
+ return false;
294
+ }
295
+
296
+ auto * ctx = (common_reasoning_budget_ctx *) smpl->ctx;
297
+
298
+ // only a sampler that is actively counting down the budget may be forced;
299
+ // any other state (idle, already forcing/waiting, or done) is left untouched
300
+ if (ctx->state != REASONING_BUDGET_COUNTING) {
301
+ return false;
302
+ }
303
+
304
+ ctx->state = REASONING_BUDGET_FORCING;
305
+ ctx->force_pos = 0;
306
+ ctx->end_matcher.reset();
307
+ COM_TRC("%s", "forced into forcing state (manual transition)\n");
308
+
309
+ return true;
310
+ }
common/reasoning-budget.h ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include "llama.h"
4
+
5
+ #include "common.h"
6
+
7
+ #include <cstdint>
8
+ #include <vector>
9
+
10
+ enum common_reasoning_budget_state {
11
+ REASONING_BUDGET_IDLE, // waiting for start sequence
12
+ REASONING_BUDGET_COUNTING, // counting down tokens
13
+ REASONING_BUDGET_FORCING, // forcing budget message + end sequence
14
+ REASONING_BUDGET_WAITING_UTF8, // budget exhausted, waiting for UTF-8 completion
15
+ REASONING_BUDGET_DONE, // passthrough forever
16
+ };
17
+
18
+ // Creates a reasoning budget sampler that limits token generation inside a
19
+ // reasoning block (e.g. between <think> and </think>).
20
+ //
21
+ // State machine: IDLE -> COUNTING -> WAITING_UTF8 -> FORCING -> DONE
22
+ // IDLE: passthrough, watching for a start sequence
23
+ // COUNTING: counting down remaining tokens, watching for a natural end sequence
24
+ // WAITING_UTF8: budget exhausted, allowing tokens to complete a UTF-8 sequence
25
+ // FORCING: forces forced_tokens token-by-token (all other logits -> -inf)
26
+ // DONE: passthrough forever
27
+ //
28
+ // Parameters:
29
+ // vocab - vocabulary (used for UTF-8 boundary detection; can be nullptr)
30
+ // start_seqs - token sequences, any of which activates counting
31
+ // end_seqs - token sequences, any of which naturally deactivates
32
+ // forced_tokens - token sequence forced when budget expires
33
+ // budget - max tokens allowed in the reasoning block
34
+ // initial_state - initial state
35
+ //
36
+ struct llama_sampler * common_reasoning_budget_init(
37
+ const struct llama_vocab * vocab,
38
+ const std::vector<llama_tokens> & start_seqs,
39
+ const std::vector<llama_tokens> & end_seqs,
40
+ const llama_tokens & forced_tokens,
41
+ int32_t budget,
42
+ common_reasoning_budget_state initial_state = REASONING_BUDGET_IDLE);
43
+
44
+ common_reasoning_budget_state common_reasoning_budget_get_state(const struct llama_sampler * smpl);
45
+
46
+ // The end sequence that transitioned the sampler to DONE, or nullptr if none
47
+ // was recorded. Cleared when a new start sequence re-arms the sampler.
48
+ const llama_tokens * common_reasoning_budget_get_end_match(const struct llama_sampler * smpl);
49
+
50
+ // Manually transition the reasoning budget sampler into the FORCING state.
51
+ // Returns true if the transition occurred.
52
+ bool common_reasoning_budget_force(struct llama_sampler * smpl);
common/sampling.cpp ADDED
@@ -0,0 +1,919 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "sampling.h"
2
+
3
+ #include "common.h"
4
+ #include "fit.h"
5
+ #include "log.h"
6
+ #include "reasoning-budget.h"
7
+
8
+ #include "ggml.h"
9
+
10
+ #include <algorithm>
11
+ #include <cctype>
12
+ #include <climits>
13
+ #include <cmath>
14
+ #include <cstring>
15
+ #include <unordered_map>
16
+ #include <vector>
17
+
18
+ // the ring buffer works similarly to std::deque, but with a fixed capacity
19
+ // TODO: deduplicate with llama-impl.h
20
+ template<typename T>
21
+ struct ring_buffer {
22
+ ring_buffer(size_t cap) : capacity(cap), data(cap) {}
23
+
24
+ T & front() {
25
+ if (sz == 0) {
26
+ throw std::runtime_error("ring buffer is empty");
27
+ }
28
+ return data[first];
29
+ }
30
+
31
+ const T & front() const {
32
+ if (sz == 0) {
33
+ throw std::runtime_error("ring buffer is empty");
34
+ }
35
+ return data[first];
36
+ }
37
+
38
+ T & back() {
39
+ if (sz == 0) {
40
+ throw std::runtime_error("ring buffer is empty");
41
+ }
42
+ return data[pos];
43
+ }
44
+
45
+ const T & back() const {
46
+ if (sz == 0) {
47
+ throw std::runtime_error("ring buffer is empty");
48
+ }
49
+ return data[pos];
50
+ }
51
+
52
+ void push_back(const T & value) {
53
+ if (sz == capacity) {
54
+ // advance the start when buffer is full
55
+ first = (first + 1) % capacity;
56
+ } else {
57
+ sz++;
58
+ }
59
+ data[pos] = value;
60
+ pos = (pos + 1) % capacity;
61
+ }
62
+
63
+ T pop_front() {
64
+ if (sz == 0) {
65
+ throw std::runtime_error("ring buffer is empty");
66
+ }
67
+ T value = data[first];
68
+ first = (first + 1) % capacity;
69
+ sz--;
70
+ return value;
71
+ }
72
+
73
+ const T & rat(size_t i) const {
74
+ if (i >= sz) {
75
+ throw std::runtime_error("ring buffer: index out of bounds");
76
+ }
77
+ return data[(first + sz - i - 1) % capacity];
78
+ }
79
+
80
+ std::vector<T> to_vector() const {
81
+ std::vector<T> result;
82
+ result.reserve(sz);
83
+ for (size_t i = 0; i < sz; i++) {
84
+ result.push_back(data[(first + i) % capacity]);
85
+ }
86
+ return result;
87
+ }
88
+
89
+ void clear() {
90
+ // here only reset the status of the buffer
91
+ sz = 0;
92
+ first = 0;
93
+ pos = 0;
94
+ }
95
+
96
+ bool empty() const {
97
+ return sz == 0;
98
+ }
99
+
100
+ size_t size() const {
101
+ return sz;
102
+ }
103
+
104
+ size_t capacity = 0;
105
+ size_t sz = 0;
106
+ size_t first = 0;
107
+ size_t pos = 0;
108
+ std::vector<T> data;
109
+ };
110
+
111
+ struct common_sampler {
112
+ common_params_sampling params;
113
+
114
+ struct llama_sampler * grmr;
115
+ struct llama_sampler * rbudget;
116
+ struct llama_sampler * chain;
117
+
118
+ ring_buffer<llama_token> prev;
119
+
120
+ std::vector<llama_token_data> cur;
121
+
122
+ llama_token_data_array cur_p;
123
+
124
+ void reset() {
125
+ prev.clear();
126
+
127
+ llama_sampler_reset(chain);
128
+ }
129
+
130
+ void set_logits(struct llama_context * ctx, int idx) {
131
+ const float * sampled_probs = llama_get_sampled_probs_ith (ctx, idx);
132
+ const float * sampled_logits = llama_get_sampled_logits_ith (ctx, idx);
133
+ const llama_token * sampled_ids = llama_get_sampled_candidates_ith(ctx, idx);
134
+
135
+ const llama_model * model = llama_get_model(ctx);
136
+ const llama_vocab * vocab = llama_model_get_vocab(model);
137
+
138
+ const int n_vocab = llama_vocab_n_tokens(vocab);
139
+
140
+ if (sampled_probs) {
141
+ const uint32_t sampled_probs_count = llama_get_sampled_probs_count_ith(ctx, idx);
142
+ cur.resize(sampled_probs_count);
143
+ for (uint32_t i = 0; i < sampled_probs_count; ++i) {
144
+ cur[i] = llama_token_data{sampled_ids[i], sampled_logits[i], sampled_probs[i]};
145
+ }
146
+ } else if (sampled_logits) {
147
+ const uint32_t sampled_logits_count = llama_get_sampled_logits_count_ith(ctx, idx);
148
+ cur.resize(sampled_logits_count);
149
+ for (uint32_t i = 0; i < sampled_logits_count; i++) {
150
+ cur[i] = llama_token_data{sampled_ids[i], sampled_logits[i], 0.0f};
151
+ }
152
+ } else {
153
+ const auto * logits = llama_get_logits_ith(ctx, idx);
154
+ GGML_ASSERT(logits != nullptr);
155
+ cur.resize(n_vocab);
156
+ for (llama_token token_id = 0; token_id < n_vocab; token_id++) {
157
+ cur[token_id] = llama_token_data{token_id, logits[token_id], 0.0f};
158
+ }
159
+ }
160
+
161
+ cur_p = { cur.data(), cur.size(), -1, false };
162
+ }
163
+
164
+ common_time_meas tm() {
165
+ return common_time_meas(t_total_us, params.no_perf);
166
+ }
167
+
168
+ mutable int64_t t_total_us = 0;
169
+ };
170
+
171
+ std::string common_params_sampling::print() const {
172
+ char result[1024];
173
+
174
+ snprintf(result, sizeof(result),
175
+ "\trepeat_last_n = %d, repeat_penalty = %.3f, frequency_penalty = %.3f, presence_penalty = %.3f\n"
176
+ "\tdry_multiplier = %.3f, dry_base = %.3f, dry_allowed_length = %d, dry_penalty_last_n = %d\n"
177
+ "\ttop_k = %d, top_p = %.3f, min_p = %.3f, xtc_probability = %.3f, xtc_threshold = %.3f, typical_p = %.3f, top_n_sigma = %.3f, temp = %.3f\n"
178
+ "\tmirostat = %d, mirostat_lr = %.3f, mirostat_ent = %.3f, adaptive_target = %.3f, adaptive_decay = %.3f",
179
+ penalty_last_n, penalty_repeat, penalty_freq, penalty_present,
180
+ dry_multiplier, dry_base, dry_allowed_length, dry_penalty_last_n,
181
+ top_k, top_p, min_p, xtc_probability, xtc_threshold, typ_p, top_n_sigma, temp,
182
+ mirostat, mirostat_eta, mirostat_tau, adaptive_target, adaptive_decay);
183
+
184
+ return std::string(result);
185
+ }
186
+
187
+ struct common_sampler * common_sampler_init(
188
+ const struct llama_model * model,
189
+ struct common_params_sampling & params) {
190
+ if (!std::isfinite(params.penalty_repeat) ||
191
+ params.penalty_repeat <= 0.0f ||
192
+ !std::isfinite(1.0f/params.penalty_repeat)) {
193
+ throw std::invalid_argument("penalty_repeat must be finite and greater than 0");
194
+ }
195
+ if (!std::isfinite(params.penalty_freq)) {
196
+ throw std::invalid_argument("penalty_freq must be finite");
197
+ }
198
+ if (!std::isfinite(params.penalty_present)) {
199
+ throw std::invalid_argument("penalty_present must be finite");
200
+ }
201
+ const llama_vocab * vocab = llama_model_get_vocab(model);
202
+ llama_sampler_chain_params lparams = llama_sampler_chain_default_params();
203
+
204
+ lparams.no_perf = params.no_perf;
205
+
206
+ llama_sampler * grmr = nullptr;
207
+ llama_sampler * rbudget = nullptr;
208
+ llama_sampler * chain = llama_sampler_chain_init(lparams);
209
+
210
+ std::vector<llama_sampler *> samplers;
211
+
212
+ const std::string & grammar_str = common_grammar_value(params.grammar);
213
+ if (grammar_str.compare(0, 11, "%llguidance") == 0) {
214
+ #ifdef LLAMA_USE_LLGUIDANCE
215
+ grmr = llama_sampler_init_llg(vocab, "lark", grammar_str.c_str());
216
+ #else
217
+ GGML_ABORT("llguidance (cmake -DLLAMA_LLGUIDANCE=ON) is not enabled");
218
+ #endif // LLAMA_USE_LLGUIDANCE
219
+ } else {
220
+ std::vector<std::string> trigger_patterns;
221
+ std::vector<llama_token> trigger_tokens;
222
+ for (const auto & trigger : params.grammar_triggers) {
223
+ switch (trigger.type) {
224
+ case COMMON_GRAMMAR_TRIGGER_TYPE_WORD:
225
+ {
226
+ const auto & word = trigger.value;
227
+ trigger_patterns.push_back(regex_escape(word));
228
+ break;
229
+ }
230
+ case COMMON_GRAMMAR_TRIGGER_TYPE_PATTERN:
231
+ {
232
+ trigger_patterns.push_back(trigger.value);
233
+ break;
234
+ }
235
+ case COMMON_GRAMMAR_TRIGGER_TYPE_PATTERN_FULL:
236
+ {
237
+ const auto & pattern = trigger.value;
238
+ std::string anchored = "^$";
239
+ if (!pattern.empty()) {
240
+ anchored = (pattern.front() != '^' ? "^" : "")
241
+ + pattern
242
+ + (pattern.back() != '$' ? "$" : "");
243
+ }
244
+ trigger_patterns.push_back(anchored);
245
+ break;
246
+ }
247
+ case COMMON_GRAMMAR_TRIGGER_TYPE_TOKEN:
248
+ {
249
+ const auto token = trigger.token;
250
+ trigger_tokens.push_back(token);
251
+ break;
252
+ }
253
+ default:
254
+ GGML_ASSERT(false && "unknown trigger type");
255
+ }
256
+ }
257
+
258
+ std::vector<const char *> trigger_patterns_c;
259
+ trigger_patterns_c.reserve(trigger_patterns.size());
260
+ for (const auto & regex : trigger_patterns) {
261
+ trigger_patterns_c.push_back(regex.c_str());
262
+ }
263
+
264
+ if (!grammar_str.empty()) {
265
+ if (params.grammar_lazy) {
266
+ grmr = llama_sampler_init_grammar_lazy_patterns(vocab, grammar_str.c_str(), "root",
267
+ trigger_patterns_c.data(), trigger_patterns_c.size(),
268
+ trigger_tokens.data(), trigger_tokens.size());
269
+ } else {
270
+ grmr = llama_sampler_init_grammar(vocab, grammar_str.c_str(), "root");
271
+ }
272
+ }
273
+ }
274
+ if (!grmr && !grammar_str.empty()) {
275
+ throw std::runtime_error("failed to parse grammar");
276
+ }
277
+
278
+ // Compute prefill tokens from the generation prompt
279
+ std::vector<llama_token> prefill_tokens;
280
+ if (!params.generation_prompt.empty()) {
281
+ GGML_ASSERT(vocab != nullptr);
282
+ auto tokens = common_tokenize(vocab, params.generation_prompt, false, true);
283
+ for (size_t i = 0; i < tokens.size(); i++) {
284
+ std::string piece = common_token_to_piece(vocab, tokens[i], true);
285
+ if (i == 0 && std::isspace(piece[0]) && !std::isspace(params.generation_prompt[0])) {
286
+ // Some tokenizers will add a space before the first special token, need to exclude
287
+ continue;
288
+ }
289
+ LOG_DBG("%s: prefill token: %d = %s\n", __func__, tokens[i], piece.c_str());
290
+ prefill_tokens.push_back(tokens[i]);
291
+ }
292
+ }
293
+
294
+ // Feed generation prompt tokens to the grammar sampler so it advances past
295
+ // tokens the template already placed in the prompt.
296
+ // Only applies to output-format and tool-call grammars; user-supplied grammars must not be prefilled.
297
+ if (grmr && !params.grammar_lazy && common_grammar_needs_prefill(params.grammar)) {
298
+ try {
299
+ for (const auto & token : prefill_tokens) {
300
+ llama_sampler_accept(grmr, token);
301
+ LOG_DBG("%s: grammar accepted prefill token (%d)\n", __func__, token);
302
+ }
303
+ } catch (std::exception &e) {
304
+ LOG_ERR("%s: error initializing grammar sampler for grammar:\n%s\n\nGeneration prompt:\n'%s'\n", __func__,
305
+ common_grammar_value(params.grammar).c_str(), params.generation_prompt.c_str());
306
+ throw e;
307
+ }
308
+ }
309
+
310
+ // reasoning budget sampler (skip when budget is unlimited unless a lazy grammar is active, which needs rbudget for thinking-block suppression)
311
+ if (!params.reasoning_budget_start.empty() && !params.reasoning_budget_end.empty() && (params.grammar_lazy || params.reasoning_budget_tokens >= 0 || params.reasoning_control)) {
312
+ rbudget = common_reasoning_budget_init(
313
+ vocab,
314
+ {params.reasoning_budget_start},
315
+ params.reasoning_budget_end,
316
+ params.reasoning_budget_forced,
317
+ params.reasoning_budget_tokens < 0 ? INT_MAX : params.reasoning_budget_tokens);
318
+
319
+ for (const auto & token : prefill_tokens) {
320
+ llama_sampler_accept(rbudget, token);
321
+ LOG_DBG("%s: reasoning-budget accepted prefill token (%d)\n", __func__, token);
322
+ }
323
+ }
324
+
325
+ // logit bias: user biases + model suppress tokens (-INFINITY)
326
+ {
327
+ std::vector<llama_logit_bias> merged = params.logit_bias;
328
+
329
+ int32_t n_suppress = 0;
330
+ const llama_token * suppress = llama_vocab_get_suppress_tokens(vocab, &n_suppress);
331
+ for (int32_t i = 0; i < n_suppress; ++i) {
332
+ merged.push_back({ suppress[i], -INFINITY });
333
+ }
334
+
335
+ if (!merged.empty()) {
336
+ samplers.push_back(llama_sampler_init_logit_bias(llama_vocab_n_tokens(vocab), merged.size(), merged.data()));
337
+ }
338
+ }
339
+
340
+ if (params.mirostat == 0) {
341
+
342
+ bool use_adaptive_p = false; // see below
343
+
344
+ for (const auto & cnstr : params.samplers) {
345
+ switch (cnstr) {
346
+ case COMMON_SAMPLER_TYPE_DRY:
347
+ {
348
+ std::vector<const char *> c_breakers;
349
+ c_breakers.reserve(params.dry_sequence_breakers.size());
350
+ for (const auto & str : params.dry_sequence_breakers) {
351
+ c_breakers.push_back(str.c_str());
352
+ }
353
+ samplers.push_back(llama_sampler_init_dry(vocab, params.dry_multiplier, params.dry_base, params.dry_allowed_length, params.dry_penalty_last_n, c_breakers.data(), c_breakers.size()));
354
+ }
355
+ break;
356
+ case COMMON_SAMPLER_TYPE_TOP_K:
357
+ samplers.push_back(llama_sampler_init_top_k(params.top_k));
358
+ break;
359
+ case COMMON_SAMPLER_TYPE_TOP_P:
360
+ samplers.push_back(llama_sampler_init_top_p(params.top_p, params.min_keep));
361
+ break;
362
+ case COMMON_SAMPLER_TYPE_TOP_N_SIGMA:
363
+ samplers.push_back(llama_sampler_init_top_n_sigma(params.top_n_sigma));
364
+ break;
365
+ case COMMON_SAMPLER_TYPE_MIN_P:
366
+ samplers.push_back(llama_sampler_init_min_p(params.min_p, params.min_keep));
367
+ break;
368
+ case COMMON_SAMPLER_TYPE_XTC:
369
+ samplers.push_back(llama_sampler_init_xtc(params.xtc_probability, params.xtc_threshold, params.min_keep, params.seed));
370
+ break;
371
+ case COMMON_SAMPLER_TYPE_TYPICAL_P:
372
+ samplers.push_back(llama_sampler_init_typical(params.typ_p, params.min_keep));
373
+ break;
374
+ case COMMON_SAMPLER_TYPE_TEMPERATURE:
375
+ samplers.push_back(llama_sampler_init_temp_ext(params.temp, params.dynatemp_range, params.dynatemp_exponent));
376
+ break;
377
+ case COMMON_SAMPLER_TYPE_INFILL:
378
+ samplers.push_back(llama_sampler_init_infill(vocab));
379
+ break;
380
+ case COMMON_SAMPLER_TYPE_PENALTIES:
381
+ samplers.push_back(llama_sampler_init_penalties(llama_vocab_n_tokens(vocab), params.penalty_last_n, params.penalty_repeat, params.penalty_freq, params.penalty_present));
382
+ break;
383
+ case COMMON_SAMPLER_TYPE_ADAPTIVE_P:
384
+ // the `adaptive-p` sampler is like `dist` and `mirostat` in that it selects
385
+ // a single token, so we will add `dist` at the end of the chain by default,
386
+ // unless the user specifically included `adaptive-p`. we set this flag here
387
+ // so we know to add the sampler at the very end.
388
+ use_adaptive_p = true;
389
+ break;
390
+ default:
391
+ GGML_ASSERT(false && "unknown sampler type");
392
+ }
393
+ }
394
+ if (use_adaptive_p) {
395
+ // only if user explicitly included adaptive-p sampler
396
+ samplers.push_back(llama_sampler_init_adaptive_p(params.adaptive_target, params.adaptive_decay, params.seed));
397
+ } else {
398
+ // default: sample from distribution
399
+ samplers.push_back(llama_sampler_init_dist(params.seed));
400
+ }
401
+ } else if (params.mirostat == 1) {
402
+ samplers.push_back(llama_sampler_init_temp(params.temp));
403
+ samplers.push_back(llama_sampler_init_mirostat(llama_vocab_n_tokens(vocab), params.seed, params.mirostat_tau, params.mirostat_eta, 100));
404
+ } else if (params.mirostat == 2) {
405
+ samplers.push_back(llama_sampler_init_temp(params.temp));
406
+ samplers.push_back(llama_sampler_init_mirostat_v2(params.seed, params.mirostat_tau, params.mirostat_eta));
407
+ } else {
408
+ GGML_ASSERT(false && "unknown mirostat version");
409
+ }
410
+
411
+ for (auto * smpl : samplers) {
412
+ llama_sampler_chain_add(chain, smpl);
413
+ }
414
+
415
+ if (grmr && params.backend_sampling) {
416
+ LOG_WRN("%s: backend sampling is not compatible with grammar, disabling\n", __func__);
417
+
418
+ params.backend_sampling = false;
419
+ }
420
+
421
+ if (rbudget && params.backend_sampling) {
422
+ LOG_WRN("%s: backend sampling is not compatible with reasoning budget, disabling\n", __func__);
423
+
424
+ params.backend_sampling = false;
425
+ }
426
+
427
+ auto * result = new common_sampler {
428
+ /* .params = */ params,
429
+ /* .grmr = */ grmr,
430
+ /* .rbudget = */ rbudget,
431
+ /* .chain = */ chain,
432
+ /* .prev = */ ring_buffer<llama_token>(std::max(32, params.n_prev)),
433
+ /* .cur = */ {},
434
+ /* .cur_p = */ {},
435
+ };
436
+
437
+ return result;
438
+ }
439
+
440
+ void common_sampler_free(struct common_sampler * gsmpl) {
441
+ if (!gsmpl) {
442
+ return;
443
+ }
444
+
445
+ llama_sampler_free(gsmpl->grmr);
446
+ llama_sampler_free(gsmpl->rbudget);
447
+ llama_sampler_free(gsmpl->chain);
448
+
449
+ delete gsmpl;
450
+ }
451
+
452
+ static bool grammar_should_apply(struct common_sampler * gsmpl) {
453
+ if (!gsmpl->grmr) {
454
+ return false;
455
+ }
456
+ if (!gsmpl->rbudget) {
457
+ return true;
458
+ }
459
+ if (gsmpl->params.grammar_lazy) {
460
+ // if grammar is lazy, only apply when reasoning budget is not active
461
+ const auto state = common_reasoning_budget_get_state(gsmpl->rbudget);
462
+ return state == REASONING_BUDGET_IDLE || state == REASONING_BUDGET_DONE;
463
+ }
464
+ return true;
465
+ }
466
+
467
+ void common_sampler_accept(struct common_sampler * gsmpl, llama_token token, bool is_generated) {
468
+ if (!gsmpl) {
469
+ return;
470
+ }
471
+
472
+ const auto tm = gsmpl->tm();
473
+
474
+ // grammar_should_apply() checks the reasoning budget state, so calculate this before we accept
475
+ const auto accept_grammar = is_generated && grammar_should_apply(gsmpl);
476
+
477
+ if (gsmpl->rbudget && is_generated) {
478
+ llama_sampler_accept(gsmpl->rbudget, token);
479
+
480
+ // if done, replay end sequence which may contain a grammar trigger
481
+ const bool is_done = common_reasoning_budget_get_state(gsmpl->rbudget) == REASONING_BUDGET_DONE;
482
+ if (gsmpl->grmr && !accept_grammar && is_done) {
483
+ const llama_tokens * end_seq = common_reasoning_budget_get_end_match(gsmpl->rbudget);
484
+ if (end_seq) {
485
+ for (const llama_token end_token : *end_seq) {
486
+ llama_sampler_accept(gsmpl->grmr, end_token);
487
+ }
488
+ }
489
+ }
490
+ }
491
+
492
+ if (gsmpl->grmr && accept_grammar) {
493
+ llama_sampler_accept(gsmpl->grmr, token);
494
+ }
495
+
496
+ llama_sampler_accept(gsmpl->chain, token);
497
+
498
+ gsmpl->prev.push_back(token);
499
+ }
500
+
501
+ void common_sampler_reset(struct common_sampler * gsmpl) {
502
+ if (!gsmpl) {
503
+ return;
504
+ }
505
+
506
+ gsmpl->reset();
507
+ }
508
+
509
+ struct common_sampler * common_sampler_clone(common_sampler * gsmpl) {
510
+ return new common_sampler {
511
+ /* .params = */ gsmpl->params,
512
+ /* .grmr = */ llama_sampler_clone(gsmpl->grmr),
513
+ /* .rbudget = */ llama_sampler_clone(gsmpl->rbudget),
514
+ /* .chain = */ llama_sampler_clone(gsmpl->chain),
515
+ /* .prev = */ gsmpl->prev,
516
+ /* .cur = */ gsmpl->cur,
517
+ /* .cur_p = */ gsmpl->cur_p,
518
+ };
519
+ }
520
+
521
+ void common_sampler_copy(const common_sampler * src, common_sampler * dst) {
522
+ if (!src || !dst || src == dst) {
523
+ return;
524
+ }
525
+
526
+ GGML_ASSERT((src->grmr == nullptr) == (dst->grmr == nullptr));
527
+ GGML_ASSERT((src->rbudget == nullptr) == (dst->rbudget == nullptr));
528
+
529
+ llama_sampler_copy(src->grmr, dst->grmr);
530
+ llama_sampler_copy(src->rbudget, dst->rbudget);
531
+ llama_sampler_copy(src->chain, dst->chain);
532
+
533
+ dst->params = src->params;
534
+ dst->prev = src->prev;
535
+ dst->cur = src->cur;
536
+ dst->cur_p = src->cur_p;
537
+ dst->cur_p.data = src->cur_p.data ? dst->cur.data() : nullptr; // re-point to dst's buffer
538
+ dst->t_total_us = src->t_total_us;
539
+ }
540
+
541
+ void common_perf_print(const struct llama_context * ctx, const struct common_sampler * gsmpl) {
542
+ // TODO: measure grammar performance
543
+
544
+ const double t_sampling_ms = gsmpl ? 1e-3*gsmpl->t_total_us : 0;
545
+
546
+ llama_perf_sampler_data data_smpl;
547
+ llama_perf_context_data data_ctx;
548
+
549
+ memset(&data_smpl, 0, sizeof(data_smpl));
550
+ memset(&data_ctx, 0, sizeof(data_ctx));
551
+
552
+ if (gsmpl) {
553
+ auto & data = data_smpl;
554
+
555
+ data = llama_perf_sampler(gsmpl->chain);
556
+
557
+ // note: the sampling time includes the samplers time + extra time spent in common/sampling
558
+ LOG_INF("%s: sampling time = %10.2f ms\n", __func__, t_sampling_ms);
559
+ LOG_INF("%s: samplers time = %10.2f ms / %5d tokens\n", __func__, data.t_sample_ms, data.n_sample);
560
+ }
561
+
562
+ if (ctx) {
563
+ auto & data = data_ctx;
564
+
565
+ data = llama_perf_context(ctx);
566
+
567
+ const double t_end_ms = 1e-3 * ggml_time_us();
568
+
569
+ const double t_total_ms = t_end_ms - data.t_start_ms;
570
+ const double t_unacc_ms = t_total_ms - (t_sampling_ms + data.t_p_eval_ms + data.t_eval_ms);
571
+ const double t_unacc_pc = 100.0 * t_unacc_ms / t_total_ms;
572
+
573
+ LOG_INF("%s: load time = %10.2f ms\n", __func__, data.t_load_ms);
574
+ LOG_INF("%s: prompt eval time = %10.2f ms / %5d tokens (%8.2f ms per token, %8.2f tokens per second)\n",
575
+ __func__, data.t_p_eval_ms, data.n_p_eval, data.t_p_eval_ms / data.n_p_eval, 1e3 / data.t_p_eval_ms * data.n_p_eval);
576
+ LOG_INF("%s: eval time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
577
+ __func__, data.t_eval_ms, data.n_eval, data.t_eval_ms / data.n_eval, 1e3 / data.t_eval_ms * data.n_eval);
578
+ LOG_INF("%s: total time = %10.2f ms / %5d tokens\n", __func__, (t_end_ms - data.t_start_ms), (data.n_p_eval + data.n_eval));
579
+ LOG_INF("%s: unaccounted time = %10.2f ms / %5.1f %% (total - sampling - prompt eval - eval) / (total)\n", __func__, t_unacc_ms, t_unacc_pc);
580
+ LOG_INF("%s: graphs reused = %10d\n", __func__, data.n_reused);
581
+
582
+ common_memory_breakdown_print(ctx);
583
+ }
584
+ }
585
+
586
+ struct llama_sampler * common_sampler_get(const struct common_sampler * gsmpl) {
587
+ if (!gsmpl) {
588
+ return nullptr;
589
+ }
590
+
591
+ return gsmpl->chain;
592
+ }
593
+
594
+ llama_token common_sampler_sample(struct common_sampler * gsmpl, struct llama_context * ctx, int idx, bool grammar_first) {
595
+ llama_synchronize(ctx);
596
+
597
+ // start measuring sampling time after the llama_context synchronization in order to not measure any ongoing async operations
598
+ const auto tm = gsmpl->tm();
599
+
600
+ llama_token id = LLAMA_TOKEN_NULL;
601
+
602
+ auto & grmr = gsmpl->grmr;
603
+ auto & rbudget = gsmpl->rbudget;
604
+ auto & chain = gsmpl->chain;
605
+ auto & cur_p = gsmpl->cur_p; // initialized by set_logits
606
+
607
+ gsmpl->set_logits(ctx, idx);
608
+
609
+ // Check if a backend sampler has already sampled a token in which case we
610
+ // return that token id directly.
611
+ {
612
+ id = llama_get_sampled_token_ith(ctx, idx);
613
+
614
+ if (id != LLAMA_TOKEN_NULL) {
615
+ LOG_DBG("%s: Backend sampler selected token: '%d'. Will not run any CPU samplers\n", __func__, id);
616
+
617
+ GGML_ASSERT(!gsmpl->grmr && "using grammar in combination with backend sampling is not supported");
618
+ GGML_ASSERT(!gsmpl->rbudget && "using reasoning budget in combination with backend sampling is not supported");
619
+
620
+ for (size_t i = 0; i < cur_p.size; ++i) {
621
+ if (cur_p.data[i].id == id) {
622
+ cur_p.selected = i;
623
+ break;
624
+ }
625
+ }
626
+
627
+ return id;
628
+ }
629
+ }
630
+
631
+ // apply reasoning budget first
632
+ llama_sampler_apply(rbudget, &cur_p);
633
+
634
+ if (grammar_first && grammar_should_apply(gsmpl)) {
635
+ llama_sampler_apply(grmr, &cur_p);
636
+ }
637
+
638
+ llama_sampler_apply(chain, &cur_p);
639
+
640
+ id = cur_p.data[cur_p.selected].id;
641
+
642
+ if (grammar_first || !grammar_should_apply(gsmpl)) {
643
+ return id;
644
+ }
645
+
646
+ // check if it the sampled token fits the grammar (grammar-based rejection sampling)
647
+ {
648
+ llama_token_data single_token_data = { id, 1.0f, 0.0f };
649
+ llama_token_data_array single_token_data_array = { &single_token_data, 1, -1, false };
650
+
651
+ llama_sampler_apply(grmr, &single_token_data_array);
652
+
653
+ const bool is_valid = single_token_data_array.data[0].logit != -INFINITY;
654
+ if (is_valid) {
655
+ return id;
656
+ }
657
+ }
658
+
659
+ // resampling:
660
+ // if the token is not valid, sample again, but first apply the grammar sampler and then the sampling chain
661
+ gsmpl->set_logits(ctx, idx);
662
+
663
+ llama_sampler_apply(rbudget, &cur_p);
664
+
665
+ if (grammar_should_apply(gsmpl)) {
666
+ llama_sampler_apply(grmr, &cur_p);
667
+ }
668
+
669
+ llama_sampler_apply(chain, &cur_p);
670
+
671
+ GGML_ASSERT(cur_p.selected != -1 && "no selected token during sampling - check your sampling configuration");
672
+
673
+ id = cur_p.data[cur_p.selected].id;
674
+
675
+ return id;
676
+ }
677
+
678
+ std::vector<llama_token> common_sampler_sample_and_accept_n(struct common_sampler * gsmpl, struct llama_context * ctx, const std::vector<int> & idxs, const llama_tokens & draft, bool grammar_first) {
679
+ GGML_ASSERT(idxs.size() == draft.size() + 1 && "idxs.size() must be draft.size() + 1");
680
+
681
+ std::vector<llama_token> result;
682
+ result.reserve(idxs.size());
683
+
684
+ size_t i = 0;
685
+ for (; i < draft.size(); i++) {
686
+ const llama_token id = common_sampler_sample(gsmpl, ctx, idxs[i], grammar_first);
687
+
688
+ common_sampler_accept(gsmpl, id, true);
689
+
690
+ result.push_back(id);
691
+
692
+ if (draft[i] != id) {
693
+ break;
694
+ }
695
+ }
696
+
697
+ if (i == draft.size()) {
698
+ const llama_token id = common_sampler_sample(gsmpl, ctx, idxs[i], grammar_first);
699
+
700
+ common_sampler_accept(gsmpl, id, true);
701
+
702
+ result.push_back(id);
703
+ }
704
+
705
+ return result;
706
+ }
707
+
708
+ std::vector<llama_token> common_sampler_sample_and_accept_n(struct common_sampler * gsmpl, struct llama_context * ctx, const llama_tokens & draft, bool grammar_first) {
709
+ std::vector<int> idxs(draft.size() + 1);
710
+ for (size_t i = 0; i < idxs.size(); ++i) {
711
+ idxs[i] = i;
712
+ }
713
+
714
+ return common_sampler_sample_and_accept_n(gsmpl, ctx, idxs, draft, grammar_first);
715
+ }
716
+
717
+ uint32_t common_sampler_get_seed(const struct common_sampler * gsmpl) {
718
+ return llama_sampler_get_seed(gsmpl->chain);
719
+ }
720
+
721
+ bool common_sampler_reasoning_budget_force(struct common_sampler * gsmpl) {
722
+ if (!gsmpl) {
723
+ return false;
724
+ }
725
+
726
+ return common_reasoning_budget_force(gsmpl->rbudget);
727
+ }
728
+
729
+ // helpers
730
+
731
+ llama_token_data_array * common_sampler_get_candidates(struct common_sampler * gsmpl, bool do_sort) {
732
+ const auto tm = gsmpl->tm();
733
+
734
+ auto * res = &gsmpl->cur_p;
735
+
736
+ if (do_sort && !res->sorted) {
737
+ // remember the selected token before sorting
738
+ const llama_token id = res->data[res->selected].id;
739
+
740
+ std::sort(res->data, res->data + res->size, [](const llama_token_data & a, const llama_token_data & b) {
741
+ return a.p > b.p;
742
+ });
743
+
744
+ // restore the selected token after sorting
745
+ for (size_t i = 0; i < res->size; ++i) {
746
+ if (res->data[i].id == id) {
747
+ res->selected = i;
748
+ break;
749
+ }
750
+ }
751
+
752
+ res->sorted = true;
753
+ }
754
+
755
+ return res;
756
+ }
757
+
758
+ llama_token common_sampler_last(const struct common_sampler * gsmpl) {
759
+ return gsmpl->prev.rat(0);
760
+ }
761
+
762
+ std::string common_sampler_print(const struct common_sampler * gsmpl) {
763
+ std::string result = "logits ";
764
+
765
+ for (int i = 0; i < llama_sampler_chain_n(gsmpl->chain); i++) {
766
+ const auto * smpl = llama_sampler_chain_get(gsmpl->chain, i);
767
+ result += std::string("-> ");
768
+ result += std::string(llama_sampler_name(smpl)) + " ";
769
+ }
770
+
771
+ return result;
772
+ }
773
+
774
+ std::string common_sampler_prev_str(common_sampler * gsmpl, llama_context * ctx_main, int n) {
775
+ n = std::min(n, (int) gsmpl->prev.size());
776
+
777
+ if (n <= 0) {
778
+ return "";
779
+ }
780
+
781
+ std::string result;
782
+ result.reserve(8*n); // 8 is the average length of a token [citation needed], TODO: compute this from the vocab
783
+
784
+ for (int i = n - 1; i >= 0; i--) {
785
+ const llama_token id = gsmpl->prev.rat(i);
786
+
787
+ GGML_ASSERT(id != LLAMA_TOKEN_NULL && "null token in the sampling history - should not happen");
788
+
789
+ result += common_token_to_piece(ctx_main, id);
790
+ }
791
+
792
+ return result;
793
+ }
794
+
795
+ char common_sampler_type_to_chr(enum common_sampler_type cnstr) {
796
+ switch (cnstr) {
797
+ case COMMON_SAMPLER_TYPE_DRY: return 'd';
798
+ case COMMON_SAMPLER_TYPE_TOP_K: return 'k';
799
+ case COMMON_SAMPLER_TYPE_TYPICAL_P: return 'y';
800
+ case COMMON_SAMPLER_TYPE_TOP_P: return 'p';
801
+ case COMMON_SAMPLER_TYPE_TOP_N_SIGMA: return 's';
802
+ case COMMON_SAMPLER_TYPE_MIN_P: return 'm';
803
+ case COMMON_SAMPLER_TYPE_TEMPERATURE: return 't';
804
+ case COMMON_SAMPLER_TYPE_XTC: return 'x';
805
+ case COMMON_SAMPLER_TYPE_INFILL: return 'i';
806
+ case COMMON_SAMPLER_TYPE_PENALTIES: return 'e';
807
+ case COMMON_SAMPLER_TYPE_ADAPTIVE_P: return 'a';
808
+ default : return '?';
809
+ }
810
+ }
811
+
812
+ std::string common_sampler_type_to_str(enum common_sampler_type cnstr) {
813
+ switch (cnstr) {
814
+ case COMMON_SAMPLER_TYPE_DRY: return "dry";
815
+ case COMMON_SAMPLER_TYPE_TOP_K: return "top_k";
816
+ case COMMON_SAMPLER_TYPE_TYPICAL_P: return "typ_p";
817
+ case COMMON_SAMPLER_TYPE_TOP_P: return "top_p";
818
+ case COMMON_SAMPLER_TYPE_TOP_N_SIGMA: return "top_n_sigma";
819
+ case COMMON_SAMPLER_TYPE_MIN_P: return "min_p";
820
+ case COMMON_SAMPLER_TYPE_TEMPERATURE: return "temperature";
821
+ case COMMON_SAMPLER_TYPE_XTC: return "xtc";
822
+ case COMMON_SAMPLER_TYPE_INFILL: return "infill";
823
+ case COMMON_SAMPLER_TYPE_PENALTIES: return "penalties";
824
+ case COMMON_SAMPLER_TYPE_ADAPTIVE_P: return "adaptive_p";
825
+ default : return "";
826
+ }
827
+ }
828
+
829
+ std::vector<common_sampler_type> common_sampler_types_from_names(const std::vector<std::string> & names) {
830
+ // sampler names can be written multiple ways; generate aliases from canonical names
831
+ static const auto sampler_name_map = []{
832
+ // canonical sampler name mapping
833
+ std::unordered_map<std::string, common_sampler_type> canonical_name_map {
834
+ { "dry", COMMON_SAMPLER_TYPE_DRY },
835
+ { "top_k", COMMON_SAMPLER_TYPE_TOP_K },
836
+ { "top_p", COMMON_SAMPLER_TYPE_TOP_P },
837
+ { "top_n_sigma", COMMON_SAMPLER_TYPE_TOP_N_SIGMA },
838
+ { "typ_p", COMMON_SAMPLER_TYPE_TYPICAL_P },
839
+ { "min_p", COMMON_SAMPLER_TYPE_MIN_P },
840
+ { "temperature", COMMON_SAMPLER_TYPE_TEMPERATURE },
841
+ { "xtc", COMMON_SAMPLER_TYPE_XTC },
842
+ { "infill", COMMON_SAMPLER_TYPE_INFILL },
843
+ { "penalties", COMMON_SAMPLER_TYPE_PENALTIES },
844
+ { "adaptive_p", COMMON_SAMPLER_TYPE_ADAPTIVE_P }
845
+ };
846
+ std::unordered_map<std::string, common_sampler_type> alias_name_map;
847
+ for (const auto & entry : canonical_name_map) {
848
+ const std::string & canonical = entry.first;
849
+ if (canonical.find('_') == std::string::npos) {
850
+ continue;
851
+ }
852
+ // kebab-case: "top-k", "min-p", etc.
853
+ {
854
+ std::string kebab_case = canonical;
855
+ std::replace(kebab_case.begin(), kebab_case.end(), '_', '-');
856
+ alias_name_map.insert({kebab_case, entry.second});
857
+ }
858
+ // no dash: "topk", "minp", etc.
859
+ {
860
+ std::string no_dash = canonical;
861
+ no_dash.erase(std::remove(no_dash.begin(), no_dash.end(), '_'), no_dash.end());
862
+ alias_name_map.insert({no_dash, entry.second});
863
+ }
864
+ }
865
+ // misc. aliases
866
+ alias_name_map.insert({"nucleus", COMMON_SAMPLER_TYPE_TOP_P});
867
+ alias_name_map.insert({"temp", COMMON_SAMPLER_TYPE_TEMPERATURE});
868
+ alias_name_map.insert({"typ", COMMON_SAMPLER_TYPE_TYPICAL_P});
869
+ // include aliases + canonical names in the complete mapping
870
+ alias_name_map.merge(canonical_name_map);
871
+ return alias_name_map;
872
+ }();
873
+
874
+ std::vector<common_sampler_type> samplers;
875
+ samplers.reserve(names.size());
876
+
877
+ for (const auto & name : names) {
878
+ std::string name_lower = name;
879
+ std::transform(name_lower.begin(), name_lower.end(), name_lower.begin(), ::tolower);
880
+ auto sampler = sampler_name_map.find(name_lower);
881
+ if (sampler != sampler_name_map.end()) {
882
+ samplers.push_back(sampler->second);
883
+ continue;
884
+ }
885
+ LOG_WRN("%s: unable to match sampler by name '%s'\n", __func__, name_lower.c_str());
886
+ }
887
+
888
+ return samplers;
889
+ }
890
+
891
+ std::vector<common_sampler_type> common_sampler_types_from_chars(const std::string & chars) {
892
+ std::unordered_map<char, common_sampler_type> sampler_name_map = {
893
+ { common_sampler_type_to_chr(COMMON_SAMPLER_TYPE_DRY), COMMON_SAMPLER_TYPE_DRY },
894
+ { common_sampler_type_to_chr(COMMON_SAMPLER_TYPE_TOP_K), COMMON_SAMPLER_TYPE_TOP_K },
895
+ { common_sampler_type_to_chr(COMMON_SAMPLER_TYPE_TYPICAL_P), COMMON_SAMPLER_TYPE_TYPICAL_P },
896
+ { common_sampler_type_to_chr(COMMON_SAMPLER_TYPE_TOP_P), COMMON_SAMPLER_TYPE_TOP_P },
897
+ { common_sampler_type_to_chr(COMMON_SAMPLER_TYPE_TOP_N_SIGMA), COMMON_SAMPLER_TYPE_TOP_N_SIGMA },
898
+ { common_sampler_type_to_chr(COMMON_SAMPLER_TYPE_MIN_P), COMMON_SAMPLER_TYPE_MIN_P },
899
+ { common_sampler_type_to_chr(COMMON_SAMPLER_TYPE_TEMPERATURE), COMMON_SAMPLER_TYPE_TEMPERATURE },
900
+ { common_sampler_type_to_chr(COMMON_SAMPLER_TYPE_XTC), COMMON_SAMPLER_TYPE_XTC },
901
+ { common_sampler_type_to_chr(COMMON_SAMPLER_TYPE_INFILL), COMMON_SAMPLER_TYPE_INFILL },
902
+ { common_sampler_type_to_chr(COMMON_SAMPLER_TYPE_PENALTIES), COMMON_SAMPLER_TYPE_PENALTIES },
903
+ { common_sampler_type_to_chr(COMMON_SAMPLER_TYPE_ADAPTIVE_P), COMMON_SAMPLER_TYPE_ADAPTIVE_P },
904
+ };
905
+
906
+ std::vector<common_sampler_type> samplers;
907
+ samplers.reserve(chars.size());
908
+
909
+ for (const auto & c : chars) {
910
+ const auto sampler = sampler_name_map.find(c);
911
+ if (sampler != sampler_name_map.end()) {
912
+ samplers.push_back(sampler->second);
913
+ } else {
914
+ LOG_WRN("%s: unable to match sampler by char '%c'\n", __func__, c);
915
+ }
916
+ }
917
+
918
+ return samplers;
919
+ }
common/sampling.h ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include "llama.h"
4
+
5
+ #include "common.h"
6
+
7
+ #include <string>
8
+ #include <vector>
9
+
10
+ // common_sampler extends llama_sampler with additional functionality:
11
+ //
12
+ // - grammar support
13
+ // - custom sampler logic based on the parameters
14
+ // - history of the last accepted tokens
15
+ // - performance metrics
16
+ //
17
+ // This goal is to have a common implementation of the sampling logic shared across the examples.
18
+ // For example, depending on the temperature, the sampling chain can be very simple (greedy) or more
19
+ // complex (top-k, top-p, etc).
20
+ //
21
+ // Another example is related to the grammar. In general, the grammar constraints applied on the full
22
+ // vocabulary can be very taxing. To improve performance, the grammar can be applied only to the sampled
23
+ // token in order to verify if it fits the grammar. And only if the token doesn't fit the grammar, the
24
+ // grammar constraints are applied to the full vocabulary and the token is resampled.
25
+ //
26
+ // The common_sampler also maintains a container with the last accepted tokens. In the future, this can
27
+ // be moved into the core llama library.
28
+ //
29
+ // For convenience, the common_sampler also maintains a container with the current candidate tokens.
30
+ // This can be used to access the probabilities of the rest of the non-sampled tokens.
31
+ //
32
+ // TODO: measure grammar performance
33
+ //
34
+
35
+ struct common_sampler;
36
+
37
+ // llama_sampler API overloads
38
+
39
+ // note: can mutate params in some cases
40
+ struct common_sampler * common_sampler_init(
41
+ const struct llama_model * model,
42
+ struct common_params_sampling & params);
43
+
44
+ void common_sampler_free(struct common_sampler * gsmpl);
45
+
46
+ // if is_generated is true, the token is accepted by the sampling chain, the reasoning budget sampler, and the grammar sampler
47
+ void common_sampler_accept(struct common_sampler * gsmpl, llama_token token, bool is_generated);
48
+ void common_sampler_reset (struct common_sampler * gsmpl);
49
+ struct common_sampler * common_sampler_clone (struct common_sampler * gsmpl);
50
+ void common_sampler_copy (const struct common_sampler * src, struct common_sampler * dst);
51
+
52
+ // arguments can be nullptr to skip printing
53
+ void common_perf_print(const struct llama_context * ctx, const struct common_sampler * gsmpl);
54
+
55
+ // get the underlying llama_sampler_chain
56
+ struct llama_sampler * common_sampler_get(const struct common_sampler * gsmpl);
57
+
58
+ // extended sampling implementation:
59
+ //
60
+ // - set logits
61
+ // - apply the configured sampler chain
62
+ // - check if the token fits the grammar (if any)
63
+ // - if not: resample by first applying the grammar constraints and then sampling again (slower path)
64
+ //
65
+ // if grammar_first is true, the grammar is applied before the samplers (slower)
66
+ // useful in cases where all the resulting candidates (not just the sampled one) must fit the grammar
67
+ //
68
+ llama_token common_sampler_sample(struct common_sampler * gsmpl, struct llama_context * ctx, int idx, bool grammar_first = false);
69
+
70
+ // generalized version of common_sampler_sample
71
+ //
72
+ // will cross-reference the sampled tokens with a batch of draft tokens and accept those that match
73
+ // if the sampler disagrees at some point, we stop and return the accepted tokens up to now
74
+ //
75
+ // common_sampler_sample_n(gsmpl, ctx, { idx }, {});
76
+ //
77
+ // is equivalent to
78
+ //
79
+ // common_sampler_sample(gsmpl, ctx, idx);
80
+ // common_sampler_accept(gsmpl, token, true);
81
+ //
82
+ // requires: idxs.size() == draft.size() + 1
83
+ //
84
+ // returns at least 1 token, up to idxs.size()
85
+ //
86
+ std::vector<llama_token> common_sampler_sample_and_accept_n(struct common_sampler * gsmpl, struct llama_context * ctx, const std::vector<int> & idxs, const llama_tokens & draft, bool grammar_first = false);
87
+
88
+ // assume idxs == [ 0, 1, 2, ..., draft.size() ]
89
+ std::vector<llama_token> common_sampler_sample_and_accept_n(struct common_sampler * gsmpl, struct llama_context * ctx, const llama_tokens & draft, bool grammar_first = false);
90
+
91
+ uint32_t common_sampler_get_seed(const struct common_sampler * gsmpl);
92
+
93
+ // force the reasoning budget sampler (if any) to begin forcing its end sequence now.
94
+ bool common_sampler_reasoning_budget_force(struct common_sampler * gsmpl);
95
+
96
+ // helpers
97
+
98
+ // access the internal list of current candidate tokens
99
+ // if do_sort == true, the candidates are guaranteed to be sorted afterwards (in descending order of probability)
100
+ // the .sorted flag of the result indicates whether the returned candidates are sorted
101
+ llama_token_data_array * common_sampler_get_candidates(struct common_sampler * gsmpl, bool do_sort);
102
+
103
+ // get the last accepted token
104
+ llama_token common_sampler_last(const struct common_sampler * gsmpl);
105
+
106
+ // print the sampler chain into a string
107
+ std::string common_sampler_print(const struct common_sampler * gsmpl);
108
+
109
+ // get a string representation of the last accepted tokens
110
+ std::string common_sampler_prev_str(common_sampler * gsmpl, llama_context * ctx, int n);
111
+
112
+ char common_sampler_type_to_chr(enum common_sampler_type cnstr);
113
+ std::string common_sampler_type_to_str(enum common_sampler_type cnstr);
114
+
115
+ std::vector<enum common_sampler_type> common_sampler_types_from_names(const std::vector<std::string> & names);
116
+ std::vector<enum common_sampler_type> common_sampler_types_from_chars(const std::string & chars);
117
+
118
+ llama_sampler * llama_sampler_init_llg(const llama_vocab * vocab,
119
+ const char * grammar_kind, const char * grammar_data);
120
+
121
+ struct common_sampler_deleter {
122
+ void operator()(common_sampler * s) { common_sampler_free(s); }
123
+ };
124
+
125
+ typedef std::unique_ptr<common_sampler, common_sampler_deleter> common_sampler_ptr;
common/speculative.cpp ADDED
The diff for this file is too large to render. See raw diff
 
common/speculative.h ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include "llama.h"
4
+ #include "common.h"
5
+
6
+ struct common_speculative;
7
+
8
+ // comma separated list the provided types
9
+ std::string common_speculative_type_name_str(const std::vector<enum common_speculative_type> & types);
10
+
11
+ // comma separated list of all types
12
+ const char * common_speculative_all_types_str();
13
+
14
+ // parse user provided types
15
+ std::vector<enum common_speculative_type> common_speculative_types_from_names(const std::vector<std::string> & names);
16
+
17
+ // infer the spec types from the GGUF metadata of a draft model; empty if unknown
18
+ std::vector<enum common_speculative_type> common_speculative_types_from_gguf(const std::string & path);
19
+
20
+ // convert string to type
21
+ enum common_speculative_type common_speculative_type_from_name(const std::string & name);
22
+
23
+ // convert type to string
24
+ std::string common_speculative_type_to_str(enum common_speculative_type type);
25
+
26
+ // return the max number of draft tokens based on the speculative parameters
27
+ int32_t common_speculative_n_max(const common_params_speculative * spec);
28
+
29
+ // return the max number of draft tokens from the initialized implementations
30
+ int32_t common_speculative_n_max(const common_speculative * spec);
31
+
32
+ // validate and resolve the unconditional synthetic acceptance rates
33
+ std::vector<double> common_speculative_synth_rates_resolve(const common_params_speculative * spec, int32_t n_max);
34
+
35
+ // return the conditional synthetic acceptance probabilities
36
+ const std::vector<double> & common_speculative_get_synth_probs(const common_speculative * spec);
37
+
38
+ common_params common_base_params_to_speculative(const common_params & params);
39
+
40
+ struct common_speculative_output_limits {
41
+ int32_t total;
42
+ int32_t per_seq;
43
+ };
44
+
45
+ // return the output limits needed for speculative decoding
46
+ common_speculative_output_limits common_speculative_get_output_limits(
47
+ int32_t n_batch, int32_t n_parallel, int32_t n_draft);
48
+
49
+ common_speculative * common_speculative_init(common_params_speculative & params, uint32_t n_seq);
50
+
51
+ void common_speculative_free(common_speculative * spec);
52
+
53
+ struct common_speculative_draft_params {
54
+ // this flag is used to chain the drafts through all the available implementations
55
+ // after the first successful draft from an implementation, we set it
56
+ // to false to prevent further drafts for that sequence
57
+ // at the end of the draft() call, all drafting flags will be reset to false
58
+ bool drafting = false;
59
+
60
+ // overrides individual configurations (-1 disabled)
61
+ // can be used to constraint the max draft based on the remaining context size
62
+ int32_t n_max = -1;
63
+
64
+ llama_pos pos0;
65
+ llama_token id_last;
66
+
67
+ // TODO: remove in the future by keeping track of the prompt from the _begin() call and the consecutive accept calls
68
+ const llama_tokens * prompt;
69
+
70
+ // the generated draft from the last _draft() call
71
+ llama_tokens * result;
72
+ };
73
+
74
+ common_speculative_draft_params & common_speculative_get_draft_params(common_speculative * spec, llama_seq_id seq_id);
75
+
76
+ // optionally call once at the beginning of a new generation
77
+ void common_speculative_begin(common_speculative * spec, llama_seq_id seq_id, const llama_tokens & prompt);
78
+
79
+ // process the batch and update the internal state of the speculative context
80
+ bool common_speculative_process(common_speculative * spec, const llama_batch & batch);
81
+
82
+ // generate drafts for the sequences specified with `common_speculative_get_draft_params`
83
+ void common_speculative_draft(common_speculative * spec);
84
+
85
+ // informs the speculative context that n_accepted tokens were accepted by the target model
86
+ void common_speculative_accept(common_speculative * spec, llama_seq_id, uint16_t n_accepted);
87
+
88
+ // (optional) get/set internal state
89
+ bool common_speculative_get_state(common_speculative * spec, llama_seq_id seq_id, std::vector<uint8_t> & data);
90
+ void common_speculative_set_state(common_speculative * spec, llama_seq_id seq_id, const std::vector<uint8_t> & data);
91
+
92
+ // print statistics about the speculative decoding
93
+ void common_speculative_print_stats(const common_speculative * spec);
94
+
95
+ struct common_speculative_deleter {
96
+ void operator()(common_speculative * s) { common_speculative_free(s); }
97
+ };
98
+
99
+ typedef std::unique_ptr<common_speculative, common_speculative_deleter> common_speculative_ptr;
100
+
101
+ struct common_speculative_init_result {
102
+ common_speculative_init_result(common_params & params, llama_model * model_tgt, llama_context * ctx_tgt);
103
+ ~common_speculative_init_result();
104
+
105
+ llama_model * model();
106
+ llama_context * context();
107
+
108
+ private:
109
+ struct impl;
110
+ std::unique_ptr<impl> pimpl;
111
+ };
112
+
113
+ using common_speculative_init_result_ptr = std::unique_ptr<common_speculative_init_result>;
114
+
115
+ common_speculative_init_result_ptr common_speculative_init_from_params(common_params & params, llama_model * model_tgt, llama_context * ctx_tgt);
common/subproc.cpp ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "subproc.h"
2
+
3
+ bool common_subproc::is_supported() {
4
+ #ifdef LLAMA_SUBPROCESS
5
+ return true;
6
+ #else
7
+ return false;
8
+ #endif
9
+ }
10
+
11
+ #ifdef LLAMA_SUBPROCESS
12
+
13
+ static std::vector<char *> to_cstr_vec(const std::vector<std::string> & v) {
14
+ std::vector<char *> r;
15
+ r.reserve(v.size() + 1);
16
+ for (const auto & s : v) {
17
+ r.push_back(const_cast<char *>(s.c_str()));
18
+ }
19
+ r.push_back(nullptr);
20
+ return r;
21
+ }
22
+
23
+ common_subproc::~common_subproc() {
24
+ if (is_created) {
25
+ subprocess_destroy(&proc);
26
+ is_created = false;
27
+ }
28
+ }
29
+
30
+ bool common_subproc::create(
31
+ const std::vector<std::string> & args,
32
+ int options,
33
+ const std::vector<std::string> & env,
34
+ const char * cwd) {
35
+ auto argv = to_cstr_vec(args);
36
+
37
+ int result;
38
+ if (env.empty() && cwd == nullptr) {
39
+ result = subprocess_create(argv.data(), options, &proc);
40
+ } else {
41
+ auto envp = to_cstr_vec(env);
42
+ result = subprocess_create_ex(argv.data(), options, env.empty() ? nullptr : envp.data(), cwd, &proc);
43
+ }
44
+
45
+ is_created = result == 0;
46
+ return is_created;
47
+ }
48
+
49
+ bool common_subproc::has_handle() const {
50
+ if (!is_created) {
51
+ return false;
52
+ }
53
+ #if defined(_WIN32)
54
+ return proc.hProcess != nullptr;
55
+ #else
56
+ return proc.child > 0;
57
+ #endif
58
+ }
59
+
60
+ bool common_subproc::alive() {
61
+ return is_created && subprocess_alive(&proc);
62
+ }
63
+
64
+ FILE * common_subproc::stdin_file() {
65
+ return is_created ? subprocess_stdin(&proc) : nullptr;
66
+ }
67
+
68
+ FILE * common_subproc::stdout_file() {
69
+ return is_created ? subprocess_stdout(&proc) : nullptr;
70
+ }
71
+
72
+ FILE * common_subproc::stderr_file() {
73
+ return is_created ? subprocess_stderr(&proc) : nullptr;
74
+ }
75
+
76
+ void common_subproc::close_stdin() {
77
+ if (is_created && proc.stdin_file) {
78
+ fclose(proc.stdin_file);
79
+ proc.stdin_file = nullptr;
80
+ }
81
+ }
82
+
83
+ void common_subproc::terminate() {
84
+ if (has_handle()) {
85
+ subprocess_terminate(&proc);
86
+ }
87
+ }
88
+
89
+ int common_subproc::join() {
90
+ int exit_code = -1;
91
+ if (is_created) {
92
+ subprocess_join(&proc, &exit_code);
93
+ subprocess_destroy(&proc);
94
+ is_created = false;
95
+ }
96
+ return exit_code;
97
+ }
98
+
99
+ #else // !LLAMA_SUBPROCESS
100
+
101
+ common_subproc::~common_subproc() = default;
102
+
103
+ bool common_subproc::create(
104
+ const std::vector<std::string> &,
105
+ int,
106
+ const std::vector<std::string> &,
107
+ const char *) {
108
+ (void)(proc);
109
+ (void)(is_created);
110
+ return false;
111
+ }
112
+
113
+ bool common_subproc::has_handle() const {
114
+ return false;
115
+ }
116
+
117
+ bool common_subproc::alive() {
118
+ return false;
119
+ }
120
+
121
+ FILE * common_subproc::stdin_file() {
122
+ return nullptr;
123
+ }
124
+
125
+ FILE * common_subproc::stdout_file() {
126
+ return nullptr;
127
+ }
128
+
129
+ FILE * common_subproc::stderr_file() {
130
+ return nullptr;
131
+ }
132
+
133
+ void common_subproc::close_stdin() {
134
+ }
135
+
136
+ void common_subproc::terminate() {
137
+ }
138
+
139
+ int common_subproc::join() {
140
+ return -1;
141
+ }
142
+
143
+ #endif // LLAMA_SUBPROCESS
common/subproc.h ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <atomic>
4
+ #include <cstdio>
5
+ #include <string>
6
+ #include <vector>
7
+
8
+ #ifdef LLAMA_SUBPROCESS
9
+ #include <sheredom/subprocess.h>
10
+ #else
11
+ // dummy values to allow compilation when subprocess is disabled
12
+ struct subprocess_s {};
13
+ static constexpr int subprocess_option_no_window = 0;
14
+ static constexpr int subprocess_option_combined_stdout_stderr = 0;
15
+ static constexpr int subprocess_option_inherit_environment = 0;
16
+ static constexpr int subprocess_option_search_user_path = 0;
17
+ #endif
18
+
19
+ // RAII-style wrapper around https://github.com/sheredom/subprocess.h,
20
+ // exposing method calls instead of free functions operating on subprocess_s.
21
+ struct common_subproc {
22
+ common_subproc() = default;
23
+ ~common_subproc();
24
+
25
+ common_subproc(const common_subproc &) = delete;
26
+ common_subproc & operator=(const common_subproc &) = delete;
27
+
28
+ // spawn a child process; if env is non-empty it replaces the child's environment
29
+ // (do not combine with subprocess_option_inherit_environment)
30
+ bool create(
31
+ const std::vector<std::string> & args,
32
+ int options,
33
+ const std::vector<std::string> & env = {},
34
+ const char * cwd = nullptr);
35
+
36
+ bool alive();
37
+
38
+ // true if LLAMA_SUBPROCESS was enabled at build time; when false, create() always fails
39
+ static bool is_supported();
40
+
41
+ FILE * stdin_file();
42
+ FILE * stdout_file();
43
+ FILE * stderr_file();
44
+
45
+ // close stdin and detach it from the process, so a later join()/destroy() won't double-close it;
46
+ // use this after writing all input to signal EOF to the child while it's still running
47
+ void close_stdin();
48
+
49
+ void terminate();
50
+
51
+ // wait for the process to exit, release the underlying handle and return its exit code
52
+ int join();
53
+
54
+ private:
55
+ subprocess_s proc {};
56
+ std::atomic<bool> is_created{false};
57
+
58
+ bool has_handle() const;
59
+ };
common/trie.cpp ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "trie.h"
2
+
3
+ #include "unicode.h"
4
+
5
+ #include <deque>
6
+
7
+ common_trie::match_result common_trie::check_at(std::string_view sv, size_t start_pos) const {
8
+ size_t current = 0; // Start at root
9
+ size_t pos = start_pos;
10
+
11
+ // LOG_DBG("%s: checking at pos %zu, sv='%s'\n", __func__, start_pos, std::string(sv).c_str());
12
+
13
+ while (pos < sv.size()) {
14
+ auto result = common_parse_utf8_codepoint(sv, pos);
15
+ if (result.status != utf8_parse_result::SUCCESS) {
16
+ break;
17
+ }
18
+
19
+ auto it = nodes[current].children.find(result.codepoint);
20
+ if (it == nodes[current].children.end()) {
21
+ // Can't continue matching
22
+ return match_result{match_result::NO_MATCH};
23
+ }
24
+
25
+ current = it->second;
26
+ pos += result.bytes_consumed;
27
+
28
+ // Check if we've matched a complete word
29
+ if (nodes[current].pattern >= 0) {
30
+ return match_result{match_result::COMPLETE_MATCH};
31
+ }
32
+ }
33
+
34
+ // Reached end of input while still in the trie (not at root)
35
+ if (current != 0) {
36
+ // We're in the middle of a potential match
37
+ return match_result{match_result::PARTIAL_MATCH};
38
+ }
39
+
40
+ // Reached end at root (no match)
41
+ return match_result{match_result::NO_MATCH};
42
+ }
43
+
44
+ int32_t common_trie::insert(const std::string & word) {
45
+ std::vector<uint32_t> symbols;
46
+ size_t pos = 0;
47
+ while (pos < word.length()) {
48
+ auto result = common_parse_utf8_codepoint(word, pos);
49
+ if (result.status != utf8_parse_result::SUCCESS) {
50
+ break;
51
+ }
52
+
53
+ symbols.push_back(result.codepoint);
54
+ pos += result.bytes_consumed;
55
+ }
56
+ return insert(symbols);
57
+ }
58
+
59
+ int32_t common_trie::insert(const std::vector<uint32_t> & symbols) {
60
+ size_t current = 0;
61
+ for (uint32_t ch : symbols) {
62
+ auto it = nodes[current].children.find(ch);
63
+ if (it == nodes[current].children.end()) {
64
+ size_t child = create_node();
65
+ nodes[current].children[ch] = child;
66
+ current = child;
67
+ } else {
68
+ current = it->second;
69
+ }
70
+ }
71
+ if (nodes[current].pattern < 0) {
72
+ nodes[current].pattern = n_patterns++;
73
+ }
74
+ return nodes[current].pattern;
75
+ }
76
+
77
+ common_aho_corasick::common_aho_corasick(common_trie trie) : t(std::move(trie)) {
78
+ const auto & nodes = t.nodes;
79
+ const size_t n = nodes.size();
80
+
81
+ fail.assign(n, 0);
82
+ order.reserve(n);
83
+
84
+ std::deque<size_t> queue{ 0 };
85
+ while (!queue.empty()) {
86
+ size_t u = queue.front();
87
+ queue.pop_front();
88
+ order.push_back(u);
89
+ for (const auto & [ch, v] : nodes[u].children) {
90
+ if (u != 0) {
91
+ size_t f = fail[u];
92
+ while (f && nodes[f].children.find(ch) == nodes[f].children.end()) {
93
+ f = fail[f];
94
+ }
95
+ auto it = nodes[f].children.find(ch);
96
+ fail[v] = (it != nodes[f].children.end() && it->second != v) ? it->second : 0;
97
+ }
98
+ queue.push_back(v);
99
+ }
100
+ }
101
+
102
+ // fail[u] points to a strictly shorter suffix, so the first pattern found on
103
+ // the fail chain (including u itself) is the longest pattern ending at u
104
+ match.assign(n, -1);
105
+ for (size_t u : order) {
106
+ match[u] = nodes[u].pattern >= 0 ? nodes[u].pattern : (u != 0 ? match[fail[u]] : -1);
107
+ }
108
+
109
+ for (const auto & node : nodes) {
110
+ for (const auto & [ch, v] : node.children) {
111
+ alphabet.insert(ch);
112
+ }
113
+ }
114
+ }
115
+
116
+ size_t common_aho_corasick::next(size_t state, uint32_t ch) const {
117
+ const auto & nodes = t.nodes;
118
+ while (state && nodes[state].children.find(ch) == nodes[state].children.end()) {
119
+ state = fail[state];
120
+ }
121
+ auto it = nodes[state].children.find(ch);
122
+ return it != nodes[state].children.end() ? it->second : 0;
123
+ }
common/trie.h ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <cstdint>
4
+ #include <map>
5
+ #include <set>
6
+ #include <string>
7
+ #include <string_view>
8
+ #include <vector>
9
+
10
+ // Trie for matching multiple literals.
11
+ // This is used in common_peg_until_parser and to build a GBNF exclusion grammar
12
+ struct common_trie {
13
+ struct node {
14
+ std::map<uint32_t, size_t> children; // Use uint32_t to store Unicode codepoints
15
+ int32_t pattern = -1; // index of the pattern ending at this node, -1 if none
16
+ };
17
+
18
+ std::vector<node> nodes;
19
+
20
+ common_trie() {
21
+ create_node(); // root node
22
+ }
23
+
24
+ common_trie(const std::vector<std::string> & words) : common_trie() {
25
+ for (const auto & w : words) {
26
+ insert(w);
27
+ }
28
+ }
29
+
30
+ enum match_result { NO_MATCH, PARTIAL_MATCH, COMPLETE_MATCH };
31
+
32
+ // Check if a delimiter starts at the given position
33
+ match_result check_at(std::string_view sv, size_t start_pos) const;
34
+
35
+ // Insert a word as a sequence of Unicode codepoints, returns its pattern index
36
+ int32_t insert(const std::string & word);
37
+
38
+ // Insert a raw symbol sequence, returns its pattern index (insertion order,
39
+ // duplicates keep the first index)
40
+ int32_t insert(const std::vector<uint32_t> & symbols);
41
+
42
+ private:
43
+ int32_t n_patterns = 0;
44
+
45
+ size_t create_node() {
46
+ size_t index = nodes.size();
47
+ nodes.emplace_back();
48
+ return index;
49
+ }
50
+ };
51
+
52
+ // Aho-Corasick automaton
53
+ struct common_aho_corasick {
54
+ common_trie t;
55
+ std::vector<size_t> fail; // failure links
56
+ std::vector<size_t> order; // states in BFS order
57
+ std::vector<int32_t> match; // longest pattern ending at each state (directly or via a suffix link), -1 if none
58
+ std::set<uint32_t> alphabet; // every character with a transition
59
+
60
+ common_aho_corasick(common_trie trie);
61
+
62
+ common_aho_corasick(const std::vector<std::string> & strings)
63
+ : common_aho_corasick(common_trie(strings)) {}
64
+
65
+ size_t num_states() const { return t.nodes.size(); }
66
+ bool is_terminal(size_t s) const { return match[s] >= 0; }
67
+
68
+ // index of the longest pattern ending at this state, -1 if none
69
+ int32_t match_pattern(size_t s) const { return match[s]; }
70
+
71
+ // follow failure links until a transition on `ch` exists.
72
+ size_t next(size_t state, uint32_t ch) const;
73
+ };
common/unicode.cpp ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "unicode.h"
2
+
3
+ #include <algorithm>
4
+ #include <cassert>
5
+ #include <stdexcept>
6
+ #include <string>
7
+ #include <vector>
8
+
9
+ // implementation adopted from src/unicode.cpp
10
+
11
+ size_t common_utf8_sequence_length(unsigned char first_byte) {
12
+ const size_t lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 3, 4 };
13
+ uint8_t highbits = static_cast<uint8_t>(first_byte) >> 4;
14
+ return lookup[highbits];
15
+ }
16
+
17
+ utf8_parse_result common_parse_utf8_codepoint(std::string_view input, size_t offset) {
18
+ if (offset >= input.size()) {
19
+ return utf8_parse_result(utf8_parse_result::INCOMPLETE);
20
+ }
21
+
22
+ // ASCII fast path
23
+ if (!(input[offset] & 0x80)) {
24
+ return utf8_parse_result(utf8_parse_result::SUCCESS, input[offset], 1);
25
+ }
26
+
27
+ // Invalid: continuation byte as first byte
28
+ if (!(input[offset] & 0x40)) {
29
+ return utf8_parse_result(utf8_parse_result::INVALID);
30
+ }
31
+
32
+ // 2-byte sequence
33
+ if (!(input[offset] & 0x20)) {
34
+ if (offset + 1 >= input.size()) {
35
+ return utf8_parse_result(utf8_parse_result::INCOMPLETE);
36
+ }
37
+ if ((input[offset + 1] & 0xc0) != 0x80) {
38
+ return utf8_parse_result(utf8_parse_result::INVALID);
39
+ }
40
+ auto result = ((input[offset] & 0x1f) << 6) | (input[offset + 1] & 0x3f);
41
+ return utf8_parse_result(utf8_parse_result::SUCCESS, result, 2);
42
+ }
43
+
44
+ // 3-byte sequence
45
+ if (!(input[offset] & 0x10)) {
46
+ if (offset + 2 >= input.size()) {
47
+ return utf8_parse_result(utf8_parse_result::INCOMPLETE);
48
+ }
49
+ if ((input[offset + 1] & 0xc0) != 0x80 || (input[offset + 2] & 0xc0) != 0x80) {
50
+ return utf8_parse_result(utf8_parse_result::INVALID);
51
+ }
52
+ auto result = ((input[offset] & 0x0f) << 12) | ((input[offset + 1] & 0x3f) << 6) | (input[offset + 2] & 0x3f);
53
+ return utf8_parse_result(utf8_parse_result::SUCCESS, result, 3);
54
+ }
55
+
56
+ // 4-byte sequence
57
+ if (!(input[offset] & 0x08)) {
58
+ if (offset + 3 >= input.size()) {
59
+ return utf8_parse_result(utf8_parse_result::INCOMPLETE);
60
+ }
61
+ if ((input[offset + 1] & 0xc0) != 0x80 || (input[offset + 2] & 0xc0) != 0x80 || (input[offset + 3] & 0xc0) != 0x80) {
62
+ return utf8_parse_result(utf8_parse_result::INVALID);
63
+ }
64
+ auto result = ((input[offset] & 0x07) << 18) | ((input[offset + 1] & 0x3f) << 12) | ((input[offset + 2] & 0x3f) << 6) | (input[offset + 3] & 0x3f);
65
+ return utf8_parse_result(utf8_parse_result::SUCCESS, result, 4);
66
+ }
67
+
68
+ // Invalid first byte
69
+ return utf8_parse_result(utf8_parse_result::INVALID);
70
+ }
71
+
72
+ bool common_utf8_is_complete(const std::string & s) {
73
+ if (s.empty()) {
74
+ return true;
75
+ }
76
+ for (int i = 1; i <= std::min(4, (int)s.size()); i++) {
77
+ unsigned char c = s[s.size() - i];
78
+ if ((c & 0xC0) != 0x80) {
79
+ int expected = (c >= 0xF0) ? 4 : (c >= 0xE0) ? 3 : (c >= 0xC0) ? 2 : 1;
80
+ return i >= expected;
81
+ }
82
+ }
83
+ return false;
84
+ }
85
+
86
+ std::string common_unicode_cpts_to_utf8(const std::vector<uint32_t> & cps) {
87
+ std::string result;
88
+ for (size_t i = 0; i < cps.size(); ++i) {
89
+ result.append(common_unicode_cpt_to_utf8(cps[i]));
90
+ }
91
+ return result;
92
+ }
93
+
94
+ std::string common_unicode_cpt_to_utf8(uint32_t cpt) {
95
+ std::string result;
96
+
97
+ if (/* 0x00 <= cpt && */ cpt <= 0x7f) {
98
+ result.push_back(cpt);
99
+ return result;
100
+ }
101
+ if (0x80 <= cpt && cpt <= 0x7ff) {
102
+ result.push_back(0xc0 | ((cpt >> 6) & 0x1f));
103
+ result.push_back(0x80 | (cpt & 0x3f));
104
+ return result;
105
+ }
106
+ if (0x800 <= cpt && cpt <= 0xffff) {
107
+ result.push_back(0xe0 | ((cpt >> 12) & 0x0f));
108
+ result.push_back(0x80 | ((cpt >> 6) & 0x3f));
109
+ result.push_back(0x80 | (cpt & 0x3f));
110
+ return result;
111
+ }
112
+ if (0x10000 <= cpt && cpt <= 0x10ffff) {
113
+ result.push_back(0xf0 | ((cpt >> 18) & 0x07));
114
+ result.push_back(0x80 | ((cpt >> 12) & 0x3f));
115
+ result.push_back(0x80 | ((cpt >> 6) & 0x3f));
116
+ result.push_back(0x80 | (cpt & 0x3f));
117
+ return result;
118
+ }
119
+
120
+ throw std::invalid_argument("invalid codepoint");
121
+ }
122
+
123
+
124
+
common/unicode.h ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <cstdint>
4
+ #include <string_view>
5
+ #include <vector>
6
+ #include <string>
7
+
8
+ // UTF-8 parsing utilities for streaming-aware unicode support
9
+
10
+ struct utf8_parse_result {
11
+ uint32_t codepoint; // Decoded codepoint (only valid if status == SUCCESS)
12
+ size_t bytes_consumed; // How many bytes this codepoint uses (1-4)
13
+ enum status { SUCCESS, INCOMPLETE, INVALID } status;
14
+
15
+ utf8_parse_result(enum status s, uint32_t cp = 0, size_t bytes = 0)
16
+ : codepoint(cp), bytes_consumed(bytes), status(s) {}
17
+ };
18
+
19
+ // Determine the expected length of a UTF-8 sequence from its first byte
20
+ // Returns 0 for invalid first bytes
21
+ size_t common_utf8_sequence_length(unsigned char first_byte);
22
+
23
+ // Check if a string ends with a complete UTF-8 sequence.
24
+ bool common_utf8_is_complete(const std::string & s);
25
+
26
+ // Parse a single UTF-8 codepoint from input
27
+ utf8_parse_result common_parse_utf8_codepoint(std::string_view input, size_t offset);
28
+
29
+ std::string common_unicode_cpts_to_utf8(const std::vector<uint32_t> & cps);
30
+ std::string common_unicode_cpt_to_utf8(uint32_t cpt);
conversion/__init__.py ADDED
@@ -0,0 +1,404 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from .base import (
4
+ ModelBase, TextModel, MmprojModel, ModelType, SentencePieceTokenTypes,
5
+ logger, _mistral_common_installed, _mistral_import_error_msg,
6
+ get_model_architecture, LazyTorchTensor,
7
+ )
8
+ from typing import Type
9
+
10
+
11
+ __all__ = [
12
+ "ModelBase", "TextModel", "MmprojModel", "ModelType", "SentencePieceTokenTypes",
13
+ "get_model_architecture", "LazyTorchTensor", "logger",
14
+ "_mistral_common_installed", "_mistral_import_error_msg",
15
+ "get_model_class", "print_registered_models", "load_all_models",
16
+ ]
17
+
18
+
19
+ TEXT_MODEL_MAP: dict[str, str] = {
20
+ "AfmoeForCausalLM": "afmoe",
21
+ "LagunaForCausalLM": "laguna",
22
+ "ApertusForCausalLM": "llama",
23
+ "ArceeForCausalLM": "llama",
24
+ "ArcticForCausalLM": "arctic",
25
+ "AudioFlamingo3ForConditionalGeneration": "qwen",
26
+ "BaiChuanForCausalLM": "baichuan",
27
+ "BaichuanForCausalLM": "baichuan",
28
+ "BailingMoeForCausalLM": "bailingmoe",
29
+ "BailingMoeV2ForCausalLM": "bailingmoe",
30
+ "BailingMoeV3ForCausalLM": "bailingmoe3",
31
+ "BambaForCausalLM": "granite",
32
+ "BertForMaskedLM": "bert",
33
+ "BertForSequenceClassification": "bert",
34
+ "BertModel": "bert",
35
+ "BitnetForCausalLM": "bitnet",
36
+ "BitNetForCausalLM": "bitnet",
37
+ "BloomForCausalLM": "bloom",
38
+ "BloomModel": "bloom",
39
+ "CamembertModel": "bert",
40
+ "ChameleonForCausalLM": "chameleon",
41
+ "ChameleonForConditionalGeneration": "chameleon",
42
+ "ChatGLMForConditionalGeneration": "chatglm",
43
+ "ChatGLMModel": "chatglm",
44
+ "CodeShellForCausalLM": "codeshell",
45
+ "CogVLMForCausalLM": "cogvlm",
46
+ "Cohere2MoeForCausalLM": "command_r",
47
+ "Cohere2ForCausalLM": "command_r",
48
+ "CohereForCausalLM": "command_r",
49
+ "DbrxForCausalLM": "dbrx",
50
+ "DeciLMForCausalLM": "deci",
51
+ "DeepseekForCausalLM": "deepseek",
52
+ "DeepseekOCRForCausalLM": "deepseek",
53
+ "DeepseekV2ForCausalLM": "deepseek",
54
+ "DeepseekV3ForCausalLM": "deepseek",
55
+ "DeepseekV32ForCausalLM": "deepseek",
56
+ "DFlashDraftModel": "qwen",
57
+ "DFlash2DraftModel": "qwen",
58
+ "Qwen3DSparkModel": "qwen",
59
+ "DSparkDraftModel": "qwen",
60
+ "DSparkSpeculator": "qwen",
61
+ "Lfm2DSparkDraftModel": "qwen",
62
+ "LingDSparkModel": "qwen",
63
+ "DeepseekV4ForCausalLM": "deepseek",
64
+ "DeepseekV4DSparkModel": "deepseek",
65
+ "DistilBertForMaskedLM": "bert",
66
+ "DistilBertForSequenceClassification": "bert",
67
+ "DistilBertModel": "bert",
68
+ "Dots1ForCausalLM": "dots1",
69
+ "Dots3NoteForCausalLM": "dots3",
70
+ "Dots3NoteForConditionalGeneration": "dots3",
71
+ "Dots3NoteTextForCausalLM": "dots3",
72
+ "DotsOCRForCausalLM": "qwen",
73
+ "DreamModel": "dream",
74
+ "Ernie4_5ForCausalLM": "ernie",
75
+ "Ernie4_5_ForCausalLM": "ernie",
76
+ "Ernie4_5_MoeForCausalLM": "ernie",
77
+ "EuroBertModel": "bert",
78
+ "Exaone4_5_ForConditionalGeneration": "exaone",
79
+ "Exaone4ForCausalLM": "exaone",
80
+ "ExaoneForCausalLM": "exaone",
81
+ "ExaoneMoEForCausalLM": "exaone",
82
+ "ExaoneMoeForCausalLM": "exaone",
83
+ "FalconForCausalLM": "falcon",
84
+ "FalconH1ForCausalLM": "falcon_h1",
85
+ "FalconMambaForCausalLM": "mamba",
86
+ "GPT2LMHeadModel": "gpt2",
87
+ "GPTBigCodeForCausalLM": "starcoder",
88
+ "GPTNeoXForCausalLM": "gptneox",
89
+ "GPTRefactForCausalLM": "refact",
90
+ "Gemma2ForCausalLM": "gemma",
91
+ "Gemma3ForCausalLM": "gemma",
92
+ "Gemma3ForConditionalGeneration": "gemma",
93
+ "Gemma3TextModel": "gemma",
94
+ "Gemma3nForCausalLM": "gemma",
95
+ "Gemma3nForConditionalGeneration": "gemma",
96
+ "Gemma4AssistantForCausalLM": "gemma",
97
+ "Gemma4ForConditionalGeneration": "gemma",
98
+ "Gemma4ForCausalLM": "gemma",
99
+ "Gemma4UnifiedForConditionalGeneration": "gemma",
100
+ "Gemma4UnifiedAssistantForCausalLM": "gemma",
101
+ "GemmaForCausalLM": "gemma",
102
+ "Glm4ForCausalLM": "glm",
103
+ "Glm4MoeForCausalLM": "glm",
104
+ "Glm4MoeLiteForCausalLM": "glm",
105
+ "Glm4vForConditionalGeneration": "glm",
106
+ "Glm4vMoeForConditionalGeneration": "glm",
107
+ "GlmForCausalLM": "chatglm",
108
+ "GlmMoeDsaForCausalLM": "glm",
109
+ "GlmOcrForConditionalGeneration": "glm",
110
+ "GptOssForCausalLM": "gpt_oss",
111
+ "GraniteForCausalLM": "granite",
112
+ "GraniteMoeForCausalLM": "granite",
113
+ "GraniteMoeHybridForCausalLM": "granite",
114
+ "GraniteMoeSharedForCausalLM": "granite",
115
+ "GraniteSwitchForCausalLM": "granite",
116
+ "GraniteSpeechForConditionalGeneration": "granite",
117
+ "GraniteSpeechPlusForConditionalGeneration": "granite",
118
+ "GraniteSWAForCausalLM": "granite",
119
+ "GraniteMoeSWAForCausalLM": "granite",
120
+ "Grok1ForCausalLM": "grok",
121
+ "GrokForCausalLM": "grok",
122
+ "GroveMoeForCausalLM": "grovemoe",
123
+ "HunYuanDenseV1ForCausalLM": "hunyuan",
124
+ "HunYuanMoEV1ForCausalLM": "hunyuan",
125
+ "HunYuanVLForConditionalGeneration": "hunyuan",
126
+ "HrmTextForCausalLM": "hrm_text",
127
+ "HYV3ForCausalLM": "hunyuan",
128
+ "HYV4ForCausalLM": "hy_v4",
129
+ "IQuestCoderForCausalLM": "llama",
130
+ "InternLM2ForCausalLM": "internlm",
131
+ "InternLM3ForCausalLM": "internlm",
132
+ "JAISLMHeadModel": "jais",
133
+ "Jais2ForCausalLM": "jais",
134
+ "JambaForCausalLM": "jamba",
135
+ "JanusForConditionalGeneration": "januspro",
136
+ "JinaBertForMaskedLM": "bert",
137
+ "JinaBertModel": "bert",
138
+ "JinaEmbeddingsV5Model": "bert",
139
+ "KORMoForCausalLM": "qwen",
140
+ "KimiK25ForConditionalGeneration": "deepseek",
141
+ "KimiK3ForConditionalGeneration": "kimi_k3",
142
+ "KimiLinearForCausalLM": "kimi_linear",
143
+ "KimiLinearModel": "kimi_linear",
144
+ "KimiVLForConditionalGeneration": "deepseek",
145
+ "LFM2ForCausalLM": "lfm2",
146
+ "LLaDAMoEModel": "llada",
147
+ "LLaDAMoEModelLM": "llada",
148
+ "LLaDAModelLM": "llada",
149
+ "LLaMAForCausalLM": "llama",
150
+ "Lfm25AudioTokenizer": "lfm2",
151
+ "Lfm2BidirectionalModel": "lfm2",
152
+ "Lfm2ForCausalLM": "lfm2",
153
+ "Lfm2Model": "lfm2",
154
+ "Lfm2MoeForCausalLM": "lfm2",
155
+ "Llama4ForCausalLM": "llama",
156
+ "Llama4ForConditionalGeneration": "llama",
157
+ "LlamaBidirectionalModel": "llama",
158
+ "LlamaForCausalLM": "llama",
159
+ "LlamaModel": "llama",
160
+ "Eagle3DraftModel": "llama",
161
+ "Eagle3Speculator": "llama",
162
+ "Eagle3LlamaForCausalLM": "llama",
163
+ "LlamaForCausalLMEagle3": "llama",
164
+ "LlavaForConditionalGeneration": "llama",
165
+ "LlavaStableLMEpochForCausalLM": "stablelm",
166
+ "MPTForCausalLM": "mpt",
167
+ "MT5ForConditionalGeneration": "t5",
168
+ "MaincoderForCausalLM": "maincoder",
169
+ "Mamba2ForCausalLM": "mamba",
170
+ "MambaForCausalLM": "mamba",
171
+ "MambaLMHeadModel": "mamba",
172
+ "MapleForCausalLM": "maple",
173
+ "MellumForCausalLM": "mellum",
174
+ "MiMoV2FlashForCausalLM": "mimo",
175
+ "MiMoV2ForCausalLM": "mimo",
176
+ "MiniCPM3ForCausalLM": "minicpm",
177
+ "MiniCPMForCausalLM": "minicpm",
178
+ "MiniCPMV4_6ForConditionalGeneration": "minicpm",
179
+ "MiniMaxText01ForCausalLM": "minimax",
180
+ "MiniMaxM1ForCausalLM": "minimax",
181
+ "MiniMaxM2ForCausalLM": "minimax",
182
+ "MiniMaxM3SparseForCausalLM": "minimax",
183
+ "MiniMaxM3SparseForConditionalGeneration": "minimax",
184
+ "Ministral3ForCausalLM": "mistral3",
185
+ "Mistral3ForConditionalGeneration": "mistral3",
186
+ "MistralForCausalLM": "llama",
187
+ "MixtralForCausalLM": "llama",
188
+ "ModernBertForMaskedLM": "bert",
189
+ "ModernBertForSequenceClassification": "bert",
190
+ "ModernBertModel": "bert",
191
+ "NanbeigeForCausalLM": "nanbeige",
192
+ "NemotronForCausalLM": "nemotron",
193
+ "NemotronHForCausalLM": "nemotron",
194
+ "NemotronHPuzzleForCausalLM": "nemotron",
195
+ "NeoBERT": "bert",
196
+ "NeoBERTForSequenceClassification": "bert",
197
+ "NeoBERTLMHead": "bert",
198
+ "NomicBertModel": "bert",
199
+ "OLMoForCausalLM": "olmo",
200
+ "Olmo2ForCausalLM": "olmo",
201
+ "Olmo3ForCausalLM": "olmo",
202
+ "OlmoForCausalLM": "olmo",
203
+ "OlmoeForCausalLM": "olmo",
204
+ "MuseGlimmerAssistantModel": "muse_glimmer",
205
+ "MuseGlimmerForConditionalGeneration": "muse_glimmer",
206
+ "OpenELMForCausalLM": "openelm",
207
+ "OrionForCausalLM": "orion",
208
+ "PLMForCausalLM": "plm",
209
+ "PLaMo2ForCausalLM": "plamo",
210
+ "PLaMo3ForCausalLM": "plamo",
211
+ "PaddleOCRVLForConditionalGeneration": "ernie",
212
+ "PanguEmbeddedForCausalLM": "pangu",
213
+ "Phi3ForCausalLM": "phi",
214
+ "Phi4ForCausalLMV": "phi",
215
+ "PhiForCausalLM": "phi",
216
+ "PhiMoEForCausalLM": "phi",
217
+ "Plamo2ForCausalLM": "plamo",
218
+ "Plamo3ForCausalLM": "plamo",
219
+ "PlamoForCausalLM": "plamo",
220
+ "QWenLMHeadModel": "qwen",
221
+ "Qwen2AudioForConditionalGeneration": "qwen",
222
+ "Qwen2ForCausalLM": "qwen",
223
+ "Qwen2Model": "qwen",
224
+ "Qwen2MoeForCausalLM": "qwen",
225
+ "Qwen2VLForConditionalGeneration": "qwenvl",
226
+ "Qwen2VLModel": "qwenvl",
227
+ "Qwen2_5OmniModel": "qwenvl",
228
+ "Qwen2_5_VLForConditionalGeneration": "qwenvl",
229
+ "Qwen3ASRForConditionalGeneration": "qwen3vl",
230
+ "Qwen3ForCausalLM": "qwen",
231
+ "Qwen3Model": "qwen",
232
+ "Qwen3MoeForCausalLM": "qwen",
233
+ "Qwen3NextForCausalLM": "qwen",
234
+ "Qwen3OmniMoeForConditionalGeneration": "qwen3vl",
235
+ "PocketTTSModel": "pockettts",
236
+ "Qwen3TTSForConditionalGeneration": "qwen3tts",
237
+ "Qwen3VLForConditionalGeneration": "qwen3vl",
238
+ "Qwen3VLMoeForConditionalGeneration": "qwen3vl",
239
+ "Qwen3_5ForCausalLM": "qwen",
240
+ "Qwen3_5ForConditionalGeneration": "qwen",
241
+ "Qwen3_5MoeForCausalLM": "qwen",
242
+ "Qwen3_5MoeForConditionalGeneration": "qwen",
243
+ "Qwen4ExpForCausalLM": "qwen4exp",
244
+ "Qwen4ExpForConditionalGeneration": "qwen4exp",
245
+ "RND1": "qwen",
246
+ "RWForCausalLM": "falcon",
247
+ "RWKV6Qwen2ForCausalLM": "rwkv",
248
+ "RWKV7ForCausalLM": "rwkv",
249
+ "RobertaForSequenceClassification": "bert",
250
+ "RobertaModel": "bert",
251
+ "RuGPT3XLForCausalLM": "gpt2",
252
+ "Rwkv6ForCausalLM": "rwkv",
253
+ "Rwkv7ForCausalLM": "rwkv",
254
+ "RwkvHybridForCausalLM": "rwkv",
255
+ "Sarashina2VisionForCausalLM": "sarashina2",
256
+ "SarvamMoEForCausalLM": "bailingmoe",
257
+ "SeedOssForCausalLM": "olmo",
258
+ "SmallThinkerForCausalLM": "smallthinker",
259
+ "SmolLM3ForCausalLM": "llama",
260
+ "Spark2_5ForCausalLM": "spark2_5",
261
+ "SolarOpenForCausalLM": "glm",
262
+ "StableLMEpochForCausalLM": "stablelm",
263
+ "StableLmForCausalLM": "stablelm",
264
+ "Starcoder2ForCausalLM": "starcoder",
265
+ "Step3p5ForCausalLM": "step3",
266
+ "StepVLForConditionalGeneration": "step3",
267
+ "Step3p7ForConditionalGeneration": "step3",
268
+ "T5EncoderModel": "t5",
269
+ "T5ForConditionalGeneration": "t5",
270
+ "T5WithLMHeadModel": "t5",
271
+ "TalkieForCausalLM": "talkie",
272
+ "UMT5ForConditionalGeneration": "t5",
273
+ "UMT5Model": "t5",
274
+ "UltravoxModel": "ultravox",
275
+ "UnlimitedOCRForCausalLM": "deepseek",
276
+ "VLlama3ForCausalLM": "llama",
277
+ "VoxtralForConditionalGeneration": "llama",
278
+ "WavTokenizerDec": "wavtokenizer",
279
+ "XLMRobertaForSequenceClassification": "bert",
280
+ "XLMRobertaModel": "bert",
281
+ "XverseForCausalLM": "xverse",
282
+ "YoutuForCausalLM": "deepseek",
283
+ "YoutuVLForConditionalGeneration": "deepseek",
284
+ "modeling_grove_moe.GroveMoeForCausalLM": "grovemoe",
285
+ "modeling_sarvam_moe.SarvamMoEForCausalLM": "bailingmoe",
286
+ }
287
+
288
+
289
+ MMPROJ_MODEL_MAP: dict[str, str] = {
290
+ "AudioFlamingo3ForConditionalGeneration": "ultravox",
291
+ "CogVLMForCausalLM": "cogvlm",
292
+ "DeepseekOCR2ForCausalLM": "deepseek",
293
+ "DeepseekOCRForCausalLM": "deepseek",
294
+ "DeepseekV4ForCausalLM": "deepseek",
295
+ "Dots3NoteForCausalLM": "dots3",
296
+ "Dots3NoteForConditionalGeneration": "dots3",
297
+ "DotsOCRForCausalLM": "dotsocr",
298
+ "Exaone4_5_ForConditionalGeneration": "exaone",
299
+ "Gemma3ForConditionalGeneration": "gemma",
300
+ "Gemma3nForConditionalGeneration": "gemma",
301
+ "Gemma4ForConditionalGeneration": "gemma",
302
+ "Gemma4UnifiedForConditionalGeneration": "gemma",
303
+ "Glm4vForConditionalGeneration": "qwen3vl",
304
+ "Glm4vMoeForConditionalGeneration": "qwen3vl",
305
+ "Glm5vForConditionalGeneration": "kimivl",
306
+ "GlmOcrForConditionalGeneration": "qwen3vl",
307
+ "GlmasrModel": "ultravox",
308
+ "Granite4VisionForConditionalGeneration": "granite",
309
+ "GraniteSpeechForConditionalGeneration": "granite",
310
+ "GraniteSpeechPlusForConditionalGeneration": "granite",
311
+ "HunYuanVLForConditionalGeneration": "hunyuan",
312
+ "Idefics3ForConditionalGeneration": "smolvlm",
313
+ "InternVisionModel": "internvl",
314
+ "JanusForConditionalGeneration": "januspro",
315
+ "KimiK25ForConditionalGeneration": "kimivl",
316
+ "KimiVLForConditionalGeneration": "kimivl",
317
+ "Lfm2AudioForConditionalGeneration": "lfm2",
318
+ "Lfm2VlForConditionalGeneration": "lfm2",
319
+ "LightOnOCRForConditionalGeneration": "lighton_ocr",
320
+ "Llama4ForConditionalGeneration": "llama4",
321
+ "LlavaForConditionalGeneration": "llava",
322
+ "MERaLiON2ForConditionalGeneration": "ultravox",
323
+ "MiMoV2ForCausalLM": "mimo",
324
+ "MiniMaxM3SparseForConditionalGeneration": "minimax",
325
+ "MiniCPMV4_6ForConditionalGeneration": "minicpm",
326
+ "Mistral3ForConditionalGeneration": "llava",
327
+ "NemotronH_Nano_VL_V2": "nemotron",
328
+ "MuseGlimmerForConditionalGeneration": "muse_glimmer",
329
+ "PaddleOCRVisionModel": "ernie",
330
+ "Phi4ForCausalLMV": "phi",
331
+ "Qwen2AudioForConditionalGeneration": "ultravox",
332
+ "Qwen2VLForConditionalGeneration": "qwenvl",
333
+ "Qwen2VLModel": "qwenvl",
334
+ "Qwen2_5OmniModel": "qwenvl",
335
+ "Qwen2_5_VLForConditionalGeneration": "qwenvl",
336
+ "Qwen3ASRForConditionalGeneration": "qwen3vl",
337
+ "Qwen3OmniMoeForConditionalGeneration": "qwen3vl",
338
+ "PocketTTSModel": "pockettts",
339
+ "Qwen3TTSForConditionalGeneration": "qwen3tts",
340
+ "Qwen3VLForConditionalGeneration": "qwen3vl",
341
+ "Qwen3VLMoeForConditionalGeneration": "qwen3vl",
342
+ "Qwen3_5ForConditionalGeneration": "qwen3vl",
343
+ "Qwen3_5MoeForConditionalGeneration": "qwen3vl",
344
+ "Qwen4ExpForConditionalGeneration": "qwen4exp",
345
+ "RADIOModel": "nemotron",
346
+ "Sarashina2VisionForCausalLM": "sarashina2",
347
+ "SmolVLMForConditionalGeneration": "smolvlm",
348
+ "StepVLForConditionalGeneration": "step3",
349
+ "Step3p7ForConditionalGeneration": "step3",
350
+ "UltravoxModel": "ultravox",
351
+ "UnlimitedOCRForCausalLM": "deepseek",
352
+ "VoxtralForConditionalGeneration": "ultravox",
353
+ "YoutuVLForConditionalGeneration": "youtuvl",
354
+ }
355
+
356
+
357
+ _TEXT_MODEL_MODULES = sorted(set(TEXT_MODEL_MAP.values()))
358
+ _MMPROJ_MODEL_MODULES = sorted(set(MMPROJ_MODEL_MAP.values()))
359
+
360
+
361
+ _loaded_text_modules: set[str] = set()
362
+ _loaded_mmproj_modules: set[str] = set()
363
+
364
+
365
+ def load_all_models() -> None:
366
+ """Import all model modules to trigger @ModelBase.register() decorators."""
367
+ if len(_loaded_text_modules) != len(_TEXT_MODEL_MODULES):
368
+ for module_name in _TEXT_MODEL_MODULES:
369
+ if module_name not in _loaded_text_modules:
370
+ try:
371
+ __import__(f"conversion.{module_name}")
372
+ _loaded_text_modules.add(module_name)
373
+ except Exception as e:
374
+ logger.warning(f"Failed to load model module {module_name}: {e}")
375
+
376
+ if len(_loaded_mmproj_modules) != len(_MMPROJ_MODEL_MODULES):
377
+ for module_name in _MMPROJ_MODEL_MODULES:
378
+ if module_name not in _loaded_mmproj_modules:
379
+ try:
380
+ __import__(f"conversion.{module_name}")
381
+ _loaded_mmproj_modules.add(module_name)
382
+ except Exception as e:
383
+ logger.warning(f"Failed to load model module {module_name}: {e}")
384
+
385
+
386
+ def get_model_class(name: str, mmproj: bool = False) -> Type[ModelBase]:
387
+ """Dynamically import and return a model class by its HuggingFace architecture name."""
388
+ relevant_map = MMPROJ_MODEL_MAP if mmproj else TEXT_MODEL_MAP
389
+ if name not in relevant_map:
390
+ raise NotImplementedError(f"Architecture {name!r} not supported!")
391
+ module_name = relevant_map[name]
392
+ __import__(f"conversion.{module_name}")
393
+ model_type = ModelType.MMPROJ if mmproj else ModelType.TEXT
394
+ return ModelBase._model_classes[model_type][name]
395
+
396
+
397
+ def print_registered_models() -> None:
398
+ load_all_models()
399
+ logger.error("TEXT models:")
400
+ for name in sorted(TEXT_MODEL_MAP.keys()):
401
+ logger.error(f" - {name}")
402
+ logger.error("MMPROJ models:")
403
+ for name in sorted(MMPROJ_MODEL_MAP.keys()):
404
+ logger.error(f" - {name}")
conversion/afmoe.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import Callable, Iterable, TYPE_CHECKING
4
+
5
+ import torch
6
+
7
+ if TYPE_CHECKING:
8
+ from torch import Tensor
9
+
10
+ from .base import ModelBase, gguf
11
+
12
+ from .llama import LlamaModel
13
+
14
+
15
+ @ModelBase.register("AfmoeForCausalLM")
16
+ @ModelBase.example("arcee-ai/Trinity-Large-Thinking")
17
+ class AfmoeModel(LlamaModel):
18
+ model_arch = gguf.MODEL_ARCH.AFMOE
19
+
20
+ def set_gguf_parameters(self):
21
+ super().set_gguf_parameters()
22
+
23
+ # MoE parameters
24
+ if (n_shared_experts := self.hparams.get("num_shared_experts")) is not None:
25
+ self.gguf_writer.add_expert_shared_count(n_shared_experts)
26
+ if (moe_intermediate_size := self.hparams.get("moe_intermediate_size")) is not None:
27
+ self.gguf_writer.add_expert_feed_forward_length(moe_intermediate_size)
28
+ if (n_dense_layers := self.hparams.get("num_dense_layers")) is not None:
29
+ self.gguf_writer.add_leading_dense_block_count(n_dense_layers)
30
+
31
+ # Route normalization and scaling
32
+ if (route_norm := self.hparams.get("route_norm")) is not None:
33
+ self.gguf_writer.add_expert_weights_norm(route_norm)
34
+ if (route_scale := self.hparams.get("route_scale")) is not None:
35
+ self.gguf_writer.add_expert_weights_scale(route_scale)
36
+
37
+ # Sliding window attention
38
+ if (sliding_window := self.hparams.get("sliding_window")) is not None:
39
+ self.gguf_writer.add_sliding_window(sliding_window)
40
+
41
+ @classmethod
42
+ def filter_tensors(cls, item: tuple[str, Callable[[], Tensor]]) -> tuple[str, Callable[[], Tensor]] | None:
43
+ name, gen = item
44
+
45
+ if name.endswith(".expert_bias"):
46
+ name = name.replace(".expert_bias", ".expert_bias.bias")
47
+
48
+ return super().filter_tensors((name, gen))
49
+
50
+ def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]:
51
+ # Handle expert weights - they're already merged in the HF format
52
+ # process the experts separately
53
+ if name.find("mlp.experts") != -1:
54
+ n_experts = self.find_hparam(["num_local_experts", "num_experts"])
55
+ assert bid is not None
56
+
57
+ if self._experts is None:
58
+ self._experts = [{} for _ in range(self.block_count)]
59
+
60
+ self._experts[bid][name] = data_torch
61
+
62
+ if len(self._experts[bid]) >= n_experts * 3:
63
+ # merge the experts into a single 3d tensor
64
+ for w_name in ["gate_proj", "up_proj", "down_proj"]:
65
+ datas: list[Tensor] = []
66
+
67
+ for xid in range(n_experts):
68
+ ename_to_retrieve = f"model.layers.{bid}.mlp.experts.{xid}.{w_name}.weight"
69
+ datas.append(self._experts[bid][ename_to_retrieve])
70
+ del self._experts[bid][ename_to_retrieve]
71
+
72
+ data_torch = torch.stack(datas, dim=0)
73
+ merged_name = f"model.layers.{bid}.mlp.experts.{w_name}.weight"
74
+ yield from ModelBase.modify_tensors(self, data_torch, merged_name, bid)
75
+
76
+ return
77
+ else:
78
+ return
79
+
80
+ yield from ModelBase.modify_tensors(self, data_torch, name, bid)
conversion/arctic.py ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import sys
5
+
6
+ from typing import Iterable, TYPE_CHECKING
7
+
8
+ import torch
9
+
10
+ if TYPE_CHECKING:
11
+ from torch import Tensor
12
+
13
+ from .base import ModelBase, SentencePieceTokenTypes, TextModel, gguf, logger
14
+
15
+ from .llama import LlamaModel
16
+
17
+
18
+ @ModelBase.register("ArcticForCausalLM")
19
+ @ModelBase.example("Snowflake/snowflake-arctic-instruct")
20
+ class ArcticModel(TextModel):
21
+ model_arch = gguf.MODEL_ARCH.ARCTIC
22
+
23
+ def set_vocab(self):
24
+ # The reason for using a custom implementation here is that the
25
+ # snowflake-arctic-instruct model redefined tokens 31998 and 31999 from
26
+ # tokenizer.model and used them as BOS and EOS instead of adding new tokens.
27
+ from sentencepiece import SentencePieceProcessor
28
+
29
+ tokenizer_path = self.dir_model / 'tokenizer.model'
30
+
31
+ if not tokenizer_path.is_file():
32
+ logger.error(f'Error: Missing {tokenizer_path}')
33
+ sys.exit(1)
34
+
35
+ # Read the whole vocabulary from the tokenizer.model file
36
+ tokenizer = SentencePieceProcessor()
37
+ tokenizer.LoadFromFile(str(tokenizer_path))
38
+
39
+ vocab_size = self.hparams.get('vocab_size', tokenizer.vocab_size())
40
+
41
+ tokens: list[bytes] = [f"[PAD{i}]".encode("utf-8") for i in range(vocab_size)]
42
+ scores: list[float] = [-10000.0] * vocab_size
43
+ toktypes: list[int] = [SentencePieceTokenTypes.UNUSED] * vocab_size
44
+
45
+ for token_id in range(tokenizer.vocab_size()):
46
+
47
+ piece = tokenizer.IdToPiece(token_id)
48
+ text = piece.encode("utf-8")
49
+ score = tokenizer.GetScore(token_id)
50
+
51
+ toktype = SentencePieceTokenTypes.NORMAL
52
+ if tokenizer.IsUnknown(token_id):
53
+ toktype = SentencePieceTokenTypes.UNKNOWN
54
+ elif tokenizer.IsControl(token_id):
55
+ toktype = SentencePieceTokenTypes.CONTROL
56
+ elif tokenizer.IsUnused(token_id):
57
+ toktype = SentencePieceTokenTypes.UNUSED
58
+ elif tokenizer.IsByte(token_id):
59
+ toktype = SentencePieceTokenTypes.BYTE
60
+
61
+ tokens[token_id] = text
62
+ scores[token_id] = score
63
+ toktypes[token_id] = toktype
64
+
65
+ # Use the added_tokens_decoder field from tokeniser_config.json as the source
66
+ # of information about added/redefined tokens and modify them accordingly.
67
+ tokenizer_config_file = self.dir_model / 'tokenizer_config.json'
68
+ if tokenizer_config_file.is_file():
69
+ with open(tokenizer_config_file, "r", encoding="utf-8") as f:
70
+ tokenizer_config_json = json.load(f)
71
+
72
+ if "added_tokens_decoder" in tokenizer_config_json:
73
+ added_tokens_decoder = tokenizer_config_json["added_tokens_decoder"]
74
+ for token_id, token_json in added_tokens_decoder.items():
75
+ token_id = int(token_id)
76
+ if token_id >= vocab_size:
77
+ logger.debug(f'ignore token {token_id}: id is out of range, max={vocab_size - 1}')
78
+ continue
79
+
80
+ token_content = token_json["content"]
81
+ token_type = SentencePieceTokenTypes.USER_DEFINED
82
+ token_score = -10000.0
83
+
84
+ # Map unk_token to UNKNOWN, other special tokens to CONTROL
85
+ # Set the score to 0.0 as in the original tokenizer.model
86
+ if ("special" in token_json) and token_json["special"]:
87
+ if token_content == tokenizer_config_json["unk_token"]:
88
+ token_type = SentencePieceTokenTypes.UNKNOWN
89
+ else:
90
+ token_type = SentencePieceTokenTypes.CONTROL
91
+ token_score = 0.0
92
+
93
+ logger.info(f"Setting added token {token_id} to '{token_content}' (type: {token_type}, score: {token_score:.2f})")
94
+ tokens[token_id] = token_content.encode("utf-8")
95
+ toktypes[token_id] = token_type
96
+ scores[token_id] = token_score
97
+
98
+ self.gguf_writer.add_tokenizer_model("llama")
99
+ self.gguf_writer.add_tokenizer_pre("default")
100
+ self.gguf_writer.add_token_list(tokens)
101
+ self.gguf_writer.add_token_scores(scores)
102
+ self.gguf_writer.add_token_types(toktypes)
103
+
104
+ special_vocab = gguf.SpecialVocab(self.dir_model, n_vocab=len(tokens))
105
+ special_vocab.add_to_gguf(self.gguf_writer)
106
+
107
+ def set_gguf_parameters(self):
108
+ super().set_gguf_parameters()
109
+ hparams = self.hparams
110
+ self.gguf_writer.add_vocab_size(hparams["vocab_size"])
111
+ self.gguf_writer.add_rope_dimension_count(hparams["hidden_size"] // hparams["num_attention_heads"])
112
+
113
+ _experts: list[dict[str, Tensor]] | None = None
114
+
115
+ def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]:
116
+ n_head = self.hparams["num_attention_heads"]
117
+ n_kv_head = self.hparams.get("num_key_value_heads")
118
+
119
+ if name.endswith("q_proj.weight"):
120
+ data_torch = LlamaModel.permute(data_torch, n_head, n_head)
121
+ if name.endswith("k_proj.weight"):
122
+ data_torch = LlamaModel.permute(data_torch, n_head, n_kv_head)
123
+
124
+ # process the experts separately
125
+ if name.find("block_sparse_moe.experts") != -1:
126
+ n_experts = self.hparams["num_local_experts"]
127
+
128
+ assert bid is not None
129
+
130
+ if self._experts is None:
131
+ self._experts = [{} for _ in range(self.block_count)]
132
+
133
+ self._experts[bid][name] = data_torch
134
+
135
+ if len(self._experts[bid]) >= n_experts * 3:
136
+ # merge the experts into a single 3d tensor
137
+ for wid in ["w1", "w2", "w3"]:
138
+ datas: list[Tensor] = []
139
+
140
+ for xid in range(n_experts):
141
+ ename = f"model.layers.{bid}.block_sparse_moe.experts.{xid}.{wid}.weight"
142
+ datas.append(self._experts[bid][ename])
143
+ del self._experts[bid][ename]
144
+
145
+ data_torch = torch.stack(datas, dim=0)
146
+
147
+ merged_name = f"layers.{bid}.feed_forward.experts.{wid}.weight"
148
+
149
+ yield from super().modify_tensors(data_torch, merged_name, bid)
150
+ return
151
+ else:
152
+ return
153
+
154
+ yield from super().modify_tensors(data_torch, name, bid)
155
+
156
+ def prepare_tensors(self):
157
+ super().prepare_tensors()
158
+
159
+ if self._experts is not None:
160
+ # flatten `list[dict[str, Tensor]]` into `list[str]`
161
+ experts = [k for d in self._experts for k in d.keys()]
162
+ if len(experts) > 0:
163
+ raise ValueError(f"Unprocessed experts: {experts}")
conversion/baichuan.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import Iterable, TYPE_CHECKING
4
+
5
+ if TYPE_CHECKING:
6
+ from torch import Tensor
7
+
8
+ from .base import ModelBase, TextModel, gguf, logger
9
+
10
+
11
+ @ModelBase.register("BaichuanForCausalLM", "BaiChuanForCausalLM")
12
+ @ModelBase.example("baichuan-inc/Baichuan2-7B-Chat", "baichuan-inc/Baichuan-7B")
13
+ class BaichuanModel(TextModel):
14
+ model_arch = gguf.MODEL_ARCH.BAICHUAN
15
+
16
+ def set_vocab(self):
17
+ self._set_vocab_sentencepiece()
18
+
19
+ def set_gguf_parameters(self):
20
+ super().set_gguf_parameters()
21
+
22
+ self.gguf_writer.add_tensor_data_layout("Meta AI original pth")
23
+ self.gguf_writer.add_rope_dimension_count(self.hparams["hidden_size"] // self.hparams["num_attention_heads"])
24
+
25
+ def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]:
26
+ head_count = self.hparams["num_attention_heads"]
27
+ head_count_kv = self.hparams.get("num_key_value_heads", head_count)
28
+
29
+ if bid is not None and name == f"model.layers.{bid}.self_attn.W_pack.weight":
30
+ logger.info(f"Unpacking and permuting layer {bid}")
31
+ yield from [
32
+ (self.format_tensor_name(gguf.MODEL_TENSOR.ATTN_Q, bid),
33
+ self._reverse_hf_permute_part(data_torch, 0, head_count, head_count)),
34
+ (self.format_tensor_name(gguf.MODEL_TENSOR.ATTN_K, bid),
35
+ self._reverse_hf_permute_part(data_torch, 1, head_count, head_count_kv)),
36
+ (self.format_tensor_name(gguf.MODEL_TENSOR.ATTN_V, bid),
37
+ self._reverse_hf_part(data_torch, 2)),
38
+ ]
39
+ else:
40
+ yield from self.modify_tensors(data_torch, self.map_tensor_name(name), bid)
41
+
42
+ def _reverse_hf_permute(self, weights: Tensor, n_head: int, n_kv_head: int | None = None) -> Tensor:
43
+ if n_kv_head is not None and n_head != n_kv_head:
44
+ n_head //= n_kv_head
45
+
46
+ return (
47
+ weights.reshape(n_head, 2, weights.shape[0] // n_head // 2, *weights.shape[1:])
48
+ .swapaxes(1, 2)
49
+ .reshape(weights.shape)
50
+ )
51
+
52
+ def _reverse_hf_permute_part(
53
+ self, weights: Tensor, n_part: int, n_head: int, n_head_kv: int | None = None,
54
+ ) -> Tensor:
55
+ r = weights.shape[0] // 3
56
+ return self._reverse_hf_permute(weights[r * n_part:r * n_part + r, ...], n_head, n_head_kv)
57
+
58
+ def _reverse_hf_part(self, weights: Tensor, n_part: int) -> Tensor:
59
+ r = weights.shape[0] // 3
60
+ return weights[r * n_part:r * n_part + r, ...]
conversion/bailingmoe.py ADDED
@@ -0,0 +1,219 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import Callable, Iterable, TYPE_CHECKING
4
+
5
+ import torch
6
+
7
+ if TYPE_CHECKING:
8
+ from torch import Tensor
9
+
10
+ from .base import ModelBase, TextModel, gguf
11
+
12
+
13
+ @ModelBase.register("BailingMoeForCausalLM")
14
+ @ModelBase.example("inclusionAI/Ling-lite")
15
+ class BailingMoeModel(TextModel):
16
+ model_arch = gguf.MODEL_ARCH.BAILINGMOE
17
+
18
+ def set_vocab(self):
19
+ self._set_vocab_gpt2()
20
+
21
+ def set_gguf_parameters(self):
22
+ super().set_gguf_parameters()
23
+ hparams = self.hparams
24
+ if (rope_dim := hparams.get("head_dim")) is None:
25
+ rope_dim = hparams["hidden_size"] // hparams["num_attention_heads"]
26
+
27
+ self.gguf_writer.add_rope_dimension_count(rope_dim)
28
+ self.gguf_writer.add_leading_dense_block_count(hparams["first_k_dense_replace"])
29
+ self.gguf_writer.add_vocab_size(hparams["vocab_size"])
30
+ self.gguf_writer.add_expert_feed_forward_length(hparams["moe_intermediate_size"])
31
+ self.gguf_writer.add_expert_weights_scale(1.0)
32
+ self.gguf_writer.add_expert_shared_count(hparams["num_shared_experts"])
33
+ self.gguf_writer.add_expert_weights_norm(hparams["norm_topk_prob"])
34
+
35
+ _experts: list[dict[str, Tensor]] | None = None
36
+
37
+ @staticmethod
38
+ def permute(weights: Tensor, n_head: int, n_head_kv: int | None):
39
+ if n_head_kv is not None and n_head != n_head_kv:
40
+ n_head = n_head_kv
41
+ return (weights.reshape(n_head, 2, weights.shape[0] // n_head // 2, *weights.shape[1:])
42
+ .swapaxes(1, 2)
43
+ .reshape(weights.shape))
44
+
45
+ def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]:
46
+ n_head = self.hparams["num_attention_heads"]
47
+ n_kv_head = self.hparams.get("num_key_value_heads")
48
+ n_embd = self.hparams["hidden_size"]
49
+ if (head_dim := self.hparams.get("head_dim")) is None:
50
+ head_dim = n_embd // n_head
51
+
52
+ output_name = self.format_tensor_name(gguf.MODEL_TENSOR.OUTPUT)
53
+
54
+ if name.endswith("attention.dense.weight"):
55
+ yield from super().modify_tensors(data_torch, self.format_tensor_name(gguf.MODEL_TENSOR.ATTN_OUT, bid), bid)
56
+ return
57
+ elif name.endswith("query_key_value.weight"):
58
+ q, k, v = data_torch.split([n_head * head_dim, n_kv_head * head_dim, n_kv_head * head_dim], dim=-2)
59
+
60
+ yield from super().modify_tensors(BailingMoeModel.permute(q, n_head, n_head), self.format_tensor_name(gguf.MODEL_TENSOR.ATTN_Q, bid), bid)
61
+ yield from super().modify_tensors(BailingMoeModel.permute(k, n_head, n_kv_head), self.format_tensor_name(gguf.MODEL_TENSOR.ATTN_K, bid), bid)
62
+ yield from super().modify_tensors(v,self.format_tensor_name(gguf.MODEL_TENSOR.ATTN_V, bid), bid)
63
+ return
64
+ elif name.find("mlp.experts") != -1:
65
+ n_experts = self.find_hparam(["num_local_experts", "num_experts"])
66
+ assert bid is not None
67
+
68
+ if self._experts is None:
69
+ self._experts = [{} for _ in range(self.block_count)]
70
+
71
+ self._experts[bid][name] = data_torch
72
+
73
+ if len(self._experts[bid]) >= n_experts * 3:
74
+ # merge the experts into a single 3d tensor
75
+ for w_name in ["down_proj", "gate_proj", "up_proj"]:
76
+ datas: list[Tensor] = []
77
+
78
+ for xid in range(n_experts):
79
+ ename = f"model.layers.{bid}.mlp.experts.{xid}.{w_name}.weight"
80
+ datas.append(self._experts[bid][ename])
81
+ del self._experts[bid][ename]
82
+
83
+ data_torch = torch.stack(datas, dim=0)
84
+
85
+ merged_name = f"model.layers.{bid}.mlp.experts.{w_name}.weight"
86
+
87
+ new_name = self.map_tensor_name(merged_name)
88
+
89
+ yield from super().modify_tensors(data_torch, new_name, bid)
90
+
91
+ return
92
+
93
+ new_name = self.map_tensor_name(name)
94
+
95
+ if new_name == output_name and self.hparams.get("norm_head"):
96
+ data_torch = data_torch.float()
97
+ data_torch /= torch.norm(data_torch, p=2, dim=0, keepdim=True) + 1e-7
98
+
99
+ yield from super().modify_tensors(data_torch, new_name, bid)
100
+
101
+ def prepare_tensors(self):
102
+ super().prepare_tensors()
103
+
104
+ if self._experts is not None:
105
+ # flatten `list[dict[str, Tensor]]` into `list[str]`
106
+ experts = [k for d in self._experts for k in d.keys()]
107
+ if len(experts) > 0:
108
+ raise ValueError(f"Unprocessed experts: {experts}")
109
+
110
+
111
+ @ModelBase.register("BailingMoeV2ForCausalLM")
112
+ @ModelBase.example("inclusionAI/Ling-mini-2.0")
113
+ class BailingMoeV2Model(TextModel):
114
+ model_arch = gguf.MODEL_ARCH.BAILINGMOE2
115
+
116
+ def __init__(self, *args, **kwargs):
117
+ super().__init__(*args, **kwargs)
118
+ if nextn_layers := self.hparams.get("num_nextn_predict_layers", 0):
119
+ self.block_count = self.hparams["num_hidden_layers"] + nextn_layers
120
+ self.tensor_map = gguf.get_tensor_name_map(self.model_arch, self.block_count)
121
+
122
+ def set_vocab(self):
123
+ self._set_vocab_gpt2()
124
+
125
+ def set_gguf_parameters(self):
126
+ super().set_gguf_parameters()
127
+ hparams = self.hparams
128
+ if (rope_dim := hparams.get("head_dim")) is None:
129
+ rope_dim = hparams["hidden_size"] // hparams["num_attention_heads"]
130
+
131
+ self.gguf_writer.add_rope_dimension_count(int(rope_dim * self.rope_parameters.get("partial_rotary_factor", 0.5)))
132
+ self.gguf_writer.add_leading_dense_block_count(hparams["first_k_dense_replace"])
133
+ self.gguf_writer.add_vocab_size(hparams["vocab_size"])
134
+ self.gguf_writer.add_expert_feed_forward_length(hparams["moe_intermediate_size"])
135
+ self.gguf_writer.add_expert_shared_feed_forward_length(hparams.get("moe_shared_expert_intermediate_size", hparams["moe_intermediate_size"] * hparams["num_shared_experts"]))
136
+ self.gguf_writer.add_expert_weights_scale(hparams["routed_scaling_factor"])
137
+ self.gguf_writer.add_expert_shared_count(hparams["num_shared_experts"])
138
+ self.gguf_writer.add_expert_weights_norm(hparams["norm_topk_prob"])
139
+
140
+ if (nextn_layers := self.hparams.get("num_nextn_predict_layers")) is not None:
141
+ self.gguf_writer.add_nextn_predict_layers(nextn_layers)
142
+
143
+ _experts: list[dict[str, Tensor]] | None = None
144
+
145
+ @classmethod
146
+ def filter_tensors(cls, item: tuple[str, Callable[[], Tensor]]) -> tuple[str, Callable[[], Tensor]] | None:
147
+ name, gen = item
148
+
149
+ if name.endswith(".expert_bias"):
150
+ name = name.replace(".expert_bias", ".expert_bias.bias")
151
+
152
+ return super().filter_tensors((name, gen))
153
+
154
+ def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]:
155
+ if "mlp.experts" in name:
156
+ n_experts = self.find_hparam(["num_local_experts", "num_experts"])
157
+ assert bid is not None
158
+
159
+ if self._experts is None:
160
+ self._experts = [{} for _ in range(self.block_count)]
161
+
162
+ self._experts[bid][name] = data_torch
163
+
164
+ if len(self._experts[bid]) >= n_experts * 3:
165
+ # merge the experts into a single 3d tensor
166
+ for w_name in ["down_proj", "gate_proj", "up_proj"]:
167
+ datas: list[Tensor] = []
168
+
169
+ for xid in range(n_experts):
170
+ ename = f"model.layers.{bid}.mlp.experts.{xid}.{w_name}.weight"
171
+ datas.append(self._experts[bid][ename])
172
+ del self._experts[bid][ename]
173
+
174
+ data_torch = torch.stack(datas, dim=0)
175
+
176
+ merged_name = f"model.layers.{bid}.mlp.experts.{w_name}.weight"
177
+
178
+ yield from super().modify_tensors(data_torch, merged_name, bid)
179
+ return
180
+
181
+ yield from super().modify_tensors(data_torch, name, bid)
182
+
183
+ def prepare_tensors(self):
184
+ super().prepare_tensors()
185
+
186
+ if self._experts is not None:
187
+ # flatten `list[dict[str, Tensor]]` into `list[str]`
188
+ experts = [k for d in self._experts for k in d.keys()]
189
+ if len(experts) > 0:
190
+ raise ValueError(f"Unprocessed experts: {experts}")
191
+
192
+
193
+ @ModelBase.register("SarvamMoEForCausalLM", "modeling_sarvam_moe.SarvamMoEForCausalLM")
194
+ @ModelBase.example("sarvamai/sarvam-30b")
195
+ class SarvamMoEModel(BailingMoeV2Model):
196
+ model_arch = gguf.MODEL_ARCH.BAILINGMOE2
197
+ # Sarvam-MoE shares the BailingMoeV2 architecture; only differences:
198
+ # - full rotary (no partial_rotary_factor)
199
+ # - expert bias is zero-mean normalized at load time
200
+
201
+ def set_gguf_parameters(self):
202
+ super().set_gguf_parameters()
203
+ hparams = self.hparams
204
+ if (rope_dim := hparams.get("head_dim")) is None:
205
+ rope_dim = hparams["hidden_size"] // hparams["num_attention_heads"]
206
+ # Override the partial-rotary value written by BailingMoeV2 with the full rotary dim
207
+ self.gguf_writer.add_rope_dimension_count(rope_dim)
208
+
209
+ @classmethod
210
+ def filter_tensors(cls, item: tuple[str, Callable[[], Tensor]]) -> tuple[str, Callable[[], Tensor]] | None:
211
+ name, gen = item
212
+ if name.endswith(".expert_bias"):
213
+ # Sarvam normalizes expert bias to zero mean
214
+ inner = gen
215
+
216
+ def gen():
217
+ t = inner()
218
+ return t - t.mean()
219
+ return super().filter_tensors((name, gen))
conversion/bailingmoe3.py ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import re
4
+
5
+ from typing import Callable, Iterable, TYPE_CHECKING
6
+
7
+ import torch
8
+
9
+ if TYPE_CHECKING:
10
+ from torch import Tensor
11
+
12
+ from .base import ModelBase, TextModel, gguf
13
+
14
+
15
+ @ModelBase.register("BailingMoeV3ForCausalLM")
16
+ @ModelBase.example("inclusionAI/Ling-3.0-tiny", "inclusionAI/Ling-3.0-flash")
17
+ class BailingMoeV3Model(TextModel):
18
+ model_arch = gguf.MODEL_ARCH.BAILINGMOE3
19
+ supports_mtp_export = True
20
+
21
+ _experts: list[dict[str, Tensor]] | None = None
22
+ _main_layers: int | None = None
23
+
24
+ def __init__(self, *args, **kwargs):
25
+ super().__init__(*args, **kwargs)
26
+ nextn_layers = self.hparams.get("num_nextn_predict_layers", 0) or 0
27
+ if self.no_mtp:
28
+ nextn_layers = 0
29
+ self.block_count = self.hparams["num_hidden_layers"] + nextn_layers
30
+ self.tensor_map = gguf.get_tensor_name_map(self.model_arch, self.block_count)
31
+
32
+ def index_tensors(self, remote_hf_model_id: str | None = None):
33
+ type(self)._main_layers = self.hparams["num_hidden_layers"]
34
+ return super().index_tensors(remote_hf_model_id=remote_hf_model_id)
35
+
36
+ def set_vocab(self):
37
+ self._set_vocab_gpt2()
38
+
39
+ def is_full_attention(self, bid: int) -> bool:
40
+ n_layer = self.hparams["num_hidden_layers"]
41
+ layer_group_size = self.hparams["layer_group_size"]
42
+ return bid >= n_layer or (bid + 1) % layer_group_size == 0 or bid >= n_layer // layer_group_size * layer_group_size
43
+
44
+ def set_gguf_parameters(self):
45
+ if not self.hparams.get("no_kda_lora", False):
46
+ raise ValueError("BailingMoeV3 KDA LoRA projections are not supported")
47
+ if not self.hparams.get("kda_safe_gate", False):
48
+ raise ValueError("BailingMoeV3 non-safe KDA gates are not supported")
49
+ if self.hparams.get("gated_attention_proj_granularity_type") != "head_wise":
50
+ raise ValueError("BailingMoeV3 requires head-wise attention gates")
51
+
52
+ self.hparams["num_key_value_heads"] = 1
53
+ super().set_gguf_parameters()
54
+
55
+ n_head_kv = [1 if self.is_full_attention(il) else 0 for il in range(self.block_count)]
56
+ self.gguf_writer.add_head_count_kv(n_head_kv)
57
+
58
+ self.gguf_writer.add_vocab_size(self.hparams["vocab_size"])
59
+ self.gguf_writer.add_ssm_conv_kernel(self.hparams["short_conv_kernel_size"])
60
+ self.gguf_writer.add_kda_head_dim(self.hparams["head_dim"])
61
+ self.gguf_writer.add_kda_safe_gate(self.hparams["kda_safe_gate"])
62
+ self.gguf_writer.add_kda_gate_lower_bound(self.hparams["kda_lower_bound"])
63
+
64
+ kv_lora_rank = self.hparams["kv_lora_rank"]
65
+ qk_nope_head_dim = self.hparams["qk_nope_head_dim"]
66
+ qk_rope_head_dim = self.hparams["qk_rope_head_dim"]
67
+ if (q_lora_rank := self.hparams.get("q_lora_rank")) is not None:
68
+ self.gguf_writer.add_q_lora_rank(q_lora_rank)
69
+ self.gguf_writer.add_kv_lora_rank(kv_lora_rank)
70
+ self.gguf_writer.add_rope_dimension_count(qk_rope_head_dim)
71
+ self.gguf_writer.add_key_length(kv_lora_rank + qk_rope_head_dim)
72
+ self.gguf_writer.add_key_length_mla(qk_nope_head_dim + qk_rope_head_dim)
73
+ self.gguf_writer.add_value_length_mla(self.hparams["v_head_dim"])
74
+
75
+ self.gguf_writer.add_expert_feed_forward_length(self.hparams["moe_intermediate_size"])
76
+ self.gguf_writer.add_expert_shared_feed_forward_length(self.hparams["moe_shared_expert_intermediate_size"])
77
+ self.gguf_writer.add_expert_shared_count(self.hparams["num_shared_experts"])
78
+ self.gguf_writer.add_leading_dense_block_count(self.hparams["first_k_dense_replace"])
79
+ self.gguf_writer.add_expert_weights_scale(self.hparams["routed_scaling_factor"])
80
+ self.gguf_writer.add_expert_weights_norm(self.hparams["norm_topk_prob"])
81
+
82
+ def clamp_limits(key: str) -> list[float] | None:
83
+ values = self.hparams.get(key)
84
+ if values is None:
85
+ return None
86
+ values = [0.0 if value is None else float(value) for value in values[:self.block_count]]
87
+ return values + [0.0] * (self.block_count - len(values))
88
+
89
+ if (values := clamp_limits("expert_swiglu_limit_list")) is not None:
90
+ self.gguf_writer.add_swiglu_clamp_exp(values)
91
+ if (values := clamp_limits("share_expert_swiglu_limit_list")) is not None:
92
+ self.gguf_writer.add_swiglu_clamp_shexp(values)
93
+
94
+ if not self.no_mtp and (nextn_layers := self.hparams.get("num_nextn_predict_layers", 0)):
95
+ self.gguf_writer.add_nextn_predict_layers(nextn_layers)
96
+
97
+ def prepare_metadata(self, vocab_only: bool):
98
+ from_dir = self.fname_out.is_dir()
99
+ super().prepare_metadata(vocab_only=vocab_only)
100
+
101
+ if not self.mtp_only or not from_dir:
102
+ return
103
+
104
+ output_type: str = self.ftype.name.partition("_")[2]
105
+ fname_default: str = gguf.naming_convention(
106
+ self.metadata.name, self.metadata.basename, self.metadata.finetune,
107
+ self.metadata.version, size_label=None, output_type=output_type, model_type=None)
108
+ self.fname_out = self.fname_out.parent / f"mtp-{fname_default}.gguf"
109
+
110
+ @classmethod
111
+ def filter_tensors(cls, item: tuple[str, Callable[[], Tensor]]) -> tuple[str, Callable[[], Tensor]] | None:
112
+ name, gen = item
113
+ if name.endswith(".expert_bias"):
114
+ name += ".bias"
115
+
116
+ if cls._main_layers is None:
117
+ return super().filter_tensors((name, gen))
118
+
119
+ m = re.match(r"model\.layers\.(\d+)\.", name)
120
+ is_mtp = m is not None and int(m.group(1)) >= cls._main_layers
121
+
122
+ if is_mtp and cls.no_mtp:
123
+ return None
124
+ if cls.mtp_only and not is_mtp and name not in (
125
+ "model.word_embeddings.weight", "model.norm.weight", "lm_head.weight",
126
+ ):
127
+ return None
128
+
129
+ return super().filter_tensors((name, gen))
130
+
131
+ def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]:
132
+ if name.endswith((".q_conv1d.weight", ".k_conv1d.weight", ".v_conv1d.weight")) and data_torch.ndim in (2, 3):
133
+ d_inner = data_torch.shape[0]
134
+ d_conv = data_torch.shape[-1]
135
+ data_torch = data_torch.reshape(1, d_inner, 1, d_conv)
136
+
137
+ if name.endswith(".A_log"):
138
+ data_torch = torch.exp(data_torch).reshape(-1, 1)
139
+
140
+ if name.endswith(".dt_bias"):
141
+ name = name.rpartition(".dt_bias")[0] + ".dt_proj.bias"
142
+
143
+ if name.endswith(".attention.f_proj.weight"):
144
+ assert bid is not None
145
+ if self.is_full_attention(bid):
146
+ raise ValueError(f"unexpected f_proj on full-attention layer {bid}")
147
+ name = self.format_tensor_name(gguf.MODEL_TENSOR.SSM_F_A, bid)
148
+
149
+ if name.endswith(".attention.g_proj.weight"):
150
+ assert bid is not None
151
+ tensor = gguf.MODEL_TENSOR.ATTN_GATE if self.is_full_attention(bid) else gguf.MODEL_TENSOR.SSM_G_A
152
+ name = self.format_tensor_name(tensor, bid)
153
+
154
+ if ".mlp.experts." in name:
155
+ n_experts = self.hparams["num_experts"]
156
+ assert bid is not None
157
+
158
+ if self._experts is None:
159
+ self._experts = [{} for _ in range(self.block_count)]
160
+
161
+ self._experts[bid][name] = data_torch
162
+ if len(self._experts[bid]) >= n_experts * 3:
163
+ for weight_name in ("down_proj", "gate_proj", "up_proj"):
164
+ tensors = []
165
+ for expert_id in range(n_experts):
166
+ expert_name = f"model.layers.{bid}.mlp.experts.{expert_id}.{weight_name}.weight"
167
+ tensors.append(self._experts[bid].pop(expert_name))
168
+ merged_name = f"model.layers.{bid}.mlp.experts.{weight_name}.weight"
169
+ yield from super().modify_tensors(torch.stack(tensors, dim=0), merged_name, bid)
170
+ return
171
+
172
+ if name.endswith(".attention.kv_b_proj.weight"):
173
+ assert bid is not None
174
+ n_head = self.hparams["num_attention_heads"]
175
+ v_head_dim = self.hparams["v_head_dim"]
176
+ qk_nope_head_dim = self.hparams["qk_nope_head_dim"]
177
+ assert data_torch.shape[0] == n_head * (v_head_dim + qk_nope_head_dim)
178
+ kv_b = data_torch.view(n_head, v_head_dim + qk_nope_head_dim, data_torch.shape[-1])
179
+ k_b, v_b = torch.split(kv_b, [qk_nope_head_dim, v_head_dim], dim=1)
180
+ name_k = self.format_tensor_name(gguf.MODEL_TENSOR.ATTN_K_B, bid)
181
+ name_v = self.format_tensor_name(gguf.MODEL_TENSOR.ATTN_V_B, bid)
182
+ yield from super().modify_tensors(k_b.transpose(1, 2), name_k, bid)
183
+ yield from super().modify_tensors(v_b, name_v, bid)
184
+ return
185
+
186
+ yield from super().modify_tensors(data_torch, name, bid)
187
+
188
+ def prepare_tensors(self):
189
+ super().prepare_tensors()
190
+ if self._experts is not None:
191
+ experts = [name for layer in self._experts for name in layer]
192
+ if experts:
193
+ raise ValueError(f"Unprocessed experts: {experts}")
conversion/base.py ADDED
The diff for this file is too large to render. See raw diff
 
conversion/bert.py ADDED
@@ -0,0 +1,641 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import os
5
+
6
+ from pathlib import Path
7
+ from typing import Any, Callable, Iterable, TYPE_CHECKING
8
+
9
+ import torch
10
+
11
+ if TYPE_CHECKING:
12
+ from torch import Tensor
13
+
14
+ from .base import ModelBase, SentencePieceTokenTypes, TextModel, gguf, logger
15
+
16
+
17
+ @ModelBase.register("BertModel", "BertForMaskedLM", "CamembertModel", "BertForSequenceClassification")
18
+ @ModelBase.example("BAAI/bge-small-en-v1.5", "dangvantuan/sentence-camembert-base")
19
+ class BertModel(TextModel):
20
+ model_arch = gguf.MODEL_ARCH.BERT
21
+
22
+ def __init__(self, *args, **kwargs):
23
+ super().__init__(*args, **kwargs)
24
+ self.vocab_size = None
25
+
26
+ if cls_out_labels := self.hparams.get("id2label"):
27
+ if len(cls_out_labels) == 2 and cls_out_labels[0] == "LABEL_0":
28
+ # Remove dummy labels added by AutoConfig
29
+ cls_out_labels = None
30
+ self.cls_out_labels = cls_out_labels
31
+
32
+ def set_gguf_parameters(self):
33
+ super().set_gguf_parameters()
34
+ self.gguf_writer.add_causal_attention(False)
35
+ self._try_set_pooling_type()
36
+
37
+ if self.cls_out_labels:
38
+ self.gguf_writer.add_classifier_output_labels([v for k, v in sorted(self.cls_out_labels.items())])
39
+
40
+ def set_vocab(self):
41
+ tokens, toktypes, tokpre = self.get_vocab_base()
42
+ self.vocab_size = len(tokens)
43
+
44
+ # we need this to validate the size of the token_type embeddings
45
+ # though currently we are passing all zeros to the token_type embeddings
46
+ # "Sequence A" or "Sequence B"
47
+ self.gguf_writer.add_token_type_count(self.hparams.get("type_vocab_size", 1))
48
+
49
+ # convert to phantom space vocab
50
+ def phantom(tok, toktype):
51
+ if toktype == gguf.TokenType.CONTROL:
52
+ return tok
53
+ if tok.startswith("##"):
54
+ return tok[2:]
55
+ return "\u2581" + tok
56
+ assert len(tokens) == len(toktypes)
57
+ tokens = list(map(phantom, tokens, toktypes))
58
+
59
+ # add vocab to gguf
60
+ self.gguf_writer.add_tokenizer_model("bert")
61
+ self.gguf_writer.add_tokenizer_pre(tokpre)
62
+ self.gguf_writer.add_token_list(tokens)
63
+ self.gguf_writer.add_token_types(toktypes)
64
+
65
+ # handle special tokens
66
+ special_vocab = gguf.SpecialVocab(self.dir_model, n_vocab=len(tokens))
67
+ special_vocab.add_to_gguf(self.gguf_writer)
68
+
69
+ @classmethod
70
+ def filter_tensors(cls, item: tuple[str, Callable[[], Tensor]]) -> tuple[str, Callable[[], Tensor]] | None:
71
+ name, gen = item
72
+
73
+ if name.startswith("bert."):
74
+ name = name[5:]
75
+
76
+ if name.endswith(".gamma"):
77
+ name = name[:-6] + ".weight"
78
+
79
+ if name.endswith(".beta"):
80
+ name = name[:-5] + ".bias"
81
+
82
+ # we are only using BERT for embeddings so we don't need the pooling layer
83
+ if name in ("embeddings.position_ids", "pooler.dense.weight", "pooler.dense.bias"):
84
+ return None
85
+
86
+ if name.startswith("cls.predictions"):
87
+ return None
88
+
89
+ if name.startswith("cls.seq_relationship"):
90
+ return None
91
+
92
+ return super().filter_tensors((name, gen))
93
+
94
+ def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]:
95
+ if self.cls_out_labels:
96
+ # For BertForSequenceClassification (direct projection layer)
97
+ if name == "classifier.weight":
98
+ name = "classifier.out_proj.weight"
99
+
100
+ if name == "classifier.bias":
101
+ name = "classifier.out_proj.bias"
102
+
103
+ yield from super().modify_tensors(data_torch, name, bid)
104
+
105
+ def _xlmroberta_tokenizer_init(self) -> None:
106
+ # we need the pad_token_id to know how to chop down position_embd matrix
107
+ if (pad_token_id := self.hparams.get("pad_token_id")) is not None:
108
+ self._position_offset = 1 + pad_token_id
109
+ if "max_position_embeddings" in self.hparams:
110
+ self.hparams["max_position_embeddings"] -= self._position_offset
111
+ else:
112
+ self._position_offset = None
113
+
114
+ def _xlmroberta_set_vocab(self) -> None:
115
+ # to avoid TypeError: Descriptors cannot be created directly
116
+ # exception when importing sentencepiece_model_pb2
117
+ os.environ["PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION"] = "python"
118
+ from sentencepiece import SentencePieceProcessor
119
+ from sentencepiece import sentencepiece_model_pb2 as model
120
+
121
+ tokenizer_path = self.dir_model / 'sentencepiece.bpe.model'
122
+
123
+ tokenizer_json = {}
124
+ tokenizer_config_json = {}
125
+ if not tokenizer_path.is_file():
126
+ tokenizer_path = self.dir_model / 'tokenizer.json'
127
+ tokenizer_config_path = self.dir_model / 'tokenizer_config.json'
128
+
129
+ if not tokenizer_path.is_file():
130
+ raise FileNotFoundError(f"File not found: {tokenizer_path}")
131
+
132
+ from base64 import b64decode
133
+ from transformers import AutoTokenizer
134
+ tokenizer = AutoTokenizer.from_pretrained(self.dir_model)
135
+
136
+ with open(tokenizer_path, "r", encoding="utf-8") as fp:
137
+ tokenizer_json = json.load(fp)
138
+
139
+ if tokenizer_config_path.is_file():
140
+ with open(tokenizer_config_path, "r", encoding="utf-8") as fp:
141
+ tokenizer_config_json = json.load(fp)
142
+
143
+ add_prefix = tokenizer.add_prefix_space # ty: ignore[unresolved-attribute]
144
+ remove_whitespaces = tokenizer.clean_up_tokenization_spaces # ty: ignore[unresolved-attribute]
145
+ precompiled_charsmap = b64decode(tokenizer_json["normalizer"]["precompiled_charsmap"])
146
+
147
+ vocab_size = max(self.hparams.get("vocab_size", 0), tokenizer.vocab_size) # ty: ignore[unresolved-attribute]
148
+ else:
149
+ sentencepiece_model = model.ModelProto() # pyright: ignore[reportAttributeAccessIssue] # ty: ignore[unresolved-attribute]
150
+ sentencepiece_model.ParseFromString(open(tokenizer_path, "rb").read())
151
+ assert sentencepiece_model.trainer_spec.model_type == 1 # UNIGRAM
152
+
153
+ add_prefix = sentencepiece_model.normalizer_spec.add_dummy_prefix
154
+ remove_whitespaces = sentencepiece_model.normalizer_spec.remove_extra_whitespaces
155
+ precompiled_charsmap = sentencepiece_model.normalizer_spec.precompiled_charsmap
156
+
157
+ tokenizer = SentencePieceProcessor()
158
+ tokenizer.LoadFromFile(str(tokenizer_path))
159
+
160
+ vocab_size = max(self.hparams.get("vocab_size", 0), tokenizer.vocab_size())
161
+
162
+ tokens: list[bytes] = [f"[PAD{i}]".encode("utf-8") for i in range(vocab_size)]
163
+ scores: list[float] = [-10000.0] * vocab_size
164
+ toktypes: list[int] = [SentencePieceTokenTypes.UNUSED] * vocab_size
165
+
166
+ if isinstance(tokenizer, SentencePieceProcessor):
167
+ for token_id in range(tokenizer.vocab_size()):
168
+ piece = tokenizer.IdToPiece(token_id)
169
+ text = piece.encode("utf-8")
170
+ score = tokenizer.GetScore(token_id)
171
+
172
+ toktype = SentencePieceTokenTypes.NORMAL
173
+ if tokenizer.IsUnknown(token_id):
174
+ toktype = SentencePieceTokenTypes.UNKNOWN
175
+ elif tokenizer.IsControl(token_id):
176
+ toktype = SentencePieceTokenTypes.CONTROL
177
+ elif tokenizer.IsUnused(token_id):
178
+ toktype = SentencePieceTokenTypes.UNUSED
179
+ elif tokenizer.IsByte(token_id):
180
+ toktype = SentencePieceTokenTypes.BYTE
181
+
182
+ tokens[token_id] = text
183
+ scores[token_id] = score
184
+ toktypes[token_id] = toktype
185
+ else:
186
+ added_vocab = tokenizer.get_added_vocab() # ty: ignore[unresolved-attribute]
187
+ unk_token = tokenizer_config_json.get("unk_token")
188
+ unk_token_id = added_vocab.get(unk_token, tokenizer_json["model"].get("unk_id", 3)) # ty: ignore[no-matching-overload]
189
+
190
+ for token_id in range(tokenizer.vocab_size): # ty: ignore[unresolved-attribute]
191
+ piece = tokenizer._convert_id_to_token(token_id) # ty: ignore[unresolved-attribute]
192
+ if (piece := tokenizer._convert_id_to_token(token_id)) is not None: # ty: ignore[unresolved-attribute]
193
+ text = piece.encode("utf-8")
194
+ score = tokenizer_json["model"]["vocab"][token_id][1]
195
+
196
+ toktype = SentencePieceTokenTypes.NORMAL
197
+ if token_id == unk_token_id:
198
+ toktype = SentencePieceTokenTypes.UNKNOWN
199
+ elif token_id in tokenizer.all_special_ids: # ty: ignore[unresolved-attribute]
200
+ toktype = SentencePieceTokenTypes.CONTROL
201
+ elif token_id in added_vocab.values():
202
+ toktype = SentencePieceTokenTypes.USER_DEFINED
203
+ # No reliable way to detect this, but jina doesn't have any
204
+ # elif tokenizer.IsByte(token_id):
205
+ # toktype = SentencePieceTokenTypes.BYTE
206
+
207
+ tokens[token_id] = text
208
+ scores[token_id] = score
209
+ toktypes[token_id] = toktype
210
+
211
+ if isinstance(tokenizer, SentencePieceProcessor):
212
+ # realign tokens (see HF tokenizer code)
213
+ tokens = [b'<s>', b'<pad>', b'</s>', b'<unk>'] + tokens[3:-1]
214
+ scores = [0.0, 0.0, 0.0, 0.0] + scores[3:-1]
215
+ toktypes = [
216
+ SentencePieceTokenTypes.CONTROL,
217
+ SentencePieceTokenTypes.CONTROL,
218
+ SentencePieceTokenTypes.CONTROL,
219
+ SentencePieceTokenTypes.UNKNOWN,
220
+ ] + toktypes[3:-1]
221
+
222
+ if self.model_arch == gguf.MODEL_ARCH.NOMIC_BERT_MOE:
223
+ # Add mask token missing from sentencepiece.bpe.model
224
+ tokens[250001] = b'<mask>'
225
+ scores[250001] = 0.0
226
+ toktypes[250001] = SentencePieceTokenTypes.CONTROL
227
+
228
+ self.gguf_writer.add_tokenizer_model("t5")
229
+ self.gguf_writer.add_tokenizer_pre("default")
230
+ self.gguf_writer.add_token_list(tokens)
231
+ self.gguf_writer.add_token_scores(scores)
232
+ self.gguf_writer.add_token_types(toktypes)
233
+ self.gguf_writer.add_add_space_prefix(add_prefix)
234
+ self.gguf_writer.add_token_type_count(self.hparams.get("type_vocab_size", 1))
235
+ self.gguf_writer.add_remove_extra_whitespaces(remove_whitespaces)
236
+ if precompiled_charsmap:
237
+ self.gguf_writer.add_precompiled_charsmap(precompiled_charsmap)
238
+
239
+ special_vocab = gguf.SpecialVocab(self.dir_model, n_vocab=len(tokens))
240
+ special_vocab.add_to_gguf(self.gguf_writer)
241
+
242
+
243
+ @ModelBase.register("DistilBertModel", "DistilBertForMaskedLM", "DistilBertForSequenceClassification")
244
+ @ModelBase.example("distilbert/distilbert-base-uncased")
245
+ class DistilBertModel(BertModel):
246
+ model_arch = gguf.MODEL_ARCH.BERT
247
+
248
+ def set_gguf_parameters(self):
249
+ self.gguf_writer.add_layer_norm_eps(1e-12)
250
+ logger.info("gguf: layer norm epsilon = 1e-12")
251
+ super().set_gguf_parameters()
252
+
253
+ @classmethod
254
+ def filter_tensors(cls, item: tuple[str, Callable[[], Tensor]]) -> tuple[str, Callable[[], Tensor]] | None:
255
+ name, gen = item
256
+
257
+ if name.startswith("distilbert."):
258
+ name = name[11:]
259
+
260
+ # These layers act as MLM head, so we don't need them
261
+ if name.startswith("vocab_"):
262
+ return None
263
+
264
+ return super().filter_tensors((name, gen))
265
+
266
+
267
+ @ModelBase.register("RobertaModel", "RobertaForSequenceClassification")
268
+ @ModelBase.example("sentence-transformers/stsb-roberta-base")
269
+ class RobertaModel(BertModel):
270
+ model_arch = gguf.MODEL_ARCH.BERT
271
+
272
+ def __init__(self, *args, **kwargs):
273
+ super().__init__(*args, **kwargs)
274
+
275
+ # we need the pad_token_id to know how to chop down position_embd matrix
276
+ if (pad_token_id := self.hparams.get("pad_token_id")) is not None:
277
+ self._position_offset = 1 + pad_token_id
278
+ if "max_position_embeddings" in self.hparams:
279
+ self.hparams["max_position_embeddings"] -= self._position_offset
280
+ else:
281
+ self._position_offset = None
282
+
283
+ def set_vocab(self):
284
+ """Support BPE tokenizers for roberta models"""
285
+ bpe_tok_path = self.dir_model / "tokenizer.json"
286
+ if bpe_tok_path.exists():
287
+ self._set_vocab_gpt2()
288
+
289
+ # we need this to validate the size of the token_type embeddings
290
+ # though currently we are passing all zeros to the token_type embeddings
291
+ # "Sequence A" or "Sequence B"
292
+ self.gguf_writer.add_token_type_count(self.hparams.get("type_vocab_size", 1))
293
+
294
+ else:
295
+ return super().set_vocab()
296
+
297
+ @classmethod
298
+ def filter_tensors(cls, item: tuple[str, Callable[[], Tensor]]) -> tuple[str, Callable[[], Tensor]] | None:
299
+ name, gen = item
300
+
301
+ # if name starts with "roberta.", remove the prefix
302
+ # e.g. https://huggingface.co/BAAI/bge-reranker-v2-m3/tree/main
303
+ if name.startswith("roberta."):
304
+ name = name[8:]
305
+
306
+ return super().filter_tensors((name, gen))
307
+
308
+ def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]:
309
+ # position embeddings start at pad_token_id + 1, so just chop down the weight tensor
310
+ if name == "embeddings.position_embeddings.weight":
311
+ if self._position_offset is not None:
312
+ data_torch = data_torch[self._position_offset:,:]
313
+
314
+ yield from super().modify_tensors(data_torch, name, bid)
315
+
316
+
317
+ @ModelBase.register("NomicBertModel")
318
+ @ModelBase.example("nomic-ai/nomic-embed-text-v1.5")
319
+ class NomicBertModel(BertModel):
320
+ model_arch = gguf.MODEL_ARCH.BERT
321
+
322
+ def __init__(self, dir_model: Path, ftype: gguf.LlamaFileType, fname_out: Path, **kwargs: Any):
323
+ hparams = kwargs.pop("hparams", None)
324
+ if hparams is None:
325
+ hparams = ModelBase.load_hparams(dir_model, False)
326
+
327
+ self.is_moe = bool(hparams.get("moe_every_n_layers"))
328
+ self.model_arch = gguf.MODEL_ARCH.NOMIC_BERT_MOE if self.is_moe else gguf.MODEL_ARCH.NOMIC_BERT
329
+
330
+ super().__init__(dir_model, ftype, fname_out, hparams=hparams, **kwargs)
331
+
332
+ self._tokenizer_is_xlmroberta = self._is_tokenizer_xlmroberta()
333
+ if self._tokenizer_is_xlmroberta:
334
+ self._xlmroberta_tokenizer_init()
335
+
336
+ npos, mtp = self.hparams["n_positions"], self.hparams.get("max_trained_positions", 2048)
337
+ if npos == 8192 and mtp == 2048:
338
+ self.hparams["n_positions"] = 2048 # nomic-embed-text v1 and v1.5 are trained for 2048 tokens.
339
+ elif npos == 2048 and mtp == 2048:
340
+ self.hparams["n_positions"] = 512 # nomic-embed-text-v2-moe is trained for 512 tokens.
341
+ else:
342
+ raise ValueError(f"unrecognized parameters: n_positions={npos}, max_trained_positions={mtp}")
343
+
344
+ assert self.hparams["activation_function"] == "gelu" if self.is_moe else "swiglu"
345
+
346
+ # this doesn't do anything in the HF version
347
+ assert self.hparams["causal"] is False
348
+ # no bias tensors unless MoE
349
+ assert self.hparams["qkv_proj_bias"] == self.is_moe
350
+ assert self.hparams["mlp_fc1_bias"] == self.is_moe
351
+ assert self.hparams["mlp_fc2_bias"] == self.is_moe
352
+
353
+ # norm at end of layer
354
+ assert self.hparams["prenorm"] is False
355
+ # standard RoPE
356
+ assert self.hparams["rotary_emb_fraction"] == 1.0
357
+ assert self.hparams["rotary_emb_interleaved"] is False
358
+ assert self.hparams["rotary_emb_scale_base"] is None
359
+
360
+ def set_vocab(self) -> None:
361
+ if self._tokenizer_is_xlmroberta:
362
+ return self._xlmroberta_set_vocab()
363
+ return super().set_vocab()
364
+
365
+ @classmethod
366
+ def filter_tensors(cls, item: tuple[str, Callable[[], Tensor]]) -> tuple[str, Callable[[], Tensor]] | None:
367
+ name, gen = item
368
+
369
+ # If the tensor is an experts bias tensor, skip it.
370
+ if "mlp.experts.bias" in name:
371
+ return None
372
+
373
+ return super().filter_tensors(item)
374
+
375
+ def modify_tensors(self, data_torch: torch.Tensor, name: str, bid: int | None) -> Iterable[tuple[str, torch.Tensor]]:
376
+ if "mlp.experts.mlp.w1" in name:
377
+ n_experts = self.find_hparam(["num_local_experts", "num_experts"])
378
+ data_torch = data_torch.view(n_experts, self.hparams["n_inner"], self.hparams["n_embd"])
379
+ name += ".weight"
380
+
381
+ if "mlp.experts.mlp.w2" in name:
382
+ n_experts = self.find_hparam(["num_local_experts", "num_experts"])
383
+ data_torch = data_torch.view(n_experts, self.hparams["n_inner"], self.hparams["n_embd"])
384
+ data_torch = data_torch.transpose(1, 2)
385
+ name += ".weight"
386
+
387
+ yield from super().modify_tensors(data_torch, name, bid)
388
+
389
+ def set_gguf_parameters(self):
390
+ super().set_gguf_parameters()
391
+ if self.is_moe:
392
+ self.gguf_writer.add_moe_every_n_layers(self.hparams["moe_every_n_layers"])
393
+ self.gguf_writer.add_expert_used_count(self.hparams["moe_top_k"])
394
+
395
+ def _is_tokenizer_xlmroberta(self) -> bool:
396
+ with open(self.dir_model / "tokenizer.json") as f:
397
+ tokenizer_json = json.load(f)
398
+ toktyp = tokenizer_json["model"]["type"]
399
+ if toktyp == "Unigram":
400
+ return True
401
+ if toktyp == "WordPiece":
402
+ return False
403
+ raise ValueError(f"unknown tokenizer: {toktyp}")
404
+
405
+
406
+ @ModelBase.register("NeoBERT", "NeoBERTLMHead", "NeoBERTForSequenceClassification")
407
+ @ModelBase.example("chandar-lab/NeoBERT")
408
+ class NeoBert(BertModel):
409
+ model_arch = gguf.MODEL_ARCH.NEO_BERT
410
+
411
+ def set_gguf_parameters(self):
412
+ super().set_gguf_parameters()
413
+
414
+ # NeoBERT uses 2/3 of the intermediate size as feed forward length
415
+ self.gguf_writer.add_feed_forward_length(int(2 * self.hparams["intermediate_size"] / 3))
416
+ self.gguf_writer.add_rope_freq_base(10000.0) # default value for NeoBERT
417
+ self.gguf_writer.add_rope_scaling_type(gguf.RopeScalingType.NONE)
418
+
419
+ f_rms_eps = self.hparams.get("norm_eps", 1e-6) # default value for NeoBERT
420
+ self.gguf_writer.add_layer_norm_rms_eps(f_rms_eps)
421
+ logger.info(f"gguf: rms norm epsilon = {f_rms_eps}")
422
+
423
+ self.gguf_writer.add_pooling_type(gguf.PoolingType.CLS) # https://huggingface.co/chandar-lab/NeoBERT#how-to-use
424
+
425
+ @classmethod
426
+ def filter_tensors(cls, item: tuple[str, Callable[[], Tensor]]) -> tuple[str, Callable[[], Tensor]] | None:
427
+ name, gen = item
428
+
429
+ if name.startswith("decoder."):
430
+ return None
431
+
432
+ if name.startswith("model."):
433
+ name = name[6:]
434
+
435
+ return super().filter_tensors((name, gen))
436
+
437
+
438
+ @ModelBase.register("EuroBertModel", "JinaEmbeddingsV5Model")
439
+ @ModelBase.example("hf-tiny-v2/tiny-random-EuroBertModel", "jinaai/jina-embeddings-v5-text-nano")
440
+ class EuroBertModel(TextModel):
441
+ model_arch = gguf.MODEL_ARCH.EUROBERT
442
+
443
+ def set_vocab(self):
444
+ self.gguf_writer.add_add_bos_token(False)
445
+ self._set_vocab_gpt2()
446
+
447
+ def set_gguf_parameters(self):
448
+ super().set_gguf_parameters()
449
+
450
+ # EuroBert is bidirectional (encoder)
451
+ self.gguf_writer.add_causal_attention(False)
452
+
453
+ self.gguf_writer.add_rope_scaling_type(gguf.RopeScalingType.NONE)
454
+
455
+ self._try_set_pooling_type()
456
+
457
+ @classmethod
458
+ def filter_tensors(cls, item: tuple[str, Callable[[], Tensor]]) -> tuple[str, Callable[[], Tensor]] | None:
459
+ name, gen = item
460
+
461
+ if name.startswith("model."):
462
+ name = name[6:]
463
+
464
+ return super().filter_tensors((name, gen))
465
+
466
+
467
+ @ModelBase.register("XLMRobertaModel", "XLMRobertaForSequenceClassification")
468
+ @ModelBase.example("BAAI/bge-m3")
469
+ class XLMRobertaModel(BertModel):
470
+ model_arch = gguf.MODEL_ARCH.BERT
471
+ _lora_files = {}
472
+ _lora_names = []
473
+
474
+ def __init__(self, dir_model: Path, ftype: gguf.LlamaFileType, fname_out: Path, **kwargs: Any):
475
+ hparams = kwargs.pop("hparams", None)
476
+ if hparams is None:
477
+ hparams = ModelBase.load_hparams(dir_model, False)
478
+
479
+ if lora_names := hparams.get("lora_adaptations"):
480
+ self._lora_names = lora_names
481
+ self.model_arch = gguf.MODEL_ARCH.JINA_BERT_V3
482
+
483
+ super().__init__(dir_model, ftype, fname_out, hparams=hparams, **kwargs)
484
+ self._xlmroberta_tokenizer_init()
485
+
486
+ def generate_extra_tensors(self) -> Iterable[tuple[str, Tensor]]:
487
+ if self._lora_names:
488
+ for name in self._lora_names:
489
+ fname = self.add_prefix_to_filename(self.fname_out, f"lora-{name}-")
490
+ self._lora_files[name] = gguf.GGUFWriter(fname, arch=gguf.MODEL_ARCH_NAMES[self.model_arch], endianess=self.endianess, use_temp_file=self.use_temp_file, dry_run=self.dry_run)
491
+
492
+ return super().generate_extra_tensors()
493
+
494
+ def set_type(self):
495
+ for lora_writer in self._lora_files.values():
496
+ lora_writer.add_type(gguf.GGUFType.ADAPTER)
497
+ lora_writer.add_string(gguf.Keys.Adapter.TYPE, "lora")
498
+ super().set_type()
499
+
500
+ def set_vocab(self):
501
+ self._xlmroberta_set_vocab()
502
+
503
+ @classmethod
504
+ def filter_tensors(cls, item: tuple[str, Callable[[], Tensor]]) -> tuple[str, Callable[[], Tensor]] | None:
505
+ name, gen = item
506
+
507
+ # if name starts with "roberta.", remove the prefix
508
+ # e.g. https://huggingface.co/BAAI/bge-reranker-v2-m3/tree/main
509
+ if name.startswith("roberta."):
510
+ name = name[8:]
511
+
512
+ # jina-embeddings-v3
513
+ if ".parametrizations." in name:
514
+ name = name.replace(".parametrizations.", ".")
515
+ if name.endswith(".original"):
516
+ name = name[:-9]
517
+
518
+ return super().filter_tensors((name, gen))
519
+
520
+ def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]:
521
+ # position embeddings start at pad_token_id + 1, so just chop down the weight tensor
522
+ if name == "embeddings.position_embeddings.weight":
523
+ if self._position_offset is not None:
524
+ data_torch = data_torch[self._position_offset:,:]
525
+
526
+ if name.endswith(".0.lora_A") or name.endswith(".0.lora_B"):
527
+ if name.startswith("pooler.dense"):
528
+ return
529
+
530
+ num_loras = data_torch.size(0)
531
+ assert num_loras == len(self._lora_names)
532
+
533
+ # Split out each LoRA in their own GGUF
534
+ for i, lora_writer in enumerate(self._lora_files.values()):
535
+ new_name = self.map_tensor_name(name[:-9]) + name[-7:].lower()
536
+ data = data_torch[i, :, :]
537
+ # Transpose/flip token_embd/types into correct shape
538
+ if new_name == "token_embd.weight.lora_b":
539
+ data = data.T
540
+ elif new_name.startswith("token_types.weight."):
541
+ new_name = new_name[:-1] + ("a" if new_name[-1:] == "b" else "b")
542
+ lora_writer.add_tensor(new_name, data.float().numpy(), raw_dtype=gguf.GGMLQuantizationType.F32)
543
+
544
+ return
545
+
546
+ yield from super().modify_tensors(data_torch, name, bid)
547
+
548
+ def set_gguf_parameters(self):
549
+ super().set_gguf_parameters()
550
+
551
+ # jina-embeddings-v3
552
+ lora_alpha = self.hparams.get("lora_alpha")
553
+ if lora_prompt_prefixes := self.hparams.get("task_instructions"):
554
+ assert self._lora_files and all(lora_name in lora_prompt_prefixes for lora_name in self._lora_files.keys())
555
+ for lora_name, lora_writer in self._lora_files.items():
556
+ lora_writer.add_float32(gguf.Keys.Adapter.LORA_ALPHA, lora_alpha if lora_alpha is not None else 1.0)
557
+ lora_writer.add_string(gguf.Keys.Adapter.LORA_TASK_NAME, lora_name)
558
+ if lora_prompt_prefixes:
559
+ lora_writer.add_string(gguf.Keys.Adapter.LORA_PROMPT_PREFIX, lora_prompt_prefixes[lora_name])
560
+
561
+ def write(self):
562
+ super().write()
563
+ for lora_writer in self._lora_files.values():
564
+ lora_writer.write_header_to_file()
565
+ lora_writer.write_kv_data_to_file()
566
+ lora_writer.write_tensors_to_file(progress=True)
567
+ lora_writer.close()
568
+
569
+
570
+ @ModelBase.register("JinaBertModel", "JinaBertForMaskedLM")
571
+ @ModelBase.example("jinaai/jina-embeddings-v2-base-en")
572
+ class JinaBertV2Model(BertModel):
573
+ model_arch = gguf.MODEL_ARCH.JINA_BERT_V2
574
+
575
+ def set_vocab(self):
576
+ tokenizer_class = 'BertTokenizer'
577
+ with open(self.dir_model / "tokenizer_config.json", "r", encoding="utf-8") as f:
578
+ tokenizer_class = json.load(f)['tokenizer_class']
579
+
580
+ if tokenizer_class == 'BertTokenizer':
581
+ super().set_vocab()
582
+ elif tokenizer_class == 'RobertaTokenizer':
583
+ pre_tokenizer_type = None
584
+ tokenizer_json_path = self.dir_model / "tokenizer.json"
585
+ if tokenizer_json_path.is_file():
586
+ with open(tokenizer_json_path, "r", encoding="utf-8") as f:
587
+ pre_tokenizer_type = json.load(f).get("pre_tokenizer", {}).get("type")
588
+
589
+ if pre_tokenizer_type == "Whitespace":
590
+ self._set_vocab_whitespace()
591
+ else:
592
+ self._set_vocab_gpt2()
593
+ self.gguf_writer.add_token_type_count(2)
594
+ else:
595
+ raise NotImplementedError(f'Tokenizer {tokenizer_class} is not supported for JinaBertModel')
596
+
597
+
598
+ @ModelBase.register("ModernBertModel", "ModernBertForMaskedLM", "ModernBertForSequenceClassification")
599
+ @ModelBase.example("answerdotai/ModernBERT-base")
600
+ class ModernBertModel(BertModel):
601
+ model_arch = gguf.MODEL_ARCH.MODERN_BERT
602
+
603
+ def set_vocab(self):
604
+ self.gguf_writer.add_add_bos_token(True)
605
+ self.gguf_writer.add_add_eos_token(True)
606
+ self.gguf_writer.add_add_sep_token(True)
607
+ self._set_vocab_gpt2()
608
+
609
+ def set_gguf_parameters(self):
610
+ super().set_gguf_parameters()
611
+ self.gguf_writer.add_sliding_window(self.hparams["local_attention"])
612
+ if (sliding_window_pattern := self.hparams.get("global_attn_every_n_layers")) is not None:
613
+ self.gguf_writer.add_sliding_window_pattern(sliding_window_pattern)
614
+ self.gguf_writer.add_rope_scaling_type(gguf.RopeScalingType.NONE)
615
+ self.gguf_writer.add_vocab_size(self.hparams["vocab_size"])
616
+ # FFN activation: ModernBert uses a GLU pair (ffn_up output is 2*n_ff). The
617
+ # original ModernBERT uses GELU (-> GeGLU); some derivatives such as IBM
618
+ # Granite Embedding 97m R2 use SiLU (-> SwiGLU). Persist this so the
619
+ # llama.cpp graph can pick the matching activation.
620
+ if hidden_act := self.hparams.get("hidden_activation"):
621
+ self.gguf_writer.add_hidden_act(hidden_act)
622
+
623
+ @classmethod
624
+ def filter_tensors(cls, item: tuple[str, Callable[[], Tensor]]) -> tuple[str, Callable[[], Tensor]] | None:
625
+ name, gen = item
626
+
627
+ if name.startswith("model."):
628
+ name = name[6:]
629
+
630
+ return super().filter_tensors((name, gen))
631
+
632
+ def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]:
633
+ if self.cls_out_labels:
634
+ # For BertForSequenceClassification (direct projection layer)
635
+ if name == "classifier.weight":
636
+ name = "classifier.out_proj.weight"
637
+
638
+ if name == "classifier.bias":
639
+ name = "classifier.out_proj.bias"
640
+
641
+ yield from super().modify_tensors(data_torch, name, bid)
conversion/bitnet.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import Iterable, TYPE_CHECKING
4
+
5
+ if TYPE_CHECKING:
6
+ from torch import Tensor
7
+
8
+ from .base import ModelBase, TextModel, gguf
9
+
10
+
11
+ @ModelBase.register("BitnetForCausalLM", "BitNetForCausalLM")
12
+ @ModelBase.example("microsoft/bitnet-b1.58-2B-4T")
13
+ class BitnetModel(TextModel):
14
+ model_arch = gguf.MODEL_ARCH.BITNET
15
+
16
+ def set_vocab(self):
17
+ self._set_vocab_sentencepiece()
18
+
19
+ def set_gguf_parameters(self):
20
+ super().set_gguf_parameters()
21
+ self.gguf_writer.add_rope_scaling_type(gguf.RopeScalingType.LINEAR)
22
+ self.gguf_writer.add_rope_scaling_factor(1.0)
23
+
24
+ def weight_quant(self, weight: Tensor) -> Tensor:
25
+ dtype = weight.dtype
26
+ weight = weight.float()
27
+ scale = weight.abs().mean().clamp(min=1e-5)
28
+ iscale = 1 / scale
29
+ # TODO: multiply by the scale directly instead of inverting it twice
30
+ # (this is also unnecessarily doubly inverted upstream)
31
+ # ref: https://huggingface.co/1bitLLM/bitnet_b1_58-3B/blob/af89e318d78a70802061246bf037199d2fb97020/utils_quant.py#L10
32
+ result = (weight * iscale).round().clamp(-1, 1) / iscale
33
+ return result.type(dtype)
34
+
35
+ def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]:
36
+ new_name = self.map_tensor_name(name)
37
+
38
+ if any(self.match_model_tensor_name(new_name, key, bid) for key in [
39
+ gguf.MODEL_TENSOR.ATTN_Q,
40
+ gguf.MODEL_TENSOR.ATTN_K,
41
+ gguf.MODEL_TENSOR.ATTN_V,
42
+ gguf.MODEL_TENSOR.ATTN_OUT,
43
+ gguf.MODEL_TENSOR.FFN_UP,
44
+ gguf.MODEL_TENSOR.FFN_DOWN,
45
+ gguf.MODEL_TENSOR.FFN_GATE,
46
+ ]):
47
+ # transform weight into 1/0/-1 (in fp32)
48
+ data_torch = self.weight_quant(data_torch)
49
+
50
+ yield from super().modify_tensors(data_torch, name, bid)
conversion/bloom.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import re
4
+
5
+ from typing import Iterable, TYPE_CHECKING
6
+
7
+ import torch
8
+
9
+ if TYPE_CHECKING:
10
+ from torch import Tensor
11
+
12
+ from .base import ModelBase, TextModel, gguf, logger
13
+
14
+
15
+ @ModelBase.register("BloomForCausalLM", "BloomModel")
16
+ @ModelBase.example("bigscience/bloom-560m")
17
+ class BloomModel(TextModel):
18
+ model_arch = gguf.MODEL_ARCH.BLOOM
19
+
20
+ def set_gguf_parameters(self):
21
+ n_embed = self.hparams.get("hidden_size", self.hparams.get("n_embed"))
22
+ n_head = self.hparams.get("n_head", self.hparams.get("num_attention_heads"))
23
+ assert n_head is not None
24
+ assert n_embed is not None
25
+ self.gguf_writer.add_context_length(self.hparams.get("seq_length", n_embed))
26
+ self.gguf_writer.add_embedding_length(n_embed)
27
+ self.gguf_writer.add_feed_forward_length(4 * n_embed)
28
+ self.gguf_writer.add_block_count(self.block_count)
29
+ self.gguf_writer.add_head_count(n_head)
30
+ self.gguf_writer.add_head_count_kv(n_head)
31
+ self.gguf_writer.add_layer_norm_eps(self.hparams["layer_norm_epsilon"])
32
+ self.gguf_writer.add_file_type(self.ftype)
33
+
34
+ def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]:
35
+ n_head = self.hparams.get("n_head", self.hparams.get("num_attention_heads"))
36
+ n_embed = self.hparams.get("hidden_size", self.hparams.get("n_embed"))
37
+ assert n_head is not None
38
+ assert n_embed is not None
39
+
40
+ name = re.sub(r'transformer\.', '', name)
41
+
42
+ if re.match(r"h\.\d+\.self_attention\.query_key_value\.weight", name):
43
+ # Map bloom-style qkv_linear to gpt-style qkv_linear
44
+ # bloom: https://github.com/huggingface/transformers/blob/main/src/transformers/models/bloom/modeling_bloom.py#L238-L252 # noqa
45
+ # gpt-2: https://github.com/huggingface/transformers/blob/main/src/transformers/models/gpt2/modeling_gpt2.py#L312 # noqa
46
+ qkv_weights = data_torch.reshape((n_head, 3, n_embed // n_head, n_embed))
47
+ data_torch = torch.cat(
48
+ (
49
+ qkv_weights[:, 0, :, :].reshape((-1, n_embed)),
50
+ qkv_weights[:, 1, :, :].reshape((-1, n_embed)),
51
+ qkv_weights[:, 2, :, :].reshape((-1, n_embed)),
52
+ ),
53
+ dim=0,
54
+ )
55
+ logger.info("re-format attention.linear_qkv.weight")
56
+ elif re.match(r"h\.\d+\.self_attention\.query_key_value\.bias", name):
57
+ qkv_bias = data_torch.reshape((n_head, 3, n_embed // n_head))
58
+ data_torch = torch.cat(
59
+ (
60
+ qkv_bias[:, 0, :].reshape((n_embed,)),
61
+ qkv_bias[:, 1, :].reshape((n_embed,)),
62
+ qkv_bias[:, 2, :].reshape((n_embed,)),
63
+ ),
64
+ dim=0,
65
+ )
66
+ logger.info("re-format attention.linear_qkv.bias")
67
+
68
+ yield from super().modify_tensors(data_torch, name, bid)
conversion/chameleon.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import Callable, Iterable, TYPE_CHECKING
4
+
5
+ if TYPE_CHECKING:
6
+ from torch import Tensor
7
+
8
+ from .base import ModelBase, TextModel, gguf
9
+
10
+ from .llama import LlamaModel
11
+
12
+
13
+ @ModelBase.register("ChameleonForConditionalGeneration")
14
+ @ModelBase.register("ChameleonForCausalLM") # obsolete
15
+ # [TAG_HF_EXAMPLE_GATED] facebook/chameleon-7b is gated
16
+ # [TAG_HF_EXAMPLE_MISSING]
17
+ class ChameleonModel(TextModel):
18
+ model_arch = gguf.MODEL_ARCH.CHAMELEON
19
+
20
+ def set_gguf_parameters(self):
21
+ super().set_gguf_parameters()
22
+ self.gguf_writer.add_swin_norm(self.hparams.get("swin_norm", False))
23
+
24
+ def set_vocab(self):
25
+ self._set_vocab_gpt2()
26
+
27
+ @classmethod
28
+ def filter_tensors(cls, item: tuple[str, Callable[[], Tensor]]) -> tuple[str, Callable[[], Tensor]] | None:
29
+ name, gen = item
30
+
31
+ # ignore image tokenizer for now
32
+ # TODO: image support for Chameleon
33
+ if name.startswith("model.vqmodel"):
34
+ return None
35
+
36
+ return super().filter_tensors(item)
37
+
38
+ def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]:
39
+ n_head = self.hparams["num_attention_heads"]
40
+ n_kv_head = self.hparams.get("num_key_value_heads")
41
+ hidden_dim = self.hparams.get("hidden_size")
42
+
43
+ if name.endswith(("q_proj.weight", "q_proj.bias")):
44
+ data_torch = LlamaModel.permute(data_torch, n_head, n_head)
45
+ if name.endswith(("k_proj.weight", "k_proj.bias")):
46
+ data_torch = LlamaModel.permute(data_torch, n_head, n_kv_head)
47
+ if name.endswith(("q_norm.weight", "q_norm.bias")):
48
+ data_torch = ChameleonModel._reverse_hf_permute(data_torch, n_head, hidden_dim)
49
+ if name.endswith(("k_norm.weight", "k_norm.bias")):
50
+ data_torch = ChameleonModel._reverse_hf_permute(data_torch, n_kv_head, hidden_dim)
51
+
52
+ yield from super().modify_tensors(data_torch, name, bid)
53
+
54
+ # see: https://github.com/huggingface/transformers/blob/72fb02c47dbbe1999ae105319f24631cad6e2e00/src/transformers/models/chameleon/convert_chameleon_weights_to_hf.py#L176-L203
55
+ @staticmethod
56
+ def _reverse_hf_permute(data_torch, n_heads, hidden_dim):
57
+ head_dim = hidden_dim // n_heads
58
+ data_torch = data_torch[0].view(2, head_dim // 2).t().reshape(1, -1)
59
+ data_torch = data_torch.repeat_interleave(n_heads, 0)
60
+ return data_torch
conversion/chatglm.py ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import Callable, TYPE_CHECKING
4
+
5
+ if TYPE_CHECKING:
6
+ from torch import Tensor
7
+
8
+ from .base import ModelBase, SentencePieceTokenTypes, TextModel, gguf
9
+
10
+
11
+ @ModelBase.register("GlmForCausalLM", "ChatGLMModel", "ChatGLMForConditionalGeneration")
12
+ @ModelBase.example("THUDM/chatglm3-6b", "zai-org/glm-4-9b-chat-hf")
13
+ class ChatGLMModel(TextModel):
14
+ model_arch = gguf.MODEL_ARCH.CHATGLM
15
+
16
+ def set_vocab_chatglm3(self):
17
+ dir_model = self.dir_model
18
+ hparams = self.hparams
19
+ tokens: list[bytes] = []
20
+ toktypes: list[int] = []
21
+ scores: list[float] = []
22
+
23
+ from transformers import AutoTokenizer
24
+ tokenizer = AutoTokenizer.from_pretrained(dir_model, trust_remote_code=True)
25
+ vocab_size = hparams.get("padded_vocab_size", len(tokenizer.get_vocab())) # ty: ignore[unresolved-attribute]
26
+ assert max(tokenizer.get_vocab().values()) < vocab_size # ty: ignore[unresolved-attribute]
27
+ role_special_tokens = ["<|system|>", "<|user|>", "<|assistant|>", "<|observation|>"]
28
+ special_tokens = ["[MASK]", "[gMASK]", "[sMASK]", "sop", "eop"] + role_special_tokens
29
+ for token_id in range(vocab_size):
30
+ piece = tokenizer._convert_id_to_token(token_id) # ty: ignore[unresolved-attribute]
31
+ if token_id == 0:
32
+ piece = "<unk>"
33
+ elif token_id == 1:
34
+ piece = "<bos>"
35
+ elif token_id == 2:
36
+ piece = "<eos>"
37
+
38
+ text = piece.encode("utf-8") # ty: ignore[unresolved-attribute]
39
+ score = 0.0
40
+ # Referencing the tokenizer Python implementation(https://huggingface.co/THUDM/chatglm3-6b/blob/main/tokenization_chatglm.py),
41
+ # it is only valid if it is less than tokenizer.tokenizer.sp_model.vocab_size()
42
+ if len(piece) != 0 and token_id < tokenizer.tokenizer.sp_model.vocab_size(): # ty: ignore[unresolved-attribute, invalid-argument-type]
43
+ score = tokenizer.tokenizer.sp_model.get_score(token_id) # ty: ignore[unresolved-attribute]
44
+
45
+ if token_id >= tokenizer.tokenizer.sp_model.vocab_size(): # ty: ignore[unresolved-attribute]
46
+ if piece in special_tokens:
47
+ toktype = SentencePieceTokenTypes.CONTROL
48
+ elif len(piece) == 0: # ty: ignore[invalid-argument-type]
49
+ text = f"[PAD{token_id}]".encode("utf-8")
50
+ toktype = SentencePieceTokenTypes.UNUSED
51
+ else:
52
+ toktype = SentencePieceTokenTypes.USER_DEFINED
53
+ tokens.append(text)
54
+ scores.append(score)
55
+ toktypes.append(toktype)
56
+ continue
57
+
58
+ toktype = SentencePieceTokenTypes.NORMAL
59
+ if tokenizer.tokenizer.sp_model.is_unknown(token_id): # ty: ignore[unresolved-attribute]
60
+ toktype = SentencePieceTokenTypes.UNKNOWN
61
+ elif tokenizer.tokenizer.sp_model.is_control(token_id): # ty: ignore[unresolved-attribute]
62
+ toktype = SentencePieceTokenTypes.CONTROL
63
+ elif tokenizer.tokenizer.sp_model.is_unused(token_id): # ty: ignore[unresolved-attribute]
64
+ toktype = SentencePieceTokenTypes.UNUSED
65
+ elif tokenizer.tokenizer.sp_model.is_byte(token_id): # ty: ignore[unresolved-attribute]
66
+ toktype = SentencePieceTokenTypes.BYTE
67
+
68
+ tokens.append(text)
69
+ scores.append(score)
70
+ toktypes.append(toktype)
71
+
72
+ self.gguf_writer.add_tokenizer_model("llama")
73
+ # glm3 needs prefix and suffix formatted as:
74
+ # prompt = "[gMASK]sop<|user|>\n" + prompt + "<|assistant|>"
75
+ self.gguf_writer.add_tokenizer_pre("chatglm-spm")
76
+ self.gguf_writer.add_token_list(tokens)
77
+ self.gguf_writer.add_token_scores(scores)
78
+ self.gguf_writer.add_token_types(toktypes)
79
+
80
+ special_vocab = gguf.SpecialVocab(self.dir_model, n_vocab=len(tokens))
81
+ special_vocab.add_to_gguf(self.gguf_writer)
82
+
83
+ @staticmethod
84
+ def token_bytes_to_string(b):
85
+ from transformers.convert_slow_tokenizer import bytes_to_unicode
86
+ byte_encoder = bytes_to_unicode()
87
+ return ''.join([byte_encoder[ord(char)] for char in b.decode('latin-1')])
88
+
89
+ @staticmethod
90
+ def bpe(mergeable_ranks: dict[bytes, int], token: bytes, max_rank: int | None = None) -> list[bytes]:
91
+ parts = [bytes([b]) for b in token]
92
+ while True:
93
+ min_idx = None
94
+ min_rank = None
95
+ for i, pair in enumerate(zip(parts[:-1], parts[1:])):
96
+ rank = mergeable_ranks.get(pair[0] + pair[1])
97
+ if rank is not None and (min_rank is None or rank < min_rank):
98
+ min_idx = i
99
+ min_rank = rank
100
+ if min_rank is None or (max_rank is not None and min_rank >= max_rank):
101
+ break
102
+ assert min_idx is not None
103
+ parts = parts[:min_idx] + [parts[min_idx] + parts[min_idx + 1]] + parts[min_idx + 2:]
104
+ return parts
105
+
106
+ def set_vocab(self):
107
+ if "THUDM/chatglm3-6b" in self.hparams.get("_name_or_path", ""):
108
+ self.set_vocab_chatglm3()
109
+ return
110
+
111
+ dir_model = self.dir_model
112
+ hparams = self.hparams
113
+ tokens: list[str] = []
114
+ toktypes: list[int] = []
115
+
116
+ from transformers import AutoTokenizer
117
+ tokenizer = AutoTokenizer.from_pretrained(dir_model, trust_remote_code=True)
118
+ vocab_size = hparams.get("padded_vocab_size",hparams["vocab_size"])
119
+ assert max(tokenizer.get_vocab().values()) < vocab_size # ty: ignore[unresolved-attribute]
120
+
121
+ tokens, toktypes, tokpre = self.get_vocab_base()
122
+ self.gguf_writer.add_tokenizer_model("gpt2")
123
+ self.gguf_writer.add_tokenizer_pre(tokpre)
124
+ self.gguf_writer.add_token_list(tokens)
125
+ self.gguf_writer.add_token_types(toktypes)
126
+ special_vocab = gguf.SpecialVocab(self.dir_model, load_merges=True)
127
+ # only add special tokens when they were not already loaded from config.json
128
+ special_vocab._set_special_token("eos", tokenizer.get_added_vocab()["<|endoftext|>"]) # ty: ignore[unresolved-attribute]
129
+ special_vocab._set_special_token("eot", tokenizer.get_added_vocab()["<|user|>"]) # ty: ignore[unresolved-attribute]
130
+ # this one is usually not in config.json anyway
131
+ special_vocab._set_special_token("unk", tokenizer.get_added_vocab()["<|endoftext|>"]) # ty: ignore[unresolved-attribute]
132
+ special_vocab.add_to_gguf(self.gguf_writer)
133
+
134
+ def set_gguf_parameters(self):
135
+ n_embed = self.hparams.get("hidden_size", self.hparams.get("n_embed"))
136
+ assert n_embed is not None
137
+ n_head = self.hparams.get("n_head", self.hparams.get("num_attention_heads"))
138
+ assert n_head is not None
139
+ n_head_kv = self.hparams.get("multi_query_group_num", self.hparams.get("num_key_value_heads", n_head))
140
+ self.gguf_writer.add_context_length(self.hparams.get("seq_length", n_embed))
141
+ self.gguf_writer.add_embedding_length(n_embed)
142
+ self.gguf_writer.add_feed_forward_length(self.hparams.get("ffn_hidden_size", self.hparams.get("intermediate_size", 4 * n_embed)))
143
+ self.gguf_writer.add_block_count(self.block_count)
144
+ self.gguf_writer.add_head_count(n_head)
145
+ self.gguf_writer.add_head_count_kv(n_head_kv)
146
+ self.gguf_writer.add_layer_norm_rms_eps(self.hparams.get("layernorm_epsilon",1e-5))
147
+ self.gguf_writer.add_file_type(self.ftype)
148
+ if "attention_dim" in self.hparams:
149
+ rope_dim = self.hparams["attention_dim"]
150
+ else:
151
+ rope_dim = self.hparams["hidden_size"] // self.hparams["num_attention_heads"]
152
+ self.gguf_writer.add_rope_dimension_count(int(rope_dim * self.rope_parameters.get("partial_rotary_factor", 0.5)))
153
+ self.gguf_writer.add_add_bos_token(False)
154
+ rope_freq = 10000
155
+ if "rope_ratio" in self.hparams:
156
+ rope_freq = rope_freq * self.hparams["rope_ratio"]
157
+ self.gguf_writer.add_rope_freq_base(rope_freq)
158
+
159
+ @classmethod
160
+ def filter_tensors(cls, item: tuple[str, Callable[[], Tensor]]) -> tuple[str, Callable[[], Tensor]] | None:
161
+ name, gen = item
162
+
163
+ if name.endswith(".rotary_pos_emb.inv_freq"):
164
+ return None
165
+
166
+ name = name.removeprefix("transformer.")
167
+
168
+ return super().filter_tensors((name, gen))
conversion/codeshell.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from .base import ModelBase, TextModel, gguf
4
+
5
+
6
+ @ModelBase.register("CodeShellForCausalLM")
7
+ @ModelBase.example("WisdomShell/CodeShell-7B")
8
+ class CodeShellModel(TextModel):
9
+ model_arch = gguf.MODEL_ARCH.CODESHELL
10
+
11
+ def set_gguf_parameters(self):
12
+ self.gguf_writer.add_context_length(self.hparams["n_positions"])
13
+ self.gguf_writer.add_embedding_length(self.hparams["n_embd"])
14
+ self.gguf_writer.add_feed_forward_length(4 * self.hparams["n_embd"])
15
+ self.gguf_writer.add_block_count(self.block_count)
16
+ self.gguf_writer.add_head_count(self.hparams["n_head"])
17
+ self.gguf_writer.add_head_count_kv(self.hparams["num_query_groups"])
18
+ self.gguf_writer.add_layer_norm_eps(self.hparams["layer_norm_epsilon"])
19
+ self.gguf_writer.add_file_type(self.ftype)
20
+ self.gguf_writer.add_rope_freq_base(10000.0)
21
+ self.gguf_writer.add_rope_scaling_type(gguf.RopeScalingType.LINEAR)
22
+ self.gguf_writer.add_rope_scaling_factor(1.0)
conversion/cogvlm.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import Callable, TYPE_CHECKING
4
+
5
+ if TYPE_CHECKING:
6
+ from torch import Tensor
7
+
8
+ from .base import MmprojModel, ModelBase, gguf
9
+
10
+ from .llama import LlamaModel
11
+
12
+
13
+ @ModelBase.register("CogVLMForCausalLM")
14
+ @ModelBase.example("THUDM/cogvlm2-llama3-chat-19B", "THUDM/cogvlm-chat-hf")
15
+ class CogVLMVisionModel(MmprojModel):
16
+
17
+ def set_gguf_parameters(self):
18
+ super().set_gguf_parameters()
19
+ self.gguf_writer.add_vision_attention_layernorm_eps(self.hparams.get("layer_norm_eps", 1e-6))
20
+ self.gguf_writer.add_clip_projector_type(gguf.VisionProjectorType.COGVLM)
21
+
22
+ @classmethod
23
+ def filter_tensors(cls, item: tuple[str, Callable[[], Tensor]]) -> tuple[str, Callable[[], Tensor]] | None:
24
+ name, gen = item
25
+
26
+ if not name.startswith("model.vision."):
27
+ return None
28
+
29
+ return super().filter_tensors(item)
30
+
31
+
32
+ @ModelBase.register("CogVLMForCausalLM")
33
+ @ModelBase.example("THUDM/cogvlm2-llama3-chat-19B", "THUDM/cogvlm-chat-hf")
34
+ class CogVLMModel(LlamaModel):
35
+ model_arch = gguf.MODEL_ARCH.COGVLM
conversion/command_r.py ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import re
4
+ from typing import Iterable, TYPE_CHECKING
5
+
6
+ import torch
7
+
8
+ if TYPE_CHECKING:
9
+ from torch import Tensor
10
+
11
+ from .base import ModelBase, TextModel, gguf, logger
12
+
13
+
14
+ @ModelBase.register("CohereForCausalLM")
15
+ # [TAG_HF_EXAMPLE_GATED] CohereLabs/c4ai-command-r-v01 is gated
16
+ # [TAG_HF_EXAMPLE_MISSING]
17
+ class CommandR2Model(TextModel):
18
+ model_arch = gguf.MODEL_ARCH.COMMAND_R
19
+
20
+ def __init__(self, *args, **kwargs):
21
+ super().__init__(*args, **kwargs)
22
+
23
+ # max_position_embeddings = 8192 in config.json but model was actually
24
+ # trained on 128k context length
25
+ # aya-23 models don't have model_max_length specified
26
+ self.hparams["max_position_embeddings"] = self.find_hparam(["model_max_length", "max_position_embeddings"])
27
+
28
+ def set_gguf_parameters(self):
29
+ super().set_gguf_parameters()
30
+ self.gguf_writer.add_logit_scale(self.hparams["logit_scale"])
31
+ self.gguf_writer.add_rope_scaling_type(gguf.RopeScalingType.NONE)
32
+
33
+
34
+ @ModelBase.register("Cohere2ForCausalLM")
35
+ # [TAG_HF_EXAMPLE_GATED] CohereLabs/c4ai-command-r7b-12-2024 is gated
36
+ @ModelBase.example("hf-tiny-v2/tiny-random-Cohere2ForCausalLM")
37
+ class Cohere2Model(TextModel):
38
+ model_arch = gguf.MODEL_ARCH.COHERE2
39
+
40
+ def set_gguf_parameters(self):
41
+ super().set_gguf_parameters()
42
+
43
+ self.gguf_writer.add_logit_scale(self.hparams["logit_scale"])
44
+ self.gguf_writer.add_sliding_window(self.hparams["sliding_window"])
45
+ self.gguf_writer.add_vocab_size(self.hparams["vocab_size"])
46
+
47
+ rotary_pct = self.hparams["rotary_pct"]
48
+ hidden_size = self.hparams["hidden_size"]
49
+ num_attention_heads = self.hparams["num_attention_heads"]
50
+ self.gguf_writer.add_rope_dimension_count(int(rotary_pct * (hidden_size // num_attention_heads)))
51
+ self.gguf_writer.add_rope_scaling_type(gguf.RopeScalingType.NONE)
52
+
53
+ def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]:
54
+ # Cohere2 runtime in llama.cpp expects no bias tensors;
55
+ # the actual weight only contains 0-value tensors as bias, we can skip them
56
+ if name.endswith(".bias"):
57
+ if torch.any(data_torch != 0):
58
+ raise ValueError(f"Bias tensor {name!r} is not zero.")
59
+ logger.debug(f"Skipping bias tensor {name!r} for Cohere2 conversion.")
60
+ return
61
+
62
+ yield from super().modify_tensors(data_torch, name, bid)
63
+
64
+
65
+ @ModelBase.register("Cohere2MoeForCausalLM")
66
+ @ModelBase.example("CohereLabs/North-Mini-Code-1.0")
67
+ class Cohere2MoeModel(TextModel):
68
+ model_arch = gguf.MODEL_ARCH.COHERE2MOE
69
+ _n_main_layers: int | None = None
70
+ _expert_tensor_re = re.compile(
71
+ r"model\.layers\.(\d+)\.mlp\.experts\.(\d+)\.(down_proj|gate_proj|up_proj)\.weight"
72
+ )
73
+
74
+ def __init__(self, *args, **kwargs):
75
+ super().__init__(*args, **kwargs)
76
+ if (n_nextn := int(self.hparams.get("num_nextn_predict_layers", 0) or 0)) > 0 and not self.no_mtp:
77
+ self.block_count += n_nextn
78
+ self.tensor_map = gguf.get_tensor_name_map(self.model_arch, self.block_count)
79
+ self._experts: list[dict[str, Tensor]] = [{} for _ in range(self.block_count)]
80
+
81
+ def _set_vocab_gpt2(self) -> None:
82
+ tokens, toktypes, tokpre = self.get_vocab_base()
83
+ self.gguf_writer.add_tokenizer_model("gpt2")
84
+ self.gguf_writer.add_tokenizer_pre(tokpre)
85
+ self.gguf_writer.add_token_list(tokens)
86
+ self.gguf_writer.add_token_types(toktypes)
87
+
88
+ special_vocab = gguf.SpecialVocab(self.dir_model, load_merges=True)
89
+ special_vocab.add_to_gguf(self.gguf_writer)
90
+
91
+ def set_gguf_parameters(self):
92
+ hparams = self.hparams
93
+ expert_intermediate_size = hparams["intermediate_size"]
94
+ mlp_layer_types = hparams.get("mlp_layer_types")
95
+ n_dense_lead = hparams.get("first_k_dense_replace", 0)
96
+ if mlp_layer_types is not None:
97
+ n_dense_lead = next((i for i, t in enumerate(mlp_layer_types) if t != "dense"), len(mlp_layer_types))
98
+
99
+ super().set_gguf_parameters()
100
+
101
+ self.gguf_writer.add_logit_scale(hparams["logit_scale"])
102
+ self.gguf_writer.add_sliding_window(hparams["sliding_window"])
103
+ self.gguf_writer.add_sliding_window_pattern([t == "sliding_attention" for t in hparams["layer_types"]])
104
+ self.gguf_writer.add_vocab_size(hparams["vocab_size"])
105
+ self.gguf_writer.add_expert_feed_forward_length(expert_intermediate_size)
106
+ self.gguf_writer.add_leading_dense_block_count(n_dense_lead)
107
+ self.gguf_writer.add_expert_weights_norm(hparams.get("norm_topk_prob", False))
108
+ if (num_shared_experts := hparams.get("num_shared_experts", 0)) > 0:
109
+ if hparams.get("shared_expert_combination_strategy", "average") != "average":
110
+ raise ValueError("Cohere2 MoE only supports average shared expert combination")
111
+ self.gguf_writer.add_expert_shared_count(num_shared_experts)
112
+ self.gguf_writer.add_expert_shared_feed_forward_length(expert_intermediate_size * num_shared_experts)
113
+ if (n_nextn := hparams.get("num_nextn_predict_layers", 0)) > 0 and not self.no_mtp:
114
+ self.gguf_writer.add_nextn_predict_layers(n_nextn)
115
+ self.gguf_writer.add_rope_dimension_count(hparams["head_dim"])
116
+ self.gguf_writer.add_rope_scaling_type(gguf.RopeScalingType.NONE)
117
+
118
+ def index_tensors(self, remote_hf_model_id: str | None = None):
119
+ hparams = {**self.hparams, **self.hparams.get("text_config", {})}
120
+ self._n_main_layers = hparams.get("num_hidden_layers")
121
+ type(self)._n_main_layers = self._n_main_layers
122
+ return super().index_tensors(remote_hf_model_id=remote_hf_model_id)
123
+
124
+ @classmethod
125
+ def filter_tensors(cls, item):
126
+ if (titem := super().filter_tensors(item)) is None:
127
+ return None
128
+ name, gen = titem
129
+
130
+ if cls._n_main_layers is not None:
131
+ is_mtp = (m := re.match(r"model\.layers\.(\d+)\.", name)) is not None and int(m.group(1)) >= cls._n_main_layers
132
+ if is_mtp and cls.no_mtp:
133
+ return None
134
+ if cls.mtp_only and not is_mtp and name not in (
135
+ "model.embed_tokens.weight", "model.norm.weight", "lm_head.weight",
136
+ ):
137
+ return None
138
+
139
+ return name, gen
140
+
141
+ def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]:
142
+ if name.endswith(".bias"):
143
+ if torch.any(data_torch != 0):
144
+ raise ValueError(f"Bias tensor {name!r} is not zero.")
145
+ logger.debug(f"Skipping bias tensor {name!r}.")
146
+ return
147
+
148
+ if (m := self._expert_tensor_re.fullmatch(name)) is not None:
149
+ n_experts = self.hparams["num_experts"]
150
+ layer_idx = int(m.group(1))
151
+ assert bid is None or bid == layer_idx
152
+
153
+ self._experts[layer_idx][name] = data_torch
154
+
155
+ expected = {
156
+ f"model.layers.{layer_idx}.mlp.experts.{xid}.{w_name}.weight"
157
+ for xid in range(n_experts)
158
+ for w_name in ("down_proj", "gate_proj", "up_proj")
159
+ }
160
+ if expected.issubset(self._experts[layer_idx]):
161
+ for w_name in ["down_proj", "gate_proj", "up_proj"]:
162
+ datas: list[Tensor] = []
163
+
164
+ for xid in range(n_experts):
165
+ ename = f"model.layers.{layer_idx}.mlp.experts.{xid}.{w_name}.weight"
166
+ datas.append(self._experts[layer_idx][ename])
167
+ del self._experts[layer_idx][ename]
168
+
169
+ data_torch = torch.stack(datas, dim=0)
170
+ merged_name = f"model.layers.{layer_idx}.mlp.experts.{w_name}.weight"
171
+
172
+ yield from super().modify_tensors(data_torch, merged_name, layer_idx)
173
+ return
174
+
175
+ yield from super().modify_tensors(data_torch, name, bid)
176
+
177
+ def prepare_tensors(self):
178
+ super().prepare_tensors()
179
+
180
+ experts = [k for d in self._experts for k in d.keys()]
181
+ if len(experts) > 0:
182
+ raise ValueError(f"Unprocessed experts: {experts}")
conversion/dbrx.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import Iterable, TYPE_CHECKING
4
+
5
+ if TYPE_CHECKING:
6
+ from torch import Tensor
7
+
8
+ from .base import ModelBase, TextModel, gguf, logger
9
+
10
+
11
+ @ModelBase.register("DbrxForCausalLM")
12
+ @ModelBase.example("alpindale/dbrx-instruct")
13
+ class DbrxModel(TextModel):
14
+ model_arch = gguf.MODEL_ARCH.DBRX
15
+
16
+ def set_gguf_parameters(self):
17
+ ffn_config = self.hparams["ffn_config"]
18
+ attn_config = self.hparams["attn_config"]
19
+ self.gguf_writer.add_block_count(self.block_count)
20
+
21
+ self.gguf_writer.add_context_length(self.hparams["max_seq_len"])
22
+ self.gguf_writer.add_embedding_length(self.hparams["d_model"])
23
+ self.gguf_writer.add_feed_forward_length(ffn_config["ffn_hidden_size"])
24
+
25
+ self.gguf_writer.add_head_count(self.hparams["n_heads"])
26
+ self.gguf_writer.add_head_count_kv(attn_config["kv_n_heads"])
27
+
28
+ self.gguf_writer.add_rope_freq_base(attn_config["rope_theta"])
29
+
30
+ self.gguf_writer.add_clamp_kqv(attn_config["clip_qkv"])
31
+
32
+ self.gguf_writer.add_expert_count(ffn_config["moe_num_experts"])
33
+ self.gguf_writer.add_expert_used_count(ffn_config["moe_top_k"])
34
+
35
+ self.gguf_writer.add_layer_norm_eps(1e-5)
36
+
37
+ self.gguf_writer.add_file_type(self.ftype)
38
+ logger.info(f"gguf: file type = {self.ftype}")
39
+
40
+ def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]:
41
+ n_expert = self.hparams["ffn_config"]["moe_num_experts"]
42
+ n_ff = self.hparams["ffn_config"]["ffn_hidden_size"]
43
+ n_embd = self.hparams["d_model"]
44
+
45
+ # Specific behavior for experts tensors: suffix .weight, view as 3D and transpose
46
+ # original implementation expects (n_expert, n_ff, n_embd) for all experts weights
47
+ # But llama.cpp moe graph works differently
48
+ # AND the dimensions in ggml are typically in the reverse order of the pytorch dimensions
49
+ # so (n_expert, n_ff, n_embd) in pytorch is {n_embd, n_ff, n_expert} in ggml_tensor
50
+ exp_tensor_names = {"ffn.experts.mlp.w1": None, # LLM_TENSOR_FFN_GATE_EXPS ggml_tensor->ne{n_embd, n_ff, n_expert}
51
+ "ffn.experts.mlp.w2": (0, 2, 1), # LLM_TENSOR_FFN_DOWN_EXPS ggml_tensor->ne{n_ff, n_embd, n_expert}
52
+ "ffn.experts.mlp.v1": None} # LLM_TENSOR_FFN_UP_EXPS ggml_tensor->ne{n_embd, n_ff, n_expert}
53
+ experts = False
54
+
55
+ for exp_tensor_name in exp_tensor_names.keys():
56
+ if name.find(exp_tensor_name) != -1 and name.find(".weight") == -1:
57
+ experts = True
58
+ data_torch = data_torch.view(n_expert, n_ff, n_embd)
59
+ if (permute_tensor := exp_tensor_names[exp_tensor_name]) is not None:
60
+ data_torch = data_torch.permute(*permute_tensor)
61
+ break
62
+
63
+ # map tensor names
64
+ # In MoE models the ffn tensors are typically most of the model weights,
65
+ # and need to be quantizable. Quantize expects tensor names to be suffixed by .weight.
66
+ # Every other model has the weight names ending in .weight,
67
+ # let's assume that is the convention which is not the case for dbrx:
68
+ # https://huggingface.co/databricks/dbrx-instruct/blob/main/model.safetensors.index.json#L15
69
+ new_name = self.map_tensor_name(name if not experts else name + ".weight", try_suffixes=(".weight",))
70
+
71
+ yield from super().modify_tensors(data_torch, new_name, bid)
72
+
73
+ def tensor_force_quant(self, name: str, new_name: str, bid: int | None, n_dims: int) -> gguf.GGMLQuantizationType | bool:
74
+ del name, new_name, bid # unused
75
+
76
+ return n_dims > 1
conversion/deci.py ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import math
4
+
5
+ from typing import Any, Iterable, TYPE_CHECKING
6
+
7
+ import torch
8
+
9
+ if TYPE_CHECKING:
10
+ from torch import Tensor
11
+
12
+ from .base import ModelBase, TextModel, gguf
13
+
14
+
15
+ @ModelBase.register("DeciLMForCausalLM")
16
+ @ModelBase.example("nvidia/Llama-3_1-Nemotron-51B-Instruct", "Deci/DeciLM-7B")
17
+ class DeciModel(TextModel):
18
+ model_arch = gguf.MODEL_ARCH.DECI
19
+
20
+ @staticmethod
21
+ def _ffn_mult_to_intermediate_size(ffn_mult: float, n_embd: int) -> int:
22
+ # DeciLM-specific code
23
+ intermediate_size = int(2 * ffn_mult * n_embd / 3)
24
+ return DeciModel._find_multiple(intermediate_size, 256)
25
+
26
+ @staticmethod
27
+ def _find_multiple(n: int, k: int) -> int:
28
+ # DeciLM-specific code
29
+ if n % k == 0:
30
+ return n
31
+ return n + k - (n % k)
32
+
33
+ def __init__(self, *args, **kwargs):
34
+ super().__init__(*args, **kwargs)
35
+
36
+ if "block_configs" in self.hparams: # Llama-3_1-Nemotron-51B
37
+ _block_configs: list[dict[str,Any]] = self.hparams["block_configs"]
38
+ assert self.block_count == len(_block_configs)
39
+ self._num_kv_heads = list()
40
+ self._num_heads = list()
41
+ _ffn_multipliers = list()
42
+ # ***linear attention layer***
43
+ # if n_heads_in_group is None and replace_with_linear is True
44
+ # then _num_kv_heads[il] is 0 and _num_heads[il] is num_attention_heads
45
+ # ***attention-free layer***
46
+ # if n_heads_in_group is None and replace_with_linear is False
47
+ # then _num_kv_heads[il] is 0 and _num_heads[il] is 0
48
+ # ***normal attention-layer***
49
+ # if n_heads_in_group is not None, then
50
+ # _num_kv_heads[il] is num_attention_head // n_heads_in_group and
51
+ # _num_heads[il] is num_attention_head
52
+ # ***dummy layer*** for nemotron 253B
53
+ # if n_heads_in_group is None and ffn_mult is None
54
+ # then _num_kv_heads[il] is 0 and _num_heads[il] is 0 and _ffn_dims is 0
55
+ for il in range(len(_block_configs)):
56
+ if _block_configs[il]["attention"]["n_heads_in_group"] is None:
57
+ if _block_configs[il]["attention"]["replace_with_linear"] is True:
58
+ self._num_kv_heads.append(0)
59
+ self._num_heads.append(self.hparams["num_attention_heads"])
60
+ else:
61
+ self._num_kv_heads.append(0)
62
+ self._num_heads.append(0)
63
+ else:
64
+ self._num_kv_heads.append(self.hparams["num_attention_heads"] // _block_configs[il]["attention"]["n_heads_in_group"])
65
+ self._num_heads.append(self.hparams["num_attention_heads"])
66
+ if _block_configs[il]["ffn"]["ffn_mult"] is None: # dummy layer
67
+ _ffn_multipliers.append(0.0)
68
+ else:
69
+ _ffn_multipliers.append(_block_configs[il]["ffn"]["ffn_mult"])
70
+ assert self.block_count == len(self._num_kv_heads)
71
+ assert self.block_count == len(self._num_heads)
72
+ assert self.block_count == len(_ffn_multipliers)
73
+ assert isinstance(self._num_kv_heads, list) and isinstance(self._num_kv_heads[0], int)
74
+ assert isinstance(self._num_heads, list) and isinstance(self._num_heads[0], int)
75
+ assert isinstance(_ffn_multipliers, list) and isinstance(_ffn_multipliers[0], float)
76
+ self._ffn_dims: list[int] = [
77
+ DeciModel._ffn_mult_to_intermediate_size(multiplier, self.hparams["hidden_size"])
78
+ for multiplier in _ffn_multipliers
79
+ ]
80
+
81
+ def set_vocab(self):
82
+ # Please change tokenizer_config.json of Llama-3_1-Nemotron-51B's
83
+ # eos_token from '|eot_id|' to '|end_of_text|'
84
+ if self.hparams.get("vocab_size", 128256) == 128256:
85
+ tokens, toktypes, tokpre = self.get_vocab_base()
86
+ self.gguf_writer.add_tokenizer_model("gpt2")
87
+ self.gguf_writer.add_tokenizer_pre(tokpre)
88
+ self.gguf_writer.add_token_list(tokens)
89
+ self.gguf_writer.add_token_types(toktypes)
90
+
91
+ special_vocab = gguf.SpecialVocab(self.dir_model, load_merges=True)
92
+ special_vocab.add_to_gguf(self.gguf_writer)
93
+ else:
94
+ # DeciLM-7B
95
+ self._set_vocab_llama_hf()
96
+
97
+ def set_gguf_parameters(self):
98
+ if "block_configs" in self.hparams: # Llama-3_1-Nemotron-51B
99
+ assert self.block_count == len(self._num_kv_heads)
100
+ assert self.block_count == len(self._num_heads)
101
+ assert self.block_count == len(self._ffn_dims)
102
+ if (rope_theta := self.rope_parameters.get("rope_theta")) is not None:
103
+ self.gguf_writer.add_rope_freq_base(rope_theta)
104
+ self.gguf_writer.add_head_count_kv(self._num_kv_heads)
105
+ self.gguf_writer.add_head_count(self._num_heads)
106
+ self.gguf_writer.add_feed_forward_length(self._ffn_dims)
107
+ self.gguf_writer.add_block_count(self.block_count)
108
+ self.gguf_writer.add_context_length(self.hparams["max_position_embeddings"])
109
+ self.gguf_writer.add_embedding_length(self.hparams["hidden_size"])
110
+ self.gguf_writer.add_layer_norm_rms_eps(self.hparams["rms_norm_eps"])
111
+ self.gguf_writer.add_key_length(self.hparams["hidden_size"] // self.hparams["num_attention_heads"])
112
+ self.gguf_writer.add_value_length(self.hparams["hidden_size"] // self.hparams["num_attention_heads"])
113
+ self.gguf_writer.add_file_type(self.ftype)
114
+ else: # DeciLM-7B
115
+ super().set_gguf_parameters()
116
+ if "num_key_value_heads_per_layer" in self.hparams: # DeciLM-7B
117
+ self._num_kv_heads: list[int] = self.hparams["num_key_value_heads_per_layer"]
118
+ assert self.block_count == len(self._num_kv_heads)
119
+ self.gguf_writer.add_head_count_kv(self._num_kv_heads)
120
+ hparams = self.hparams
121
+ self.gguf_writer.add_vocab_size(hparams["vocab_size"])
122
+
123
+ if (rope_dim := hparams.get("head_dim")) is None:
124
+ rope_dim = hparams["hidden_size"] // hparams["num_attention_heads"]
125
+ self.gguf_writer.add_rope_dimension_count(rope_dim)
126
+
127
+ @staticmethod
128
+ def permute(weights: Tensor, n_head: int, n_head_kv: int | None):
129
+ if n_head_kv is not None and n_head != n_head_kv:
130
+ n_head = n_head_kv
131
+ return (weights.reshape(n_head, 2, weights.shape[0] // n_head // 2, *weights.shape[1:])
132
+ .swapaxes(1, 2)
133
+ .reshape(weights.shape))
134
+
135
+ def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]:
136
+ n_head = self.hparams["num_attention_heads"]
137
+ if bid is not None:
138
+ if "num_key_value_heads_per_layer" in self.hparams:
139
+ n_kv_head = self.hparams["num_key_value_heads_per_layer"][bid]
140
+ elif "block_configs" in self.hparams:
141
+ n_kv_head = self._num_kv_heads[bid]
142
+ n_head = self._num_heads[bid]
143
+ else:
144
+ n_kv_head = self.hparams.get("num_key_value_heads")
145
+ else:
146
+ n_kv_head = self.hparams.get("num_key_value_heads")
147
+
148
+ if name.endswith(("q_proj.weight", "q_proj.bias")):
149
+ data_torch = DeciModel.permute(data_torch, n_head, n_head)
150
+ if name.endswith(("k_proj.weight", "k_proj.bias")):
151
+ data_torch = DeciModel.permute(data_torch, n_head, n_kv_head)
152
+ yield from super().modify_tensors(data_torch, name, bid)
153
+
154
+ def generate_extra_tensors(self) -> Iterable[tuple[str, Tensor]]:
155
+ if rope_params := self.rope_parameters.get("full_attention", self.rope_parameters):
156
+ if rope_params.get("rope_type", '').lower() == "llama3":
157
+ base = rope_params.get("rope_theta", 10000.0)
158
+ if (dim := self.hparams.get("head_dim")) is None:
159
+ dim = self.hparams["hidden_size"] // self.hparams["num_attention_heads"]
160
+ freqs = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.float32) / dim))
161
+
162
+ factor = rope_params.get("factor", 8.0)
163
+ low_freq_factor = rope_params.get("low_freq_factor", 1.0)
164
+ high_freq_factor = rope_params.get("high_freq_factor", 4.0)
165
+ old_context_len = rope_params.get("original_max_position_embeddings", 8192)
166
+
167
+ low_freq_wavelen = old_context_len / low_freq_factor
168
+ high_freq_wavelen = old_context_len / high_freq_factor
169
+ assert low_freq_wavelen != high_freq_wavelen
170
+
171
+ rope_factors = []
172
+ for freq in freqs:
173
+ wavelen = 2 * math.pi / freq
174
+ if wavelen < high_freq_wavelen:
175
+ rope_factors.append(1)
176
+ elif wavelen > low_freq_wavelen:
177
+ rope_factors.append(factor)
178
+ else:
179
+ smooth = (old_context_len / wavelen - low_freq_factor) / (high_freq_factor - low_freq_factor)
180
+ rope_factors.append(1 / ((1 - smooth) / factor + smooth))
181
+
182
+ yield (self.format_tensor_name(gguf.MODEL_TENSOR.ROPE_FREQS), torch.tensor(rope_factors, dtype=torch.float32))
183
+
184
+ def prepare_tensors(self):
185
+ super().prepare_tensors()
conversion/deepseek.py ADDED
@@ -0,0 +1,1104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import re
5
+ from pathlib import Path
6
+
7
+ from typing import Any, Callable, Iterable, TYPE_CHECKING
8
+
9
+ import numpy as np
10
+ import torch
11
+
12
+ if TYPE_CHECKING:
13
+ from torch import Tensor
14
+
15
+ from .base import LazyTorchTensor, MmprojModel, ModelBase, TextModel, gguf, logger
16
+
17
+ from .qwen import QwenModel
18
+
19
+
20
+ @ModelBase.register("DeepseekOCRForCausalLM")
21
+ @ModelBase.example("deepseek-ai/DeepSeek-OCR")
22
+ class DeepseekOCRVisionModel(MmprojModel):
23
+ # HF dynamic_preprocess() max_num, which differs per model
24
+ preproc_max_tiles = 9
25
+
26
+ def __init__(self, *args, **kwargs):
27
+ super().__init__(*args, **kwargs)
28
+ self.clip_projector_type = gguf.VisionProjectorType.DEEPSEEKOCR
29
+
30
+ def set_gguf_parameters(self):
31
+ super().set_gguf_parameters()
32
+ hparams = self.hparams
33
+ self.gguf_writer.add_clip_projector_type(self.clip_projector_type)
34
+ # default values below are taken from HF tranformers code
35
+ self.gguf_writer.add_vision_attention_layernorm_eps(hparams.get("layer_norm_eps", 1e-6))
36
+ self.gguf_writer.add_vision_use_gelu(True)
37
+ # calculate proj_scale_factor (used by tinygemma3 test model)
38
+ image_seq_length = self.preprocessor_config.get("image_seq_length", 256)
39
+ n_per_side = int(image_seq_length ** 0.5)
40
+ image_size = self.hparams["image_size"]
41
+ patch_size = self.hparams["patch_size"]
42
+ proj_scale_factor = (image_size // patch_size) // n_per_side
43
+ if proj_scale_factor > 0 and proj_scale_factor != 4:
44
+ # we only need to write this if it's not the default value
45
+ # in this case, we are converting a test model
46
+ self.gguf_writer.add_vision_projector_scale_factor(proj_scale_factor)
47
+ # @bluebread: there's no window_size in config but just add it here anyway
48
+ self.gguf_writer.add_vision_window_size(self.hparams.get("window_size", 14))
49
+
50
+ self.gguf_writer.add_vision_preproc_min_tiles(2)
51
+ self.gguf_writer.add_vision_preproc_max_tiles(self.preproc_max_tiles)
52
+
53
+ # SAM configuration
54
+ sam_hparams = hparams['sam']
55
+ self.gguf_writer.add_vision_sam_layers_count(sam_hparams['layers'])
56
+ self.gguf_writer.add_vision_sam_embedding_length(sam_hparams['width'])
57
+ self.gguf_writer.add_vision_sam_head_count(sam_hparams['heads'])
58
+
59
+ def get_vision_config(self) -> dict[str, Any]:
60
+ vision_config: dict[str, Any] | None = self.global_config.get("vision_config")
61
+
62
+ if not vision_config:
63
+ raise ValueError("DeepseekOCR model requires 'vision_config' in the model configuration, but it was not found")
64
+
65
+ vision_config['sam'] = vision_config['width']['sam_vit_b']
66
+ if vision_config['width'].get('clip-l-14-224') is not None:
67
+ vision_config.update(vision_config['width']['clip-l-14-224'])
68
+ if isinstance(vision_config['width'], int):
69
+ vision_config['hidden_size'] = vision_config['width']
70
+ if vision_config.get('heads') is not None:
71
+ vision_config['num_heads'] = vision_config['heads']
72
+ vision_config['intermediate_size'] = vision_config['heads'] * 4
73
+
74
+ return vision_config
75
+
76
+ def tensor_force_quant(self, name, new_name, bid, n_dims):
77
+ for nq_name in ('.embeddings.', 'pos_embed', '.rel_pos_h', '.rel_pos_w', '.neck.', '.net_'):
78
+ if nq_name in name:
79
+ return gguf.GGMLQuantizationType.F32
80
+ return super().tensor_force_quant(name, new_name, bid, n_dims)
81
+
82
+ def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]:
83
+ if name.endswith("view_seperator"):
84
+ data_torch = data_torch.unsqueeze(0)
85
+ yield from super().modify_tensors(data_torch, name, bid)
86
+
87
+ @classmethod
88
+ def filter_tensors(cls, item: tuple[str, Callable[[], Tensor]]) -> tuple[str, Callable[[], Tensor]] | None:
89
+ name, gen = item
90
+
91
+ # Only process vision-related tensors, skip language model tensors
92
+ # Vision components: sam_model, vision_model, projector, image_newline, view_seperator
93
+ # Language model components to skip: lm_head, embed_tokens, layers, norm
94
+ if name.startswith(("lm_head.", "model.embed_tokens.", "model.layers.", "model.norm.")):
95
+ return None
96
+
97
+ if name.endswith("pos_embed") or name.endswith("rel_pos_h") or name.endswith("rel_pos_w"):
98
+ name += ".weight"
99
+
100
+ return super().filter_tensors((name, gen))
101
+
102
+
103
+ @ModelBase.register("UnlimitedOCRForCausalLM")
104
+ @ModelBase.example("baidu/Unlimited-OCR")
105
+ class UnlimitedOCRVisionModel(DeepseekOCRVisionModel):
106
+ preproc_max_tiles = 32
107
+
108
+
109
+ @ModelBase.register("DeepseekOCR2ForCausalLM")
110
+ @ModelBase.example("deepseek-ai/DeepSeek-OCR-2")
111
+ class DeepseekOCR2VisionModel(DeepseekOCRVisionModel):
112
+ preproc_max_tiles = 6
113
+
114
+ def __init__(self, *args, **kwargs):
115
+ super().__init__(*args, **kwargs)
116
+ self.clip_projector_type = gguf.VisionProjectorType.DEEPSEEKOCR2
117
+
118
+ def set_gguf_parameters(self):
119
+ # the vision tower's qwen2 encoder is built from fixed defaults,
120
+ # see build_qwen2_decoder_as_encoder() in deepencoderv2.py
121
+ if self.hparams.get("patch_size") is None:
122
+ self.hparams["patch_size"] = 16
123
+ if self.hparams.get("intermediate_size") is None:
124
+ self.hparams["intermediate_size"] = 4864
125
+ if self.hparams.get("num_attention_heads") is None:
126
+ self.hparams["num_attention_heads"] = 14
127
+ super().set_gguf_parameters()
128
+ # qwen2 encoder is GQA: 14 Q heads, 2 KV heads
129
+ self.gguf_writer.add_vision_head_count_kv(2)
130
+
131
+ def get_vision_config(self) -> dict[str, Any]:
132
+ vision_config = super().get_vision_config()
133
+ vision_config['hidden_size'] = vision_config['width']['qwen2-0-5b']['dim']
134
+ if vision_config.get('layers') is None:
135
+ vision_config['layers'] = 24
136
+ return vision_config
137
+
138
+
139
+ @ModelBase.register("DeepseekForCausalLM")
140
+ @ModelBase.example("deepseek-ai/deepseek-moe-16b-chat")
141
+ class DeepseekModel(TextModel):
142
+ model_arch = gguf.MODEL_ARCH.DEEPSEEK
143
+
144
+ def set_vocab(self):
145
+ try:
146
+ self._set_vocab_sentencepiece()
147
+ except FileNotFoundError:
148
+ self._set_vocab_gpt2()
149
+
150
+ def set_gguf_parameters(self):
151
+ super().set_gguf_parameters()
152
+ hparams = self.hparams
153
+ if (rope_dim := hparams.get("head_dim")) is None:
154
+ rope_dim = hparams["hidden_size"] // hparams["num_attention_heads"]
155
+
156
+ self.gguf_writer.add_rope_dimension_count(rope_dim)
157
+ self.gguf_writer.add_rope_scaling_type(gguf.RopeScalingType.NONE)
158
+ self.gguf_writer.add_leading_dense_block_count(hparams["first_k_dense_replace"])
159
+ self.gguf_writer.add_vocab_size(hparams["vocab_size"])
160
+ self.gguf_writer.add_expert_feed_forward_length(hparams["moe_intermediate_size"])
161
+ self.gguf_writer.add_expert_weights_scale(1.0)
162
+ self.gguf_writer.add_expert_count(hparams["n_routed_experts"])
163
+ self.gguf_writer.add_expert_shared_count(hparams["n_shared_experts"])
164
+
165
+ _experts: list[dict[str, Tensor]] | None = None
166
+
167
+ @staticmethod
168
+ def permute(weights: Tensor, n_head: int, n_head_kv: int | None):
169
+ if n_head_kv is not None and n_head != n_head_kv:
170
+ n_head = n_head_kv
171
+ return (weights.reshape(n_head, 2, weights.shape[0] // n_head // 2, *weights.shape[1:])
172
+ .swapaxes(1, 2)
173
+ .reshape(weights.shape))
174
+
175
+ def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]:
176
+ n_head = self.hparams["num_attention_heads"]
177
+ n_kv_head = self.hparams.get("num_key_value_heads")
178
+
179
+ if name.endswith(("q_proj.weight", "q_proj.bias")):
180
+ data_torch = DeepseekModel.permute(data_torch, n_head, n_head)
181
+ if name.endswith(("k_proj.weight", "k_proj.bias")):
182
+ data_torch = DeepseekModel.permute(data_torch, n_head, n_kv_head)
183
+
184
+ # process the experts separately
185
+ if name.find("mlp.experts") != -1:
186
+ n_experts = self.hparams["n_routed_experts"]
187
+ assert bid is not None
188
+
189
+ if self._experts is None:
190
+ self._experts = [{} for _ in range(self.block_count)]
191
+
192
+ self._experts[bid][name] = data_torch
193
+
194
+ if len(self._experts[bid]) >= n_experts * 3:
195
+ # merge the experts into a single 3d tensor
196
+ for w_name in ["down_proj", "gate_proj", "up_proj"]:
197
+ datas: list[Tensor] = []
198
+
199
+ for xid in range(n_experts):
200
+ ename = f"model.layers.{bid}.mlp.experts.{xid}.{w_name}.weight"
201
+ datas.append(self._experts[bid][ename])
202
+ del self._experts[bid][ename]
203
+
204
+ data_torch = torch.stack(datas, dim=0)
205
+
206
+ merged_name = f"model.layers.{bid}.mlp.experts.{w_name}.weight"
207
+
208
+ yield from super().modify_tensors(data_torch, merged_name, bid)
209
+ return
210
+ else:
211
+ return
212
+
213
+ yield from super().modify_tensors(data_torch, name, bid)
214
+
215
+ def prepare_tensors(self):
216
+ super().prepare_tensors()
217
+
218
+ if self._experts is not None:
219
+ # flatten `list[dict[str, Tensor]]` into `list[str]`
220
+ experts = [k for d in self._experts for k in d.keys()]
221
+ if len(experts) > 0:
222
+ raise ValueError(f"Unprocessed experts: {experts}")
223
+
224
+
225
+ @ModelBase.register(
226
+ "DeepseekV2ForCausalLM",
227
+ "DeepseekV3ForCausalLM",
228
+ "DeepseekOCRForCausalLM",
229
+ "UnlimitedOCRForCausalLM",
230
+ "KimiVLForConditionalGeneration",
231
+ "KimiK25ForConditionalGeneration",
232
+ "YoutuForCausalLM",
233
+ "YoutuVLForConditionalGeneration",
234
+ )
235
+ @ModelBase.example("deepseek-ai/DeepSeek-V2-Lite", "deepseek-ai/DeepSeek-V3")
236
+ class DeepseekV2Model(TextModel):
237
+ model_arch = gguf.MODEL_ARCH.DEEPSEEK2
238
+
239
+ # TODO @ngxson : remove this when we support MTP for deepseek models
240
+ skip_mtp = True
241
+
242
+ merge_expert = True
243
+
244
+ def __init__(self, *args, **kwargs):
245
+ super().__init__(*args, **kwargs)
246
+ hparams: dict = ModelBase.load_hparams(self.dir_model, is_mistral_format=False)
247
+ self.origin_hf_arch = hparams.get('architectures', [None])[0]
248
+
249
+ # special handling for Deepseek OCR
250
+ if self.origin_hf_arch in ("DeepseekOCRForCausalLM", "DeepseekOCR2ForCausalLM", "UnlimitedOCRForCausalLM"):
251
+ self.model_arch = gguf.MODEL_ARCH.DEEPSEEK2OCR
252
+ self.gguf_writer.arch = gguf.MODEL_ARCH_NAMES[self.model_arch]
253
+ self.gguf_writer.add_architecture()
254
+ # default jinja template
255
+ self.gguf_writer.add_chat_template("{% for m in messages %}{{m['content']}}{% endfor %}")
256
+
257
+ @classmethod
258
+ def filter_tensors(cls, item: tuple[str, Callable[[], Tensor]]) -> tuple[str, Callable[[], Tensor]] | None:
259
+ name, _ = item
260
+ # DeepSeek-OCR vision encoder (SAM + DeepSeek-OCR-2 qwen2 tower)
261
+ if "sam_model" in name or "qwen2_model" in name:
262
+ return None
263
+ return super().filter_tensors(item)
264
+
265
+ def set_vocab(self):
266
+ try:
267
+ self._set_vocab_gpt2()
268
+ return
269
+ except Exception:
270
+ pass
271
+
272
+ from transformers import AutoTokenizer
273
+ tokenizer = AutoTokenizer.from_pretrained(self.dir_model, trust_remote_code=True)
274
+ tokpre = self.get_vocab_base_pre(tokenizer)
275
+
276
+ if tokpre == "kimi-k2":
277
+ # Build merges list using the approach similar to HunYuanMoE
278
+ merges = []
279
+ vocab = {}
280
+ mergeable_ranks = tokenizer.model._mergeable_ranks # ty: ignore[unresolved-attribute]
281
+ for token, rank in mergeable_ranks.items():
282
+ vocab[QwenModel.token_bytes_to_string(token)] = rank
283
+ if len(token) == 1:
284
+ continue
285
+ merged = QwenModel.bpe(mergeable_ranks, token, max_rank=rank)
286
+ if len(merged) == 2:
287
+ merges.append(' '.join(map(QwenModel.token_bytes_to_string, merged)))
288
+
289
+ # Build token list
290
+ vocab_size = self.hparams["vocab_size"]
291
+ special_tokens = tokenizer.special_tokens # ty: ignore[unresolved-attribute]
292
+ reverse_vocab = {id_ : encoded_tok for encoded_tok, id_ in {**vocab, **special_tokens}.items()}
293
+ tokens: list[str] = []
294
+ toktypes: list[int] = []
295
+
296
+ for i in range(vocab_size):
297
+ if i not in reverse_vocab:
298
+ tokens.append(f"[PAD{i}]")
299
+ toktypes.append(gguf.TokenType.UNUSED)
300
+ else:
301
+ token = reverse_vocab[i]
302
+ tokens.append(token)
303
+ if i in special_tokens.values():
304
+ toktypes.append(gguf.TokenType.CONTROL)
305
+ else:
306
+ toktypes.append(gguf.TokenType.NORMAL)
307
+
308
+ self.gguf_writer.add_tokenizer_model("gpt2")
309
+ self.gguf_writer.add_tokenizer_pre(tokpre)
310
+ self.gguf_writer.add_token_list(tokens)
311
+ self.gguf_writer.add_token_types(toktypes)
312
+ self.gguf_writer.add_token_merges(merges)
313
+
314
+ special_vocab = gguf.SpecialVocab(self.dir_model, load_merges=False)
315
+ special_vocab.add_to_gguf(self.gguf_writer)
316
+ else:
317
+ raise NotImplementedError(f"Deepseek pre-tokenizer {tokpre!r} is not supported yet!")
318
+
319
+ def set_gguf_parameters(self):
320
+ is_ocr = (self.model_arch == gguf.MODEL_ARCH.DEEPSEEK2OCR)
321
+
322
+ if is_ocr:
323
+ self.hparams['rope_theta'] = self.hparams.get('rope_theta', 10000.0)
324
+ else:
325
+ # note: deepseek2 using MLA converts into MQA (ie: GQA with 1 group)
326
+ self.hparams["num_key_value_heads"] = 1
327
+
328
+ self.hparams['rms_norm_eps'] = self.hparams.get('rms_norm_eps', 1e-6)
329
+
330
+ super().set_gguf_parameters()
331
+ hparams = self.hparams
332
+
333
+ # first_k_dense_replace: number of leading layers using dense FFN instead of MoE
334
+ # For non-MoE models (like Youtu), set to n_layer to use dense FFN for all layers
335
+ # For MoE models (like DeepSeek-V2), this is the number of leading non-MoE layers
336
+ has_moe = hparams.get("n_routed_experts") is not None
337
+ first_k_dense_replace = hparams.get("first_k_dense_replace")
338
+ if first_k_dense_replace is None:
339
+ # Default: if no MoE, all layers are dense; if MoE, none are dense
340
+ first_k_dense_replace = hparams["num_hidden_layers"] if not has_moe else 0
341
+ self.gguf_writer.add_leading_dense_block_count(first_k_dense_replace)
342
+ kv_lora_rank = hparams.get("kv_lora_rank", 512)
343
+ self.gguf_writer.add_vocab_size(hparams["vocab_size"])
344
+ if "q_lora_rank" in hparams and hparams["q_lora_rank"] is not None:
345
+ self.gguf_writer.add_q_lora_rank(hparams["q_lora_rank"])
346
+
347
+ # note: deepseek2 using MLA converts into MQA with larger heads, then decompresses to MHA
348
+ if not is_ocr:
349
+ self.gguf_writer.add_kv_lora_rank(kv_lora_rank)
350
+ self.gguf_writer.add_key_length(kv_lora_rank + hparams["qk_rope_head_dim"])
351
+ self.gguf_writer.add_value_length(kv_lora_rank)
352
+ self.gguf_writer.add_key_length_mla(hparams["qk_nope_head_dim"] + hparams["qk_rope_head_dim"])
353
+ self.gguf_writer.add_value_length_mla(hparams["v_head_dim"])
354
+
355
+ # MoE parameters (required by C++ code for DEEPSEEK2 arch)
356
+ # For non-MoE models like Youtu, use intermediate_size as expert_feed_forward_length
357
+ moe_intermediate_size = self.find_hparam(["moe_intermediate_size", "intermediate_size"], optional=False)
358
+ self.gguf_writer.add_expert_feed_forward_length(moe_intermediate_size)
359
+
360
+ if (n_routed_experts := hparams.get("n_routed_experts")) is not None:
361
+ self.gguf_writer.add_expert_count(n_routed_experts)
362
+
363
+ # expert_shared_count is required by C++ code, default to 0 for non-MoE models
364
+ n_shared_experts = hparams.get("n_shared_experts", 0)
365
+ self.gguf_writer.add_expert_shared_count(n_shared_experts)
366
+
367
+ # When not set, C++ code will use scale_w = false to skip the no-op scaling
368
+ if (routed_scaling_factor := hparams.get("routed_scaling_factor")) is not None:
369
+ self.gguf_writer.add_expert_weights_scale(routed_scaling_factor)
370
+
371
+ if (norm_topk_prob := hparams.get("norm_topk_prob")) is not None and norm_topk_prob:
372
+ self.gguf_writer.add_expert_weights_norm(norm_topk_prob)
373
+
374
+ self.gguf_writer.add_rope_dimension_count(hparams["qk_rope_head_dim"])
375
+
376
+ # Unlimited-OCR sliding window; written for metadata, the decoder ignores it (full MHA)
377
+ if is_ocr:
378
+ sliding_window = hparams.get("sliding_window_size") or hparams.get("sliding_window")
379
+ if sliding_window:
380
+ self.gguf_writer.add_sliding_window(sliding_window)
381
+
382
+ if (rope_mscale_all := self.rope_parameters.get("mscale_all_dim")) is not None:
383
+ # [TAG_DEEPSEEK2_YARN_LOG_MUL_FIX]
384
+ # note: for legacy reasons, this is not consistent with the other usages of self.gguf_writer.add_rope_scaling_yarn_log_mul
385
+ # ref https://github.com/ggml-org/llama.cpp/pull/17945
386
+ self.gguf_writer.add_rope_scaling_yarn_log_mul(0.1 * rope_mscale_all)
387
+
388
+ _experts: list[dict[str, Tensor]] | None = None
389
+
390
+ def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]:
391
+ # skip lm_head.weight if tie_word_embeddings is True
392
+ if self.hparams.get("tie_word_embeddings", False):
393
+ if name == "lm_head.weight" or name == "model.lm_head.weight":
394
+ logger.info("Skipping tied output layer 'lm_head.weight' (will use token_embd.weight)")
395
+ return
396
+
397
+ # skip Multi-Token Prediction (MTP) layers
398
+ if self.skip_mtp:
399
+ block_count = self.hparams["num_hidden_layers"]
400
+ match = re.match(r"model.layers.(\d+)", name)
401
+ if match and int(match.group(1)) >= block_count:
402
+ return
403
+
404
+ # process the experts separately
405
+ if self.merge_expert and name.find("mlp.experts") != -1:
406
+ n_experts = self.hparams["n_routed_experts"]
407
+ assert bid is not None
408
+
409
+ if self._experts is None:
410
+ self._experts = [{} for _ in range(self.block_count)]
411
+
412
+ self._experts[bid][name] = data_torch
413
+
414
+ if len(self._experts[bid]) >= n_experts * 3:
415
+ # merge the experts into a single 3d tensor
416
+ for w_name in ["down_proj", "gate_proj", "up_proj"]:
417
+ datas: list[Tensor] = []
418
+
419
+ for xid in range(n_experts):
420
+ ename = f"model.layers.{bid}.mlp.experts.{xid}.{w_name}.weight"
421
+ datas.append(self._experts[bid][ename])
422
+ del self._experts[bid][ename]
423
+
424
+ data_torch = torch.stack(datas, dim=0)
425
+
426
+ merged_name = f"model.layers.{bid}.mlp.experts.{w_name}.weight"
427
+
428
+ yield from super().modify_tensors(data_torch, merged_name, bid)
429
+ return
430
+ else:
431
+ return
432
+
433
+ # note: MLA with the absorption optimization, needs these two split and k_b_proj transposed
434
+ if name.endswith("kv_b_proj.weight"):
435
+ name_kb = name.replace("kv_b_proj", "k_b_proj")
436
+ name_vb = name.replace("kv_b_proj", "v_b_proj")
437
+
438
+ n_head_kv = self.hparams["num_key_value_heads"]
439
+ v_head_dim = self.hparams["v_head_dim"]
440
+ qk_nope_head_dim = self.hparams["qk_nope_head_dim"]
441
+
442
+ assert data_torch.shape[0] == n_head_kv * (v_head_dim + qk_nope_head_dim)
443
+
444
+ kv_b = data_torch.view(n_head_kv, v_head_dim + qk_nope_head_dim, data_torch.shape[-1])
445
+ k_b, v_b = torch.split(kv_b, [qk_nope_head_dim, v_head_dim], dim=1)
446
+ k_b = k_b.transpose(1, 2)
447
+
448
+ yield from super().modify_tensors(k_b, name_kb, bid)
449
+ yield from super().modify_tensors(v_b, name_vb, bid)
450
+ return
451
+
452
+ yield from super().modify_tensors(data_torch, name, bid)
453
+
454
+ def prepare_tensors(self):
455
+ super().prepare_tensors()
456
+
457
+ if self._experts is not None:
458
+ # flatten `list[dict[str, Tensor]]` into `list[str]`
459
+ experts = [k for d in self._experts for k in d.keys()]
460
+ if len(experts) > 0:
461
+ raise ValueError(f"Unprocessed experts: {experts}")
462
+
463
+
464
+ @ModelBase.register("DeepseekV32ForCausalLM")
465
+ @ModelBase.example("deepseek-ai/DeepSeek-V3.2-Exp")
466
+ class DeepseekV32Model(DeepseekV2Model):
467
+ model_arch = gguf.MODEL_ARCH.DEEPSEEK32
468
+ skip_mtp = False
469
+ supports_mtp_export = True
470
+ _n_main_layers: int | None = None
471
+
472
+ def __init__(self, *args, **kwargs):
473
+ super().__init__(*args, **kwargs)
474
+ self.block_count = self.hparams["num_hidden_layers"]
475
+ if not self.no_mtp:
476
+ self.block_count += self.hparams.get("num_nextn_predict_layers", 0)
477
+ self.tensor_map = gguf.get_tensor_name_map(self.model_arch, self.block_count)
478
+
479
+ def index_tensors(self, remote_hf_model_id: str | None = None):
480
+ type(self)._n_main_layers = self.hparams["num_hidden_layers"]
481
+ return super().index_tensors(remote_hf_model_id=remote_hf_model_id)
482
+
483
+ @classmethod
484
+ def filter_tensors(cls, item: tuple[str, Callable[[], Tensor]]) -> tuple[str, Callable[[], Tensor]] | None:
485
+ if (titem := super().filter_tensors(item)) is None:
486
+ return None
487
+ name, gen = titem
488
+
489
+ # DeepSeek V3.2 appends the NextN/MTP block past num_hidden_layers
490
+ # (model.layers.61 -> blk.61 in the 62-block file).
491
+ assert cls._n_main_layers is not None
492
+ is_mtp = (m := re.match(r"model\.layers\.(\d+)\.", name)) is not None and int(m.group(1)) >= cls._n_main_layers
493
+
494
+ # --no-mtp: drop the appended NextN block entirely.
495
+ if is_mtp and cls.no_mtp:
496
+ return None
497
+ # --mtp: keep ONLY NextN-block tensors plus the shared embeddings/
498
+ # norm/lm_head (so the resulting GGUF carries just the draft head).
499
+ if cls.mtp_only and not is_mtp and name not in (
500
+ "model.embed_tokens.weight", "model.norm.weight", "lm_head.weight",
501
+ ):
502
+ return None
503
+
504
+ return name, gen
505
+
506
+ def set_vocab(self):
507
+ from transformers import AutoTokenizer
508
+ tokenizer = AutoTokenizer.from_pretrained(self.dir_model)
509
+ assert getattr(tokenizer, "add_bos_token", False), "Change value of add_bos_token to true in tokenizer_config.json file."
510
+ self._set_vocab_gpt2()
511
+
512
+ def set_gguf_parameters(self):
513
+ super().set_gguf_parameters()
514
+
515
+ # NextN/MTP prediction layers
516
+ if not self.no_mtp and (num_nextn_predict_layers := self.hparams.get("num_nextn_predict_layers")) is not None:
517
+ self.gguf_writer.add_nextn_predict_layers(num_nextn_predict_layers)
518
+
519
+ # DSA indexer parameters
520
+ self.gguf_writer.add_indexer_head_count(self.hparams["index_n_heads"])
521
+ self.gguf_writer.add_indexer_key_length(self.hparams["index_head_dim"])
522
+ self.gguf_writer.add_indexer_top_k(self.hparams["index_topk"])
523
+
524
+
525
+ @ModelBase.register("DeepseekV4ForCausalLM")
526
+ @ModelBase.example("deepseek-ai/DeepSeek-V4-Flash-Base")
527
+ class DeepseekV4Model(TextModel):
528
+ model_arch = gguf.MODEL_ARCH.DEEPSEEK4
529
+ supports_mtp_export = True
530
+ _skipped_mtp_tensors = 0
531
+ _dsv4_main_layers: int | None = None
532
+ _dsv4_nextn_layers: int = 0
533
+
534
+ def __init__(self, *args, **kwargs):
535
+ type(self)._skipped_mtp_tensors = 0
536
+ super().__init__(*args, **kwargs)
537
+
538
+ with open(self.dir_model / "config.json", "r", encoding="utf-8") as f:
539
+ raw_hparams = json.load(f)
540
+ for key, value in raw_hparams.items():
541
+ self.hparams.setdefault(key, value)
542
+
543
+ # workaround for special rope_parameters (main/compress) in transformers 5.x
544
+ if self.rope_parameters.get("full_attention", self.rope_parameters).get("rope_type") is None:
545
+ if (rope_scaling := raw_hparams.get("rope_scaling")) is not None:
546
+ if "rope_type" not in rope_scaling and (rope_type := rope_scaling.get("type")) is not None:
547
+ rope_scaling["rope_type"] = rope_type
548
+ self.rope_parameters.update(**rope_scaling)
549
+
550
+ self.block_count = self.hparams["num_hidden_layers"]
551
+ if self.mtp_only:
552
+ self.block_count += self.hparams.get("num_nextn_predict_layers", 0)
553
+ self.tensor_map = gguf.get_tensor_name_map(self.model_arch, self.block_count)
554
+
555
+ self._dsv4_fp8_dequantized: set[str] = set()
556
+ self._dsv4_bf16_tensors: set[str] = set()
557
+ self._dsv4_f32_tensors: set[str] = set()
558
+ self._dsv4_mxfp4_generated = False
559
+ self._collect_source_dtypes()
560
+
561
+ if type(self)._skipped_mtp_tensors:
562
+ logger.info("Skipping %d DeepSeek-V4 MTP tensor(s) for conversion v0", type(self)._skipped_mtp_tensors)
563
+
564
+ # add a default chat template; if the model has a built-in template, it will be overridden later
565
+ model_id_hint = self.remote_hf_model_id or self.dir_model.name
566
+ is_0731 = "0731" in model_id_hint
567
+ template_name = "deepseek-ai-DeepSeek-V4-Flash-0731.jinja" if is_0731 else "deepseek-ai-DeepSeek-V4.jinja"
568
+ template_path = Path(__file__).parent.parent / "models" / "templates" / template_name
569
+ if template_path.is_file():
570
+ with open(template_path, "r", encoding="utf-8") as f:
571
+ self.gguf_writer.add_chat_template(f.read())
572
+
573
+ def index_tensors(self, remote_hf_model_id: str | None = None) -> dict[str, Callable[[], Tensor]]:
574
+ type(self)._dsv4_main_layers = self.hparams["num_hidden_layers"]
575
+ type(self)._dsv4_nextn_layers = self.hparams.get("num_nextn_predict_layers", 0)
576
+ return super().index_tensors(remote_hf_model_id=remote_hf_model_id)
577
+
578
+ @classmethod
579
+ def filter_tensors(cls, item: tuple[str, Callable[[], Tensor]]) -> tuple[str, Callable[[], Tensor]] | None:
580
+ name, gen = item
581
+ if name.startswith(("aligner.", "image_")):
582
+ return None
583
+ if name.startswith("mtp."):
584
+ if not cls.mtp_only:
585
+ cls._skipped_mtp_tensors += 1
586
+ return None
587
+
588
+ assert cls._dsv4_main_layers is not None
589
+ parts = name.split(".", 2)
590
+ if len(parts) < 3 or not parts[1].isdecimal():
591
+ raise ValueError(f"Unexpected DeepSeek-V4 MTP tensor {name!r}")
592
+
593
+ mtp_idx = int(parts[1])
594
+ if mtp_idx >= cls._dsv4_nextn_layers:
595
+ raise ValueError(f"Unexpected DeepSeek-V4 MTP layer {mtp_idx}")
596
+
597
+ bid = cls._dsv4_main_layers + mtp_idx
598
+ suffix = parts[2]
599
+ root_hc_head = {
600
+ "hc_head_fn",
601
+ "hc_head_base",
602
+ "hc_head_scale",
603
+ }
604
+ if suffix in root_hc_head:
605
+ name = suffix
606
+ elif suffix in (
607
+ "e_proj.weight", "e_proj.scale",
608
+ "h_proj.weight", "h_proj.scale",
609
+ ):
610
+ name = f"layers.{bid}.nextn.{suffix}"
611
+ elif suffix == "enorm.weight":
612
+ name = f"layers.{bid}.nextn.enorm.weight"
613
+ elif suffix == "hnorm.weight":
614
+ name = f"layers.{bid}.nextn.hnorm.weight"
615
+ elif suffix == "norm.weight":
616
+ name = f"layers.{bid}.nextn.shared_head_norm.weight"
617
+ else:
618
+ name = f"layers.{bid}.{suffix}"
619
+ return name, gen
620
+
621
+ if cls.mtp_only:
622
+ keep = name in (
623
+ "embed.weight",
624
+ "norm.weight",
625
+ "head.weight",
626
+ "head.scale",
627
+ )
628
+ if not keep:
629
+ return None
630
+
631
+ return super().filter_tensors((name, gen))
632
+
633
+ @staticmethod
634
+ def _float8_dtypes() -> tuple[torch.dtype, ...]:
635
+ return tuple(
636
+ dtype for dtype in (
637
+ getattr(torch, "float8_e4m3fn", None),
638
+ getattr(torch, "float8_e5m2", None),
639
+ ) if dtype is not None
640
+ )
641
+
642
+ @staticmethod
643
+ def _e8m0_to_float(scale: Tensor) -> Tensor:
644
+ torch_float8_e8m0 = getattr(torch, "float8_e8m0fnu", None)
645
+ if torch_float8_e8m0 is not None and scale.dtype == torch_float8_e8m0:
646
+ return scale.float()
647
+
648
+ bits = scale.view(torch.uint8).float()
649
+ return torch.exp2(bits - 127.0)
650
+
651
+ def _collect_source_dtypes(self) -> None:
652
+ for name, gen in self.model_tensors.items():
653
+ dtype = gen().dtype
654
+ if dtype == torch.bfloat16:
655
+ self._dsv4_bf16_tensors.add(name)
656
+ elif dtype == torch.float32:
657
+ self._dsv4_f32_tensors.add(name)
658
+
659
+ def set_gguf_parameters(self):
660
+ super().set_gguf_parameters()
661
+ hparams = self.hparams
662
+
663
+ self.gguf_writer.add_rope_dimension_count(hparams["qk_rope_head_dim"])
664
+ self.gguf_writer.add_q_lora_rank(hparams["q_lora_rank"])
665
+ self.gguf_writer.add_sliding_window(hparams["sliding_window"])
666
+
667
+ self.gguf_writer.add_expert_feed_forward_length(hparams["moe_intermediate_size"])
668
+ self.gguf_writer.add_expert_shared_count(hparams["n_shared_experts"])
669
+ self.gguf_writer.add_expert_weights_scale(hparams["routed_scaling_factor"])
670
+ self.gguf_writer.add_expert_weights_norm(hparams["norm_topk_prob"])
671
+ self.gguf_writer.add_swiglu_clamp_exp([hparams["swiglu_limit"]] * self.block_count)
672
+ self.gguf_writer.add_swiglu_clamp_shexp([hparams["swiglu_limit"]] * self.block_count)
673
+
674
+ self.gguf_writer.add_indexer_head_count(hparams["index_n_heads"])
675
+ self.gguf_writer.add_indexer_key_length(hparams["index_head_dim"])
676
+ self.gguf_writer.add_indexer_top_k(hparams["index_topk"])
677
+
678
+ self.gguf_writer.add_attention_output_group_count(hparams["o_groups"])
679
+ self.gguf_writer.add_attention_output_lora_rank(hparams["o_lora_rank"])
680
+ self.gguf_writer.add_attention_compress_ratios(hparams["compress_ratios"])
681
+ self.gguf_writer.add_attention_compress_rope_freq_base(hparams["compress_rope_theta"])
682
+ self.gguf_writer.add_hyper_connection_count(hparams["hc_mult"])
683
+ self.gguf_writer.add_hyper_connection_sinkhorn_iterations(hparams["hc_sinkhorn_iters"])
684
+ self.gguf_writer.add_hyper_connection_epsilon(hparams["hc_eps"])
685
+ self.gguf_writer.add_hash_layer_count(hparams["num_hash_layers"])
686
+ if self.model_arch == gguf.MODEL_ARCH.DEEPSEEK4:
687
+ self.gguf_writer.add_embedding_length_out(hparams["hidden_size"] * hparams["hc_mult"])
688
+ if self.mtp_only and (num_nextn_predict_layers := hparams.get("num_nextn_predict_layers", 0)) > 0:
689
+ self.gguf_writer.add_nextn_predict_layers(num_nextn_predict_layers)
690
+
691
+ def dequant_model(self):
692
+ fp8_dtypes = self._float8_dtypes()
693
+ tensors_to_remove: list[str] = []
694
+
695
+ def dequant_fp8_weight(weight: Tensor, scale: Tensor) -> Tensor:
696
+ out_features, in_features = weight.shape
697
+ scale_f = self._e8m0_to_float(scale)
698
+ scale_f = scale_f.repeat_interleave(128, 0)[:out_features]
699
+ scale_f = scale_f.repeat_interleave(128, 1)[:, :in_features]
700
+ return weight.float() * scale_f
701
+
702
+ for name in list(self.model_tensors.keys()):
703
+ if not name.endswith(".scale"):
704
+ continue
705
+ weight_name = name.removesuffix(".scale") + ".weight"
706
+ if weight_name not in self.model_tensors:
707
+ continue
708
+
709
+ weight = self.model_tensors[weight_name]
710
+ scale = self.model_tensors[name]
711
+ if weight().dtype not in fp8_dtypes:
712
+ continue
713
+
714
+ self.model_tensors[weight_name] = lambda w=weight, s=scale: dequant_fp8_weight(w(), s())
715
+ self._dsv4_fp8_dequantized.add(weight_name)
716
+ tensors_to_remove.append(name)
717
+
718
+ for name in tensors_to_remove:
719
+ del self.model_tensors[name]
720
+
721
+ def _write_mxfp4_expert_tensor(self, bid: int, proj: str, tensor_key: gguf.MODEL_TENSOR) -> list[str]:
722
+ n_experts = self.hparams["n_routed_experts"]
723
+ data: np.ndarray | None = None
724
+ consumed: list[str] = []
725
+
726
+ for eid in range(n_experts):
727
+ weight_name = f"layers.{bid}.ffn.experts.{eid}.{proj}.weight"
728
+ scale_name = f"layers.{bid}.ffn.experts.{eid}.{proj}.scale"
729
+ if weight_name not in self.model_tensors or scale_name not in self.model_tensors:
730
+ raise KeyError(f"Missing routed expert tensors for {weight_name}")
731
+
732
+ weight = LazyTorchTensor.to_eager(self.model_tensors[weight_name]())
733
+ scale = LazyTorchTensor.to_eager(self.model_tensors[scale_name]())
734
+ packed = self.repack_mxfp4_blocks(weight, scale)
735
+ if data is None:
736
+ data = np.empty((n_experts, *packed.shape), dtype=packed.dtype)
737
+ data[eid] = packed
738
+ consumed.extend((weight_name, scale_name))
739
+
740
+ assert data is not None
741
+ new_name = self.format_tensor_name(tensor_key, bid)
742
+ shape = gguf.quant_shape_from_byte_shape(data.shape, gguf.GGMLQuantizationType.MXFP4)
743
+ logger.info(f"{new_name}: repacked routed experts to MXFP4, shape = {{{', '.join(str(n) for n in reversed(shape))}}}")
744
+ self.gguf_writer.add_tensor(new_name, data, raw_dtype=gguf.GGMLQuantizationType.MXFP4)
745
+
746
+ return consumed
747
+
748
+ def _write_hash_routing_tensors(self) -> list[str]:
749
+ consumed: list[str] = []
750
+
751
+ for bid in range(self.hparams["num_hash_layers"]):
752
+ name = f"layers.{bid}.ffn.gate.tid2eid"
753
+ if name not in self.model_tensors:
754
+ raise KeyError(f"Missing hash routing tensor {name}")
755
+
756
+ data_torch = LazyTorchTensor.to_eager(self.model_tensors[name]())
757
+ data = data_torch.to(torch.int32).cpu().numpy()
758
+ new_name = self.format_tensor_name(gguf.MODEL_TENSOR.FFN_GATE_TID2EID, bid, ".weight")
759
+ logger.info(f"{new_name}: converted hash routing table to I32, shape = {{{', '.join(str(n) for n in reversed(data.shape))}}}")
760
+ self.gguf_writer.add_tensor(new_name, data)
761
+ consumed.append(name)
762
+
763
+ return consumed
764
+
765
+ def generate_extra_tensors(self) -> Iterable[tuple[str, Tensor]]:
766
+ if self._dsv4_mxfp4_generated:
767
+ return ()
768
+
769
+ consumed: list[str] = []
770
+ main_layers = self.hparams["num_hidden_layers"]
771
+ if not self.mtp_only:
772
+ consumed.extend(self._write_hash_routing_tensors())
773
+ elif self.hparams["num_hash_layers"] > 0:
774
+ for bid in range(self.hparams["num_hash_layers"]):
775
+ name = f"layers.{bid}.ffn.gate.tid2eid"
776
+ if name in self.model_tensors:
777
+ consumed.extend(self._write_hash_routing_tensors())
778
+ break
779
+
780
+ for bid in range(self.block_count):
781
+ if self.mtp_only and bid < main_layers:
782
+ continue
783
+ consumed.extend(self._write_mxfp4_expert_tensor(bid, "w1", gguf.MODEL_TENSOR.FFN_GATE_EXP))
784
+ consumed.extend(self._write_mxfp4_expert_tensor(bid, "w2", gguf.MODEL_TENSOR.FFN_DOWN_EXP))
785
+ consumed.extend(self._write_mxfp4_expert_tensor(bid, "w3", gguf.MODEL_TENSOR.FFN_UP_EXP))
786
+
787
+ for bid in range(main_layers, self.block_count):
788
+ e_name = f"layers.{bid}.nextn.e_proj.weight"
789
+ h_name = f"layers.{bid}.nextn.h_proj.weight"
790
+ if e_name not in self.model_tensors and h_name not in self.model_tensors:
791
+ continue
792
+ if e_name not in self.model_tensors or h_name not in self.model_tensors:
793
+ raise KeyError(f"Missing DeepSeek-V4 MTP e/h projection pair for block {bid}")
794
+
795
+ e_proj = LazyTorchTensor.to_eager(self.model_tensors[e_name]())
796
+ h_proj = LazyTorchTensor.to_eager(self.model_tensors[h_name]())
797
+ yield (f"layers.{bid}.nextn.eh_proj.weight", torch.cat((e_proj, h_proj), dim=1).contiguous())
798
+ consumed.extend((e_name, h_name))
799
+
800
+ for name in consumed:
801
+ del self.model_tensors[name]
802
+
803
+ self._dsv4_mxfp4_generated = True
804
+ return ()
805
+
806
+ def _format_dsv4_tensor_name(self, key: gguf.MODEL_TENSOR, bid: int | None, suffix: str = ".weight") -> str:
807
+ return self.format_tensor_name(key, bid, suffix)
808
+
809
+ def _map_dsv4_tensor_name(self, name: str, bid: int | None) -> tuple[gguf.MODEL_TENSOR, str]:
810
+ root_map: dict[str, tuple[gguf.MODEL_TENSOR, str]] = {
811
+ "embed.weight": (gguf.MODEL_TENSOR.TOKEN_EMBD, ".weight"),
812
+ "norm.weight": (gguf.MODEL_TENSOR.OUTPUT_NORM, ".weight"),
813
+ "head.weight": (gguf.MODEL_TENSOR.OUTPUT, ".weight"),
814
+ "hc_head_fn": (gguf.MODEL_TENSOR.HC_HEAD_FN, ".weight"),
815
+ "hc_head_base": (gguf.MODEL_TENSOR.HC_HEAD_BASE, ".weight"),
816
+ "hc_head_scale": (gguf.MODEL_TENSOR.HC_HEAD_SCALE, ".weight"),
817
+ }
818
+ if name in root_map:
819
+ return root_map[name]
820
+
821
+ match = re.match(r"layers\.(\d+)\.(.+)$", name)
822
+ if match is None:
823
+ raise ValueError(f"Unsupported DeepSeek-V4 tensor {name!r}")
824
+
825
+ layer = int(match.group(1))
826
+ if bid != layer:
827
+ raise ValueError(f"Tensor {name!r} parsed bid {bid} but layer name has {layer}")
828
+
829
+ layer_map: dict[str, tuple[gguf.MODEL_TENSOR, str]] = {
830
+ "hc_attn_fn": (gguf.MODEL_TENSOR.HC_ATTN_FN, ".weight"),
831
+ "hc_attn_base": (gguf.MODEL_TENSOR.HC_ATTN_BASE, ".weight"),
832
+ "hc_attn_scale": (gguf.MODEL_TENSOR.HC_ATTN_SCALE, ".weight"),
833
+ "hc_ffn_fn": (gguf.MODEL_TENSOR.HC_FFN_FN, ".weight"),
834
+ "hc_ffn_base": (gguf.MODEL_TENSOR.HC_FFN_BASE, ".weight"),
835
+ "hc_ffn_scale": (gguf.MODEL_TENSOR.HC_FFN_SCALE, ".weight"),
836
+ "attn.attn_sink": (gguf.MODEL_TENSOR.ATTN_SINKS, ".weight"),
837
+ "attn.wq_a.weight": (gguf.MODEL_TENSOR.ATTN_Q_A, ".weight"),
838
+ "attn.wq_b.weight": (gguf.MODEL_TENSOR.ATTN_Q_B, ".weight"),
839
+ "attn.q_norm.weight": (gguf.MODEL_TENSOR.ATTN_Q_A_NORM, ".weight"),
840
+ "attn.wkv.weight": (gguf.MODEL_TENSOR.ATTN_KV, ".weight"),
841
+ "attn.kv_norm.weight": (gguf.MODEL_TENSOR.ATTN_KV_NORM, ".weight"),
842
+ "attn.wo_a.weight": (gguf.MODEL_TENSOR.ATTN_OUT_A, ".weight"),
843
+ "attn.wo_b.weight": (gguf.MODEL_TENSOR.ATTN_OUT_B, ".weight"),
844
+ "attn.compressor.ape": (gguf.MODEL_TENSOR.ATTN_COMPRESSOR_APE, ".weight"),
845
+ "attn.compressor.wkv.weight": (gguf.MODEL_TENSOR.ATTN_COMPRESSOR_WKV, ".weight"),
846
+ "attn.compressor.wgate.weight": (gguf.MODEL_TENSOR.ATTN_COMPRESSOR_WGATE, ".weight"),
847
+ "attn.compressor.norm.weight": (gguf.MODEL_TENSOR.ATTN_COMPRESSOR_NORM, ".weight"),
848
+ "attn.indexer.wq_b.weight": (gguf.MODEL_TENSOR.INDEXER_ATTN_Q_B, ".weight"),
849
+ "attn.indexer.weights_proj.weight": (gguf.MODEL_TENSOR.INDEXER_PROJ, ".weight"),
850
+ "attn.indexer.compressor.ape": (gguf.MODEL_TENSOR.INDEXER_COMPRESSOR_APE, ".weight"),
851
+ "attn.indexer.compressor.wkv.weight": (gguf.MODEL_TENSOR.INDEXER_COMPRESSOR_WKV, ".weight"),
852
+ "attn.indexer.compressor.wgate.weight": (gguf.MODEL_TENSOR.INDEXER_COMPRESSOR_WGATE, ".weight"),
853
+ "attn.indexer.compressor.norm.weight": (gguf.MODEL_TENSOR.INDEXER_COMPRESSOR_NORM, ".weight"),
854
+ "attn_norm.weight": (gguf.MODEL_TENSOR.ATTN_NORM, ".weight"),
855
+ "ffn_norm.weight": (gguf.MODEL_TENSOR.FFN_NORM, ".weight"),
856
+ "ffn.gate.weight": (gguf.MODEL_TENSOR.FFN_GATE_INP, ".weight"),
857
+ "ffn.gate.bias": (gguf.MODEL_TENSOR.FFN_EXP_PROBS_B, ".bias"),
858
+ "ffn.gate.bias_vl": (gguf.MODEL_TENSOR.FFN_EXP_PROBS_B_VL, ".bias"),
859
+ "ffn.gate.tid2eid": (gguf.MODEL_TENSOR.FFN_GATE_TID2EID, ".weight"),
860
+ "ffn.shared_experts.w1.weight": (gguf.MODEL_TENSOR.FFN_GATE_SHEXP, ".weight"),
861
+ "ffn.shared_experts.w2.weight": (gguf.MODEL_TENSOR.FFN_DOWN_SHEXP, ".weight"),
862
+ "ffn.shared_experts.w3.weight": (gguf.MODEL_TENSOR.FFN_UP_SHEXP, ".weight"),
863
+ "nextn.eh_proj.weight": (gguf.MODEL_TENSOR.NEXTN_EH_PROJ, ".weight"),
864
+ "nextn.enorm.weight": (gguf.MODEL_TENSOR.NEXTN_ENORM, ".weight"),
865
+ "nextn.hnorm.weight": (gguf.MODEL_TENSOR.NEXTN_HNORM, ".weight"),
866
+ "nextn.shared_head_norm.weight": (gguf.MODEL_TENSOR.NEXTN_SHARED_HEAD_NORM, ".weight"),
867
+ "nextn.embed_tokens.weight": (gguf.MODEL_TENSOR.NEXTN_EMBED_TOKENS, ".weight"),
868
+ "nextn.shared_head_head.weight": (gguf.MODEL_TENSOR.NEXTN_SHARED_HEAD_HEAD, ".weight"),
869
+ }
870
+
871
+ tensor_name = match.group(2)
872
+ if tensor_name in layer_map:
873
+ return layer_map[tensor_name]
874
+
875
+ if re.match(r"ffn\.experts\.\d+\.w[123]\.(weight|scale)$", tensor_name):
876
+ return gguf.MODEL_TENSOR.FFN_GATE_EXP, ".weight"
877
+
878
+ raise ValueError(f"Unsupported DeepSeek-V4 tensor {name!r}")
879
+
880
+ def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]:
881
+ if re.match(r"layers\.\d+\.ffn\.experts\.\d+\.w[123]\.(weight|scale)$", name):
882
+ return []
883
+
884
+ # hash layers route text tokens via tid2eid and image tokens via bias_vl; gate.bias is unused
885
+ if name.endswith(".ffn.gate.bias") and bid is not None and bid < self.hparams["num_hash_layers"]:
886
+ return []
887
+
888
+ tensor_key, suffix = self._map_dsv4_tensor_name(name, bid)
889
+ if tensor_key == gguf.MODEL_TENSOR.FFN_GATE_TID2EID:
890
+ return []
891
+
892
+ return [(self._format_dsv4_tensor_name(tensor_key, bid, suffix), data_torch)]
893
+
894
+ def tensor_force_quant(self, name: str, new_name: str, bid: int | None, n_dims: int) -> gguf.GGMLQuantizationType | bool:
895
+ del bid # unused
896
+
897
+ if name in self._dsv4_fp8_dequantized and n_dims >= 2:
898
+ return gguf.GGMLQuantizationType.Q8_0
899
+ if new_name.endswith(".nextn.eh_proj.weight"):
900
+ return gguf.GGMLQuantizationType.Q8_0
901
+ if name in self._dsv4_f32_tensors:
902
+ return gguf.GGMLQuantizationType.F32
903
+ if name in self._dsv4_bf16_tensors and n_dims >= 2:
904
+ return gguf.GGMLQuantizationType.BF16
905
+
906
+ return False
907
+
908
+ def prepare_metadata(self, vocab_only: bool):
909
+ from_dir = self.fname_out.is_dir()
910
+ super().prepare_metadata(vocab_only=vocab_only)
911
+
912
+ if not self.mtp_only or not from_dir:
913
+ return
914
+
915
+ output_type: str = self.ftype.name.partition("_")[2]
916
+ fname_default: str = gguf.naming_convention(
917
+ self.metadata.name, self.metadata.basename, self.metadata.finetune,
918
+ self.metadata.version, size_label=None, output_type=output_type, model_type=None)
919
+ self.fname_out = self.fname_out.parent / f"mtp-{fname_default}.gguf"
920
+
921
+ def prepare_tensors(self):
922
+ super().prepare_tensors()
923
+ self._is_mxfp4 = True
924
+ self.ftype = gguf.LlamaFileType.MOSTLY_MXFP4_MOE
925
+
926
+
927
+ @ModelBase.register("DeepseekV4DSparkModel")
928
+ @ModelBase.example("deepseek-ai/DeepSeek-V4-Flash-DSpark")
929
+ class DeepseekV4DSparkModel(DeepseekV4Model):
930
+ model_arch = gguf.MODEL_ARCH.DFLASH
931
+
932
+ _DSPARK_ROOT_MAP: dict[str, tuple[gguf.MODEL_TENSOR, str]] = {
933
+ "main_proj.weight": (gguf.MODEL_TENSOR.FC, ".weight"),
934
+ "main_norm.weight": (gguf.MODEL_TENSOR.ENC_OUTPUT_NORM, ".weight"),
935
+ "markov_head.markov_w1.weight": (gguf.MODEL_TENSOR.DSPARK_MARKOV_W1, ".weight"),
936
+ "markov_head.markov_w2.weight": (gguf.MODEL_TENSOR.DSPARK_MARKOV_W2, ".weight"),
937
+ "confidence_head.proj.weight": (gguf.MODEL_TENSOR.DSPARK_CONF_PROJ, ".weight"),
938
+ }
939
+
940
+ def __init__(self, *args, **kwargs):
941
+ super().__init__(*args, **kwargs)
942
+
943
+ self.block_count = 1 + max(
944
+ int(match.group(1)) for name in self.model_tensors
945
+ if (match := re.match(r"layers\.(\d+)\.", name))
946
+ )
947
+ self.tensor_map = gguf.get_tensor_name_map(self.model_arch, self.block_count)
948
+
949
+ self.hparams["compress_ratios"] = [0] * self.block_count
950
+ self.hparams["num_hash_layers"] = 0
951
+
952
+ def index_tensors(self, remote_hf_model_id: str | None = None) -> dict[str, Callable[[], Tensor]]:
953
+ if remote_hf_model_id is None:
954
+ return super().index_tensors()
955
+
956
+ with open(self.dir_model / "model.safetensors.index.json", "r", encoding="utf-8") as f:
957
+ weight_map = json.load(f)["weight_map"]
958
+
959
+ part_names = sorted({
960
+ part_name for name, part_name in weight_map.items()
961
+ if name.startswith("mtp.")
962
+ })
963
+ tensors: dict[str, Callable[[], Tensor]] = {}
964
+
965
+ for part_name in part_names:
966
+ from huggingface_hub import hf_hub_download
967
+
968
+ logger.info("gguf: caching remote DSpark part '%s'", part_name)
969
+ part_path = Path(hf_hub_download(repo_id=remote_hf_model_id, filename=part_name))
970
+ with gguf.utility.SafetensorsLocal(part_path) as model_part:
971
+ for name in model_part:
972
+ data = model_part[name]
973
+ data_gen = lambda data=data: LazyTorchTensor.from_local_tensor(data) # noqa: E731
974
+ if titem := self.filter_tensors((name, data_gen)):
975
+ tensor_name, tensor_gen = titem
976
+ tensors[tensor_name] = tensor_gen
977
+
978
+ return tensors
979
+
980
+ @classmethod
981
+ def filter_tensors(cls, item: tuple[str, Callable[[], Tensor]]) -> tuple[str, Callable[[], Tensor]] | None:
982
+ name, gen = item
983
+ if not name.startswith("mtp."):
984
+ return None
985
+ return super().filter_tensors((cls._rekey_mtp_tensor_name(name), gen))
986
+
987
+ @staticmethod
988
+ def _rekey_mtp_tensor_name(name: str) -> str:
989
+ match = re.match(r"mtp\.(\d+)\.(.+)$", name)
990
+ if match is None:
991
+ raise ValueError(f"Unexpected DSpark tensor {name!r}")
992
+
993
+ stage, rest = match.group(1), match.group(2)
994
+ root_names = (
995
+ "main_proj.scale",
996
+ "norm.weight",
997
+ "hc_head_fn",
998
+ "hc_head_base",
999
+ "hc_head_scale",
1000
+ )
1001
+ if rest in DeepseekV4DSparkModel._DSPARK_ROOT_MAP or rest in root_names:
1002
+ return rest
1003
+ return f"layers.{stage}.{rest}"
1004
+
1005
+ def _map_dsv4_tensor_name(self, name: str, bid: int | None) -> tuple[gguf.MODEL_TENSOR, str]:
1006
+ if name in self._DSPARK_ROOT_MAP:
1007
+ return self._DSPARK_ROOT_MAP[name]
1008
+ return super()._map_dsv4_tensor_name(name, bid)
1009
+
1010
+ def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]:
1011
+ # the DFlash draft uses the plain exp-probs bias (ffn.gate.bias -> FFN_EXP_PROBS_B);
1012
+ # the mtmd-only hash routing tensors (bias_vl, tid2eid) are not part of the DFLASH arch
1013
+ if name.endswith(".ffn.gate.bias_vl"):
1014
+ return
1015
+ yield from super().modify_tensors(data_torch, name, bid)
1016
+
1017
+ def set_vocab(self):
1018
+ if self.target_model_dir is None:
1019
+ raise ValueError("DeepSeek-V4 DSpark requires --target-model-dir with the target tokenizer")
1020
+
1021
+ original_dir = self.dir_model
1022
+ try:
1023
+ self.dir_model = self.target_model_dir
1024
+ super().set_vocab()
1025
+ finally:
1026
+ self.dir_model = original_dir
1027
+
1028
+ self.gguf_writer.add_mask_token_id(self.hparams["dspark_noise_token_id"])
1029
+
1030
+ def set_gguf_parameters(self):
1031
+ super().set_gguf_parameters()
1032
+
1033
+ self.gguf_writer.add_block_size(self.hparams["dspark_block_size"])
1034
+ self.gguf_writer.add_target_layers([layer + 1 for layer in self.hparams["dspark_target_layer_ids"]])
1035
+
1036
+
1037
+ @ModelBase.register("DeepseekV4ForCausalLM")
1038
+ @ModelBase.example("deepseek-ai/DeepSeek-V4-Flash-Vision-Exp")
1039
+ class DeepseekV4FlashVisionModel(MmprojModel):
1040
+ def __init__(self, *args, **kwargs):
1041
+ super().__init__(*args, **kwargs)
1042
+ assert self.hparams_vision is not None
1043
+ # no preprocessor_config.json in the repo; normalization is (x/255 - 0.5) / 0.5
1044
+ # ref: inference/image_processor.py (load_image)
1045
+ self.preprocessor_config = {
1046
+ "image_mean": [0.5, 0.5, 0.5],
1047
+ "image_std": [0.5, 0.5, 0.5],
1048
+ **self.preprocessor_config,
1049
+ }
1050
+
1051
+ def get_vision_config(self) -> dict[str, Any] | None:
1052
+ cfg = self.global_config
1053
+ if cfg.get("vision_n_layers", 0) == 0:
1054
+ raise ValueError("DeepseekV4FlashVisionModel requires vision_n_layers > 0 in the model config")
1055
+ return {
1056
+ "num_hidden_layers": cfg["vision_n_layers"],
1057
+ "hidden_size": cfg["vision_dim"],
1058
+ "num_attention_heads": cfg["vision_n_heads"],
1059
+ "intermediate_size": cfg["vision_inter_dim"],
1060
+ "patch_size": cfg["vision_patch_size"],
1061
+ # dynamic resolution; only used for compat / warmup
1062
+ "image_size": cfg["vision_patch_size"] * cfg["vision_downsample_ratio"] * 16,
1063
+ "rope_theta": cfg.get("vision_rope_theta", 10000.0),
1064
+ "downsample_ratio": cfg["vision_downsample_ratio"],
1065
+ "min_pixels": cfg["vision_min_pixels"],
1066
+ }
1067
+
1068
+ def set_gguf_parameters(self):
1069
+ super().set_gguf_parameters()
1070
+ assert self.hparams_vision is not None
1071
+ self.gguf_writer.add_clip_projector_type(gguf.VisionProjectorType.DEEPSEEK4V)
1072
+ # vision RMSNorm eps is the pytorch default, NOT the LLM's rms_norm_eps (1e-20)
1073
+ # ref: inference/vision.py (RMSNorm)
1074
+ self.gguf_writer.add_vision_attention_layernorm_eps(1e-6)
1075
+ self.gguf_writer.add_vision_use_silu(True) # SwiGLU MLP
1076
+ self.gguf_writer.add_vision_projector_scale_factor(self.hparams_vision["downsample_ratio"])
1077
+ self.gguf_writer.add_vision_min_pixels(self.hparams_vision["min_pixels"])
1078
+ # hardcoded on the C++ side (see PROJECTOR_TYPE_DEEPSEEK4V in clip.cpp)
1079
+ # if future models use different values, add GGUF keys for those
1080
+ assert self.global_config["vision_max_n_token"] == 384
1081
+ assert self.global_config["vision_max_wh_ratio"] == 8
1082
+
1083
+ @classmethod
1084
+ def filter_tensors(cls, item: tuple[str, Callable[[], Tensor]]) -> tuple[str, Callable[[], Tensor]] | None:
1085
+ name, _ = item
1086
+ if not (name.startswith(("vision.", "aligner.", "image_"))):
1087
+ return None
1088
+ return super().filter_tensors(item)
1089
+
1090
+ def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]:
1091
+ assert self.hparams_vision is not None
1092
+ if name == "vision.patch_embed.proj.weight":
1093
+ # nn.Linear over flattened (3, p, p) patches == conv2d weight
1094
+ p = self.hparams_vision["patch_size"]
1095
+ data_torch = data_torch.reshape(data_torch.shape[0], 3, p, p)
1096
+
1097
+ if ".mlp.w1." in name:
1098
+ # fused SwiGLU gate+up
1099
+ gate, up = data_torch.chunk(2, dim=0)
1100
+ yield from super().modify_tensors(gate, name.replace("w1", "w1_gate"), bid)
1101
+ yield from super().modify_tensors(up, name.replace("w1", "w1_up"), bid)
1102
+ return
1103
+
1104
+ yield from super().modify_tensors(data_torch, name, bid)
conversion/dots1.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import TYPE_CHECKING
4
+
5
+ if TYPE_CHECKING:
6
+ from torch import Tensor
7
+
8
+ from .base import ModelBase, gguf
9
+
10
+ from .qwen import Qwen2MoeModel
11
+
12
+
13
+ @ModelBase.register("Dots1ForCausalLM")
14
+ @ModelBase.example("rednote-hilab/dots.llm1.inst")
15
+ class Dots1Model(Qwen2MoeModel):
16
+ model_arch = gguf.MODEL_ARCH.DOTS1
17
+
18
+ def __init__(self, *args, **kwargs):
19
+ super().__init__(*args, **kwargs)
20
+ self.hparams["num_experts"] = self.hparams["n_routed_experts"]
21
+
22
+ def set_gguf_parameters(self):
23
+ super().set_gguf_parameters()
24
+ self.gguf_writer.add_leading_dense_block_count(self.hparams["first_k_dense_replace"])
25
+ self.gguf_writer.add_expert_shared_count(self.hparams["n_shared_experts"])
26
+ self.gguf_writer.add_expert_weights_scale(self.hparams["routed_scaling_factor"])
27
+ self.gguf_writer.add_expert_weights_norm(self.hparams["norm_topk_prob"])
28
+
29
+ def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None):
30
+ if "shared_experts" in name:
31
+ yield from ModelBase.modify_tensors(self, data_torch, name, bid)
32
+ else:
33
+ yield from super().modify_tensors(data_torch, name, bid)
conversion/dots3.py ADDED
@@ -0,0 +1,323 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import math
4
+ import re
5
+
6
+ import torch
7
+
8
+ from typing import TYPE_CHECKING, Any, Callable, Iterable
9
+
10
+ if TYPE_CHECKING:
11
+ from torch import Tensor
12
+
13
+ from .base import MmprojModel, ModelBase, gguf
14
+
15
+ from .deepseek import DeepseekV2Model
16
+
17
+
18
+ @ModelBase.register("Dots3NoteForCausalLM", "Dots3NoteForConditionalGeneration", "Dots3NoteTextForCausalLM")
19
+ class Dots3NoteModel(DeepseekV2Model):
20
+ model_arch = gguf.MODEL_ARCH.DOTS3NOTE
21
+ skip_mtp = False
22
+ supports_mtp_export = True
23
+
24
+ # trunk layer count, stashed before indexing for filter_tensors (mirrors DeepseekV32Model)
25
+ _n_main_layers: int | None = None
26
+
27
+ def index_tensors(self, remote_hf_model_id: str | None = None):
28
+ type(self)._n_main_layers = self.hparams["num_hidden_layers"]
29
+ return super().index_tensors(remote_hf_model_id=remote_hf_model_id)
30
+
31
+ def __init__(self, *args, **kwargs):
32
+ super().__init__(*args, **kwargs)
33
+
34
+ hparams = self.hparams
35
+
36
+ # config file doesn't specify MTP block, detect it from model weight
37
+ self.n_nextn = 1 if "model.mtp.embed_tokens.weight" in self.model_tensors else 0
38
+ if self.n_nextn:
39
+ self.block_count += self.n_nextn
40
+ self.tensor_map = gguf.get_tensor_name_map(self.model_arch, self.block_count)
41
+
42
+ self.layer_types = hparams["layer_types"]
43
+ if len(self.layer_types) < hparams["num_hidden_layers"]:
44
+ raise ValueError("layer_types is shorter than num_hidden_layers")
45
+
46
+ if hparams.get("use_dsa", True) is not True:
47
+ raise ValueError("dots3-note conversion requires use_dsa=true")
48
+ if hparams.get("normalization", "RMSNorm") != "RMSNorm" or hparams.get("final_norm", "RMSNorm") != "RMSNorm":
49
+ raise ValueError("dots3-note conversion only supports RMSNorm")
50
+ if hparams.get("k_rope_only_layernorm", True) is not True:
51
+ raise ValueError("dots3-note conversion requires k_rope_only_layernorm=true")
52
+ if hparams.get("topk_method", "noaux_tc") != "noaux_tc" or hparams.get("scoring_func") != "sigmoid":
53
+ raise ValueError("dots3-note conversion only supports noaux_tc/sigmoid expert gating")
54
+ if hparams.get("n_group", 1) != 1 or hparams.get("topk_group", 1) != 1:
55
+ raise ValueError("dots3-note conversion does not support grouped expert routing")
56
+ if hparams.get("use_dynamic_rsf", False) or hparams.get("moe_gating_fp32", False):
57
+ raise ValueError("dots3-note conversion does not support use_dynamic_rsf/moe_gating_fp32")
58
+ for key in ("attention_gate_type", "swa_attention_gate_type"):
59
+ if hparams.get(key, "headwise") != "headwise":
60
+ raise ValueError(f"dots3-note conversion only supports headwise attention gate, got {key}={hparams.get(key)!r}")
61
+ if hparams["swa_qk_nope_head_dim"] + hparams["swa_qk_rope_head_dim"] != hparams.get("swa_head_dim", 256):
62
+ raise ValueError("swa_head_dim must equal swa_qk_nope_head_dim + swa_qk_rope_head_dim")
63
+ if hparams["swa_qk_rope_head_dim"] != hparams["qk_rope_head_dim"]:
64
+ # both layer kinds share a single rope_dimension_count
65
+ raise ValueError("swa_qk_rope_head_dim must match qk_rope_head_dim")
66
+
67
+ self.apply_lora_rescale = hparams.get("apply_mla_qkv_lora_rescale", False)
68
+
69
+ def _is_swa_layer(self, bid: int) -> bool:
70
+ if bid >= self.hparams["num_hidden_layers"]:
71
+ # note: the NextN/MTP block uses the sliding-attention MLA
72
+ return True
73
+ return self.layer_types[bid] == "sliding_attention"
74
+
75
+ def set_vocab(self):
76
+ from transformers import AutoTokenizer
77
+ tokenizer = AutoTokenizer.from_pretrained(self.dir_model)
78
+ special_vocab = gguf.SpecialVocab(self.dir_model, load_merges=True)
79
+ tokens, toktypes, tokpre = self.get_vocab_base()
80
+ self.gguf_writer.add_tokenizer_model("gpt2")
81
+ self.gguf_writer.add_tokenizer_pre(tokpre)
82
+ self.gguf_writer.add_token_list(tokens)
83
+ self.gguf_writer.add_token_types(toktypes)
84
+ special_vocab._set_special_token("eot", tokenizer.get_added_vocab()["<|endofassistant|>"]) # ty: ignore[unresolved-attribute]
85
+ special_vocab.add_to_gguf(self.gguf_writer)
86
+
87
+ @classmethod
88
+ def filter_tensors(cls, item: tuple[str, Callable[[], Tensor]]) -> tuple[str, Callable[[], Tensor]] | None:
89
+ if (titem := super().filter_tensors(item)) is None:
90
+ return None
91
+ name, gen = titem
92
+ if name.startswith(("vision_encoder.", "audio_encoder.")):
93
+ return None
94
+
95
+ assert cls._n_main_layers is not None
96
+ is_mtp = name.startswith("model.mtp.") or \
97
+ ((m := re.match(r"model\.layers\.(\d+)\.", name)) is not None and int(m.group(1)) >= cls._n_main_layers)
98
+
99
+ # --no-mtp: drop the NextN/MTP block; --mtp: keep only that block plus the shared embeddings/norm/lm_head
100
+ if is_mtp and cls.no_mtp:
101
+ return None
102
+ if cls.mtp_only and not is_mtp and name not in (
103
+ "model.embed_tokens.weight", "model.norm.weight", "lm_head.weight",
104
+ ):
105
+ return None
106
+
107
+ return name, gen
108
+
109
+ def set_gguf_parameters(self):
110
+ hparams = self.hparams
111
+
112
+ # head_count is a per-layer array because the two layer kinds have different head counts
113
+ n_layer = hparams["num_hidden_layers"]
114
+ hparams["num_attention_heads"] = [
115
+ hparams["swa_num_attention_heads"] if self._is_swa_layer(il) else hparams["num_attention_heads"]
116
+ for il in range(self.block_count)
117
+ ]
118
+
119
+ # prevent the base class from emitting key/value_length from the unused head_dim
120
+ hparams.pop("head_dim", None)
121
+
122
+ super().set_gguf_parameters()
123
+
124
+ # MLA geometry of the sliding-window layers (rope.freq_base_swa is emitted by the base class)
125
+ swa_kv_lora_rank = hparams["swa_kv_lora_rank"]
126
+ self.gguf_writer.add_sliding_window(hparams["sliding_window_size"])
127
+ self.gguf_writer.add_sliding_window_pattern([self._is_swa_layer(il) for il in range(n_layer)])
128
+ self.gguf_writer.add_kv_lora_rank_swa(swa_kv_lora_rank)
129
+ self.gguf_writer.add_key_length_swa(swa_kv_lora_rank + hparams["swa_qk_rope_head_dim"])
130
+ self.gguf_writer.add_value_length_swa(swa_kv_lora_rank)
131
+ self.gguf_writer.add_key_length_mla_swa(hparams["swa_qk_nope_head_dim"] + hparams["swa_qk_rope_head_dim"])
132
+ self.gguf_writer.add_value_length_mla_swa(hparams["swa_v_head_dim"])
133
+ if hparams["swa_q_lora_rank"] != hparams["q_lora_rank"]:
134
+ raise ValueError("dots3-note conversion assumes a shared q_lora_rank for both layer kinds")
135
+
136
+ if self.n_nextn:
137
+ self.gguf_writer.add_nextn_predict_layers(self.n_nextn)
138
+
139
+ # DSA indexer (full-attention layers only)
140
+ self.gguf_writer.add_indexer_head_count(hparams["index_n_heads"])
141
+ self.gguf_writer.add_indexer_key_length(hparams["index_head_dim"])
142
+ self.gguf_writer.add_indexer_top_k(hparams["index_topk"])
143
+ self.gguf_writer.add_indexer_types([not self._is_swa_layer(il) for il in range(n_layer)])
144
+
145
+ def prepare_metadata(self, vocab_only: bool):
146
+ from_dir = self.fname_out.is_dir()
147
+ super().prepare_metadata(vocab_only=vocab_only)
148
+
149
+ if not self.mtp_only or not from_dir:
150
+ return
151
+
152
+ output_type: str = self.ftype.name.partition("_")[2]
153
+ fname_default: str = gguf.naming_convention(
154
+ self.metadata.name, self.metadata.basename, self.metadata.finetune,
155
+ self.metadata.version, size_label=None, output_type=output_type, model_type=None)
156
+ self.fname_out = self.fname_out.parent / f"mtp-{fname_default}.gguf"
157
+
158
+ def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]:
159
+ # move the MTP token embedding into the NextN block so the standard nextn mapping picks it up
160
+ if name == "model.mtp.embed_tokens.weight":
161
+ name = f"model.layers.{self.hparams['num_hidden_layers']}.embed_tokens.weight"
162
+ bid = self.hparams["num_hidden_layers"]
163
+
164
+ # fold the activation rescale sqrt(n_embd/lora_rank) into the preceding RMSNorm weight
165
+ # this also covers the indexer wq_b, which reads the same rescaled q_lora activation
166
+ if self.apply_lora_rescale and bid is not None:
167
+ if name.endswith("q_a_layernorm.weight"):
168
+ data_torch = data_torch * math.sqrt(self.hparams["hidden_size"] / self.hparams["q_lora_rank"])
169
+ elif name.endswith("kv_a_layernorm.weight"):
170
+ rank = self.hparams["swa_kv_lora_rank"] if self._is_swa_layer(bid) else self.hparams["kv_lora_rank"]
171
+ data_torch = data_torch * math.sqrt(self.hparams["hidden_size"] / rank)
172
+
173
+ # MLA absorption: split kv_b_proj into k_b (transposed) and v_b, per-layer-kind geometry
174
+ if name.endswith("kv_b_proj.weight"):
175
+ assert bid is not None
176
+ if self._is_swa_layer(bid):
177
+ n_head = self.hparams["swa_num_attention_heads"]
178
+ qk_nope_head_dim = self.hparams["swa_qk_nope_head_dim"]
179
+ v_head_dim = self.hparams["swa_v_head_dim"]
180
+ else:
181
+ n_head = self.hparams["num_attention_heads"]
182
+ qk_nope_head_dim = self.hparams["qk_nope_head_dim"]
183
+ v_head_dim = self.hparams["v_head_dim"]
184
+ if isinstance(n_head, list): # set_gguf_parameters turns this into a per-layer array
185
+ n_head = n_head[bid]
186
+
187
+ assert data_torch.shape[0] == n_head * (qk_nope_head_dim + v_head_dim)
188
+
189
+ kv_b = data_torch.view(n_head, qk_nope_head_dim + v_head_dim, data_torch.shape[-1])
190
+ k_b, v_b = kv_b.split([qk_nope_head_dim, v_head_dim], dim=1)
191
+ k_b = k_b.transpose(1, 2)
192
+
193
+ yield from ModelBase.modify_tensors(self, k_b, name.replace("kv_b_proj", "k_b_proj"), bid)
194
+ yield from ModelBase.modify_tensors(self, v_b, name.replace("kv_b_proj", "v_b_proj"), bid)
195
+ return
196
+
197
+ yield from super().modify_tensors(data_torch, name, bid)
198
+
199
+
200
+ @ModelBase.register("Dots3NoteForCausalLM", "Dots3NoteForConditionalGeneration")
201
+ class Dots3NoteMmprojModel(MmprojModel):
202
+ has_vision_encoder = True
203
+ has_audio_encoder = True
204
+
205
+ def __init__(self, *args, **kwargs):
206
+ super().__init__(*args, **kwargs)
207
+ assert self.hparams_vision is not None
208
+ assert self.hparams_audio is not None
209
+
210
+ # preprocessor_config.json nests the image params under vision_config
211
+ self.preprocessor_config = {**self.preprocessor_config, **self.preprocessor_config.get("vision_config", {})}
212
+
213
+ vis = self.hparams_vision
214
+ # in this config, hidden_size is the adapter output width; embed_dim is the tower width
215
+ vis["hidden_size"] = vis["embed_dim"]
216
+ vis["image_size"] = 0 # dynamic resolution
217
+ self.pyramid = [max(0, n) for n in vis["pyramid_num_routed"]]
218
+
219
+ if vis.get("adapter_type") != "patch_merger" or not vis.get("pre_pixel_shuffle"):
220
+ raise ValueError("dots3-note vision conversion requires adapter_type=patch_merger and pre_pixel_shuffle")
221
+ if vis.get("router_scoring_func", "sigmoid") != "sigmoid" or vis.get("router_scale", 1.0) != 1.0:
222
+ raise ValueError("dots3-note vision conversion only supports sigmoid routing with router_scale=1.0")
223
+ if vis.get("temporal_patch_size", 1) != 1 or vis.get("use_bias") or not vis.get("use_qk_norm"):
224
+ raise ValueError("unsupported dots3-note vision config variant")
225
+
226
+ aud = self.hparams_audio
227
+ if not aud.get("use_conv2d_stem") or not aud.get("use_rope") or not aud.get("use_rms_norm") or aud.get("use_causal"):
228
+ raise ValueError("unsupported dots3-note audio config variant")
229
+ if aud["whisper_config"].get("activation_function") != "swiglu":
230
+ raise ValueError("dots3-note audio conversion requires the swiglu activation")
231
+ if aud.get("merge_factor", 1) != 1 or aud.get("chunk_seconds") != 60:
232
+ raise ValueError("unsupported dots3-note audio chunking config")
233
+ # the graph hard-codes these rope parameters
234
+ rope = aud.get("rope_parameters", {})
235
+ if rope.get("partial_rotary_factor") != 0.5 or rope.get("rope_theta") != 10000.0:
236
+ raise ValueError("unsupported dots3-note audio rope config")
237
+
238
+ def get_audio_config(self) -> dict[str, Any] | None:
239
+ cfg = self.global_config.get("audio_config")
240
+ if cfg is not None:
241
+ # aliases so MmprojModel.find_aparam() / n_block_keys can resolve them
242
+ whisper = cfg["whisper_config"]
243
+ cfg["hidden_size"] = whisper["d_model"]
244
+ cfg["intermediate_size"] = whisper["encoder_ffn_dim"]
245
+ cfg["num_attention_heads"] = whisper["encoder_attention_heads"]
246
+ cfg["num_hidden_layers"] = whisper["encoder_layers"]
247
+ return cfg
248
+
249
+ def set_gguf_parameters(self):
250
+ super().set_gguf_parameters()
251
+ assert self.hparams_vision is not None
252
+ assert self.hparams_audio is not None
253
+
254
+ self.gguf_writer.add_clip_vision_projector_type(gguf.VisionProjectorType.DOTS3NOTE_V)
255
+ self.gguf_writer.add_vision_use_silu(True)
256
+ self.gguf_writer.add_vision_attention_layernorm_eps(self.hparams_vision["rms_norm_eps"])
257
+ self.gguf_writer.add_vision_spatial_merge_size(self.hparams_vision["spatial_merge_size"])
258
+ self.gguf_writer.add_vision_min_pixels(self.preprocessor_config["min_pixels"])
259
+ self.gguf_writer.add_vision_max_pixels(self.preprocessor_config["max_pixels"])
260
+ # pyramid MoE: per-block routed expert count, 0 = dense block
261
+ self.gguf_writer.add_vision_expert_count_per_layer(self.pyramid)
262
+ self.gguf_writer.add_vision_expert_used_count(int(self.hparams_vision["capacity_factor"]))
263
+
264
+ self.gguf_writer.add_clip_audio_projector_type(gguf.VisionProjectorType.DOTS3NOTE_A)
265
+ self.gguf_writer.add_audio_num_mel_bins(self.hparams_audio["whisper_config"]["num_mel_bins"])
266
+ self.gguf_writer.add_audio_attention_layernorm_eps(1e-6) # Dots3NoteAudioRMSNorm default
267
+
268
+ @classmethod
269
+ def filter_tensors(cls, item: tuple[str, Callable[[], Tensor]]) -> tuple[str, Callable[[], Tensor]] | None:
270
+ name, _ = item
271
+ if not name.startswith(("vision_encoder.", "audio_encoder.")):
272
+ return None
273
+ return super().filter_tensors(item)
274
+
275
+ _vis_experts: dict[int, dict[str, Tensor]] | None = None
276
+
277
+ def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]:
278
+ # router params have no .weight suffix in the checkpoint, but gguf tools expect one
279
+ if name.endswith((".gate_weight", ".router_bias")):
280
+ name += ".weight"
281
+
282
+ # audio fc1 fuses gate and up for swiglu; split it
283
+ if ".speech_encoder.layers." in name and ".fc1." in name:
284
+ gate, up = data_torch.chunk(2, dim=0)
285
+ yield from super().modify_tensors(gate, name.replace(".fc1.", ".fc1_gate."), bid)
286
+ yield from super().modify_tensors(up, name.replace(".fc1.", ".fc1_up."), bid)
287
+ return
288
+
289
+ # vision MoE: stack per-expert weights into a single 3D tensor per block
290
+ if ".mlp.experts." in name:
291
+ assert bid is not None
292
+ n_expert = self.pyramid[bid]
293
+ if self._vis_experts is None:
294
+ self._vis_experts = {}
295
+ buf = self._vis_experts.setdefault(bid, {})
296
+ buf[name] = data_torch
297
+
298
+ if len(buf) >= n_expert * 3:
299
+ for w_name in ("fc1", "fc2", "fc3"):
300
+ datas: list[Tensor] = []
301
+ for xid in range(n_expert):
302
+ ename = f"vision_encoder.blocks.{bid}.mlp.experts.{xid}.{w_name}.weight"
303
+ datas.append(buf.pop(ename))
304
+ merged = torch.stack(datas, dim=0)
305
+ yield from super().modify_tensors(merged, f"vision_encoder.blocks.{bid}.mlp.experts.{w_name}.weight", bid)
306
+ return
307
+
308
+ yield from super().modify_tensors(data_torch, name, bid)
309
+
310
+ def prepare_tensors(self):
311
+ super().prepare_tensors()
312
+ if self._vis_experts is not None:
313
+ leftover = [k for d in self._vis_experts.values() for k in d.keys()]
314
+ if leftover:
315
+ raise ValueError(f"unprocessed vision experts: {leftover}")
316
+
317
+ def tensor_force_quant(self, name, new_name, bid, n_dims):
318
+ # FP32 routing is load-bearing for the vision MoE (near-tied expert scores)
319
+ if ".ffn_gate_inp." in new_name or ".exp_probs_b." in new_name:
320
+ return gguf.GGMLQuantizationType.F32
321
+ if ".conv2d" in new_name or "a.conv_out" in new_name:
322
+ return gguf.GGMLQuantizationType.F32
323
+ return super().tensor_force_quant(name, new_name, bid, n_dims)
conversion/dotsocr.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import Callable, Iterable, TYPE_CHECKING
4
+
5
+ if TYPE_CHECKING:
6
+ from torch import Tensor
7
+
8
+ from .base import MmprojModel, ModelBase, gguf
9
+
10
+
11
+ @ModelBase.register("DotsOCRForCausalLM")
12
+ @ModelBase.example("rednote-hilab/dots.ocr")
13
+ class DotsOCRVisionModel(MmprojModel):
14
+ def __init__(self, *args, **kwargs):
15
+ super().__init__(*args, **kwargs)
16
+ assert self.hparams_vision is not None
17
+ self.hparams_vision["image_size"] = 0 # dynamic resolution
18
+
19
+ def set_gguf_parameters(self):
20
+ super().set_gguf_parameters()
21
+ self.gguf_writer.add_clip_projector_type(gguf.VisionProjectorType.DOTSOCR)
22
+ self.gguf_writer.add_vision_min_pixels(self.preprocessor_config["min_pixels"])
23
+ self.gguf_writer.add_vision_max_pixels(self.preprocessor_config["max_pixels"])
24
+ self.gguf_writer.add_vision_attention_layernorm_eps(self.find_vparam(["rms_norm_eps"]))
25
+ self.gguf_writer.add_vision_projector_scale_factor(self.find_vparam(["spatial_merge_size"]))
26
+ self.gguf_writer.add_vision_use_silu(True)
27
+
28
+ @classmethod
29
+ def filter_tensors(cls, item: tuple[str, Callable[[], Tensor]]) -> tuple[str, Callable[[], Tensor]] | None:
30
+ name, gen = item
31
+
32
+ if not name.startswith("vision_tower."):
33
+ return None
34
+
35
+ if "vision_tower.blocks." in name and ".mlp." in name:
36
+ # note: to avoid naming conflicts in tensor_mapping.py, we need to handle FFN renaming here
37
+ # x = F.silu(self.fc1(x)) * self.fc3(x)
38
+ # x = self.fc2(x)
39
+ # fc1 -> gate, fc2 -> down, fc3 -> up
40
+ # mapping original names to Qwen2.5 naming scheme
41
+ name = name.replace("vision_tower.blocks.", "visual.blocks.")
42
+ name = name.replace(".fc1", ".gate_proj")
43
+ name = name.replace(".fc2", ".down_proj")
44
+ name = name.replace(".fc3", ".up_proj")
45
+
46
+ return super().filter_tensors((name, gen))
47
+
48
+ def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]:
49
+ yield from super().modify_tensors(data_torch, name, bid)
conversion/dream.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import Iterable, TYPE_CHECKING
4
+
5
+ if TYPE_CHECKING:
6
+ from torch import Tensor
7
+
8
+ from .base import ModelBase, TextModel, gguf
9
+
10
+
11
+ @ModelBase.register("DreamModel")
12
+ @ModelBase.example("Dream-org/Dream-v0-Instruct-7B")
13
+ class DreamModel(TextModel):
14
+ model_arch = gguf.MODEL_ARCH.DREAM
15
+
16
+ def get_vocab_base(self) -> tuple[list[str], list[int], str]:
17
+ tokens: list[str] = []
18
+ toktypes: list[int] = []
19
+
20
+ from transformers import AutoTokenizer
21
+ tokenizer = AutoTokenizer.from_pretrained(self.dir_model, trust_remote_code=True)
22
+
23
+ vocab_dict = tokenizer.get_vocab() # ty: ignore[unresolved-attribute]
24
+ vocab_size = self.hparams.get("vocab_size", len(vocab_dict))
25
+ assert max(vocab_dict.values()) < vocab_size
26
+
27
+ tokpre = self.get_vocab_base_pre(tokenizer)
28
+
29
+ reverse_vocab = {id_: encoded_tok for encoded_tok, id_ in vocab_dict.items()}
30
+ added_vocab = tokenizer.get_added_vocab() # ty: ignore[unresolved-attribute]
31
+
32
+ for i in range(vocab_size):
33
+ if i not in reverse_vocab:
34
+ tokens.append(f"[PAD{i}]")
35
+ toktypes.append(gguf.TokenType.UNUSED)
36
+ elif reverse_vocab[i] in added_vocab:
37
+ tokens.append(reverse_vocab[i])
38
+ # Check if it's a special token - treat special tokens as CONTROL tokens
39
+ if hasattr(tokenizer, 'added_tokens_decoder') and i in tokenizer.added_tokens_decoder:
40
+ if tokenizer.added_tokens_decoder[i].special:
41
+ toktypes.append(gguf.TokenType.CONTROL)
42
+ else:
43
+ toktypes.append(gguf.TokenType.USER_DEFINED)
44
+ else:
45
+ # Fallback: treat all added vocab as control tokens for special tokens like <|im_start|>
46
+ toktypes.append(gguf.TokenType.CONTROL)
47
+ else:
48
+ tokens.append(reverse_vocab[i])
49
+ toktypes.append(gguf.TokenType.NORMAL)
50
+
51
+ return tokens, toktypes, tokpre
52
+
53
+ def set_vocab(self):
54
+ try:
55
+ self._set_vocab_sentencepiece()
56
+ except FileNotFoundError:
57
+ self._set_vocab_gpt2()
58
+
59
+ def set_gguf_parameters(self):
60
+ super().set_gguf_parameters()
61
+ self._try_set_pooling_type()
62
+
63
+ # Dream models use non-causal attention for diffusion
64
+ self.gguf_writer.add_causal_attention(False)
65
+
66
+ # Add Dream-specific parameters
67
+ mask_token_id = self.hparams.get("mask_token_id")
68
+ if mask_token_id is not None:
69
+ self.gguf_writer.add_mask_token_id(mask_token_id)
70
+
71
+ def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]:
72
+ # Dream model tensors should be mapped directly since it's the base model
73
+ yield from super().modify_tensors(data_torch, name, bid)
conversion/ernie.py ADDED
@@ -0,0 +1,204 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import math
5
+ import re
6
+
7
+ from typing import Callable, Iterable, TYPE_CHECKING
8
+
9
+ import torch
10
+
11
+ if TYPE_CHECKING:
12
+ from torch import Tensor
13
+
14
+ from .base import MmprojModel, ModelBase, TextModel, gguf
15
+
16
+
17
+ @ModelBase.register("Ernie4_5_ForCausalLM", "Ernie4_5ForCausalLM")
18
+ @ModelBase.example("baidu/ERNIE-4.5-0.3B-PT")
19
+ class Ernie4_5Model(TextModel):
20
+ model_arch = gguf.MODEL_ARCH.ERNIE4_5
21
+
22
+ def set_vocab(self):
23
+ self._set_vocab_sentencepiece()
24
+
25
+ tokenizer_config_file = self.dir_model / 'tokenizer_config.json'
26
+ if tokenizer_config_file.is_file():
27
+ with open(tokenizer_config_file, "r", encoding="utf-8") as f:
28
+ tokenizer_config_json = json.load(f)
29
+ if "add_prefix_space" in tokenizer_config_json:
30
+ self.gguf_writer.add_add_space_prefix(tokenizer_config_json["add_prefix_space"])
31
+
32
+ def set_gguf_parameters(self):
33
+ super().set_gguf_parameters()
34
+
35
+ @classmethod
36
+ def filter_tensors(cls, item: tuple[str, Callable[[], Tensor]]) -> tuple[str, Callable[[], Tensor]] | None:
37
+ name, gen = item
38
+
39
+ if "ernie." in name:
40
+ name = name.replace("ernie.", "model.")
41
+
42
+ return super().filter_tensors((name, gen))
43
+
44
+ def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]:
45
+ num_heads = self.hparams["num_attention_heads"]
46
+ num_kv_heads = self.hparams["num_key_value_heads"]
47
+ if (head_dim := self.hparams.get("head_dim")) is None:
48
+ head_dim = self.hparams["hidden_size"] // num_heads
49
+
50
+ # split the qkv weights
51
+ # qkv_proj shape: [(num_heads + 2 * num_kv_heads) * head_dim, hidden_size]
52
+ if "qkv_proj" in name:
53
+ name_q = name.replace("qkv_proj.weight", "q_proj.weight")
54
+ name_k = name.replace("qkv_proj.weight", "k_proj.weight")
55
+ name_v = name.replace("qkv_proj.weight", "v_proj.weight")
56
+ total_q_dim = num_heads * head_dim
57
+ total_k_dim = num_kv_heads * head_dim
58
+ total_v_dim = num_kv_heads * head_dim
59
+ q_proj_weight, k_proj_weight, v_proj_weight = data_torch.split([total_q_dim, total_k_dim, total_v_dim], dim=0)
60
+ yield from super().modify_tensors(q_proj_weight, name_q, bid)
61
+ yield from super().modify_tensors(k_proj_weight, name_k, bid)
62
+ yield from super().modify_tensors(v_proj_weight, name_v, bid)
63
+ # split the up_gate_proj into gate and up
64
+ # up_gate_proj shape: [2 * intermediate_size, hidden_size]
65
+ elif "up_gate_proj" in name:
66
+ name_up = name.replace("up_gate_proj.weight", "up_proj.weight")
67
+ name_gate = name.replace("up_gate_proj.weight", "gate_proj.weight")
68
+ dim_half = data_torch.shape[0] // 2
69
+ gate_proj_weight, up_proj_weight = data_torch.split(dim_half, dim=0)
70
+ yield from super().modify_tensors(gate_proj_weight, name_gate, bid)
71
+ yield from super().modify_tensors(up_proj_weight, name_up, bid)
72
+ else:
73
+ yield from super().modify_tensors(data_torch, name, bid)
74
+
75
+
76
+ @ModelBase.register("Ernie4_5_MoeForCausalLM")
77
+ @ModelBase.example("baidu/ERNIE-4.5-21B-A3B-PT")
78
+ class Ernie4_5MoeModel(Ernie4_5Model):
79
+ model_arch = gguf.MODEL_ARCH.ERNIE4_5_MOE
80
+ _experts: list[dict[str, Tensor]] | None = None
81
+
82
+ def __init__(self, *args, **kwargs):
83
+ super().__init__(*args, **kwargs)
84
+ self._experts = [{} for _ in range(self.block_count)]
85
+
86
+ def set_gguf_parameters(self):
87
+ super().set_gguf_parameters()
88
+ self.gguf_writer.add_expert_count(self.hparams["moe_num_experts"])
89
+ self.gguf_writer.add_expert_used_count(self.hparams["moe_k"])
90
+ self.gguf_writer.add_interleave_moe_layer_step(self.hparams["moe_layer_interval"])
91
+ self.gguf_writer.add_leading_dense_block_count(self.hparams["moe_layer_start_index"])
92
+ if (moe_intermediate_size := self.hparams.get("moe_intermediate_size")) is not None:
93
+ self.gguf_writer.add_expert_feed_forward_length(moe_intermediate_size)
94
+ if (shared_expert_count := self.hparams.get('moe_num_shared_experts')) is not None:
95
+ self.gguf_writer.add_expert_shared_count(shared_expert_count)
96
+ if shared_expert_count > 0 and (shared_expert_intermediate_size := self.hparams.get('intermediate_size')) is not None and (num_key_value_heads := self.hparams.get('num_key_value_heads')) is not None:
97
+ self.gguf_writer.add_expert_shared_feed_forward_length(shared_expert_intermediate_size // num_key_value_heads)
98
+
99
+ @classmethod
100
+ def filter_tensors(cls, item: tuple[str, Callable[[], Tensor]]) -> tuple[str, Callable[[], Tensor]] | None:
101
+ name, gen = item
102
+
103
+ # skip Multi-Token Prediction (MTP) layers (again, same as DeepseekV2)
104
+ match = re.match(r"model.mtp_block.(\d+)", name)
105
+ if match:
106
+ return None
107
+
108
+ # skip all other MTP tensors for now
109
+ match = re.match(r"model.mtp_emb_norm.(\d+)", name)
110
+ if match:
111
+ return None
112
+
113
+ match = re.match(r"model.mtp_hidden_norm.(\d+)", name)
114
+ if match:
115
+ return None
116
+
117
+ match = re.match(r"model.mtp_linear_proj.(\d+)", name)
118
+ if match:
119
+ return None
120
+
121
+ return super().filter_tensors(item)
122
+
123
+ def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]:
124
+ # process the experts separately
125
+ if name.find("mlp.experts") != -1:
126
+ n_experts = self.hparams["moe_num_experts"]
127
+ assert bid is not None
128
+
129
+ if self._experts is None:
130
+ self._experts = [{} for _ in range(self.block_count)]
131
+
132
+ self._experts[bid][name] = data_torch
133
+
134
+ if len(self._experts[bid]) >= n_experts * 3:
135
+ # merge the experts into a single 3d tensor
136
+ for w_name in ["gate_proj", "up_proj", "down_proj"]:
137
+ datas: list[Tensor] = []
138
+
139
+ for xid in range(n_experts):
140
+ ename_to_retrieve = f"model.layers.{bid}.mlp.experts.{xid}.{w_name}.weight"
141
+ datas.append(self._experts[bid][ename_to_retrieve])
142
+ del self._experts[bid][ename_to_retrieve]
143
+
144
+ data_torch = torch.stack(datas, dim=0)
145
+ merged_name = f"model.layers.{bid}.mlp.experts.{w_name}.weight"
146
+ yield from super().modify_tensors(data_torch, merged_name, bid)
147
+ else:
148
+ yield from ModelBase.modify_tensors(self, data_torch, name, bid)
149
+
150
+ def prepare_tensors(self):
151
+ super().prepare_tensors()
152
+
153
+ if self._experts is not None:
154
+ # flatten `list[dict[str, Tensor]]` into `list[str]`
155
+ experts = [k for d in self._experts for k in d.keys()]
156
+ if len(experts) > 0:
157
+ raise ValueError(f"Unprocessed experts: {experts}")
158
+
159
+
160
+ @ModelBase.register("PaddleOCRVLForConditionalGeneration")
161
+ @ModelBase.example("PaddlePaddle/PaddleOCR-VL")
162
+ class PaddleOCRModel(Ernie4_5Model):
163
+ model_arch = gguf.MODEL_ARCH.PADDLEOCR
164
+
165
+
166
+ @ModelBase.register("PaddleOCRVisionModel")
167
+ @ModelBase.example("PaddlePaddle/PaddleOCR-VL")
168
+ class PaddleOCRVisionModel(MmprojModel):
169
+ # PaddleOCR-VL uses a modified version of Siglip
170
+ min_pixels: int = 0
171
+ max_pixels: int = 0
172
+
173
+ def __init__(self, *args, **kwargs):
174
+ super().__init__(*args, **kwargs)
175
+ assert self.hparams_vision is not None
176
+ self.min_pixels = self.preprocessor_config["min_pixels"]
177
+ self.max_pixels = self.preprocessor_config["max_pixels"]
178
+ self.hparams_vision["image_size"] = int(math.sqrt(self.max_pixels))
179
+
180
+ def set_gguf_parameters(self):
181
+ super().set_gguf_parameters()
182
+ assert self.hparams_vision is not None
183
+ hparams = self.hparams_vision
184
+ self.gguf_writer.add_clip_projector_type(gguf.VisionProjectorType.PADDLEOCR)
185
+ self.gguf_writer.add_vision_max_pixels(self.max_pixels)
186
+ self.gguf_writer.add_vision_min_pixels(self.min_pixels)
187
+ self.gguf_writer.add_vision_use_gelu(True)
188
+ self.gguf_writer.add_vision_attention_layernorm_eps(hparams.get("rms_norm_eps", 1e-6))
189
+
190
+ @classmethod
191
+ def filter_tensors(cls, item: tuple[str, Callable[[], Tensor]]) -> tuple[str, Callable[[], Tensor]] | None:
192
+ name, gen = item
193
+
194
+ if "vision_model" not in name and "mlp_AR" not in name:
195
+ return None
196
+ name = name.replace("visual.", "model.")
197
+ if "packing_position_embedding" in name:
198
+ # unused
199
+ return None
200
+ if "vision_model.head" in name:
201
+ # we don't yet support image embeddings for this model
202
+ return None
203
+
204
+ return super().filter_tensors((name, gen))
conversion/exaone.py ADDED
@@ -0,0 +1,312 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import math
4
+
5
+ from pathlib import Path
6
+ from typing import Callable, Iterable, TYPE_CHECKING
7
+
8
+ import torch
9
+
10
+ if TYPE_CHECKING:
11
+ from torch import Tensor
12
+
13
+ from .base import MmprojModel, ModelBase, TextModel, gguf
14
+ from .qwenvl import Qwen2VLVisionModel
15
+
16
+
17
+ @ModelBase.register("ExaoneForCausalLM")
18
+ @ModelBase.example("LGAI-EXAONE/EXAONE-3.5-2.4B-Instruct")
19
+ class ExaoneModel(TextModel):
20
+ model_arch = gguf.MODEL_ARCH.EXAONE
21
+
22
+ def set_gguf_parameters(self):
23
+ super().set_gguf_parameters()
24
+ hparams = self.hparams
25
+
26
+ assert (hparams["activation_function"] == "silu")
27
+
28
+ rotary_factor = self.rope_parameters.get("partial_rotary_factor")
29
+ rotary_factor = rotary_factor if rotary_factor is not None else 1.0
30
+ self.gguf_writer.add_rope_dimension_count(int(rotary_factor * (hparams["hidden_size"] // hparams["num_attention_heads"])))
31
+
32
+ def generate_extra_tensors(self) -> Iterable[tuple[str, Tensor]]:
33
+ if rope_params := self.rope_parameters.get("full_attention", self.rope_parameters):
34
+ if rope_params.get("rope_type", '').lower() == "llama3":
35
+ base = self.rope_parameters.get("rope_theta", 10000.0)
36
+ if (dim := self.hparams.get("head_dim")) is None:
37
+ dim = self.hparams["hidden_size"] // self.hparams["num_attention_heads"]
38
+ freqs = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.float32) / dim))
39
+
40
+ factor = rope_params.get("factor", 8.0)
41
+ low_freq_factor = rope_params.get("low_freq_factor", 1.0)
42
+ high_freq_factor = rope_params.get("high_freq_factor", 4.0)
43
+ old_context_len = rope_params.get("original_max_position_embeddings", 8192)
44
+
45
+ low_freq_wavelen = old_context_len / low_freq_factor
46
+ high_freq_wavelen = old_context_len / high_freq_factor
47
+ assert low_freq_wavelen != high_freq_wavelen
48
+
49
+ rope_factors = []
50
+ for freq in freqs:
51
+ wavelen = 2 * math.pi / freq
52
+ if wavelen < high_freq_wavelen:
53
+ rope_factors.append(1)
54
+ elif wavelen > low_freq_wavelen:
55
+ rope_factors.append(factor)
56
+ else:
57
+ smooth = (old_context_len / wavelen - low_freq_factor) / (high_freq_factor - low_freq_factor)
58
+ rope_factors.append(1 / ((1 - smooth) / factor + smooth))
59
+
60
+ yield (self.format_tensor_name(gguf.MODEL_TENSOR.ROPE_FREQS), torch.tensor(rope_factors, dtype=torch.float32))
61
+
62
+
63
+ @ModelBase.register("Exaone4ForCausalLM")
64
+ @ModelBase.example("LGAI-EXAONE/EXAONE-4.0-32B")
65
+ class Exaone4Model(TextModel):
66
+ model_arch = gguf.MODEL_ARCH.EXAONE4
67
+
68
+ def set_vocab(self):
69
+ tokens, toktypes, tokpre = self.get_vocab_base()
70
+ self.gguf_writer.add_tokenizer_model("gpt2")
71
+ self.gguf_writer.add_tokenizer_pre(tokpre)
72
+ self.gguf_writer.add_token_list(tokens)
73
+ self.gguf_writer.add_token_types(toktypes)
74
+
75
+ special_vocab = gguf.SpecialVocab(self.dir_model, load_merges=True)
76
+ special_vocab.add_to_gguf(self.gguf_writer)
77
+
78
+ def set_gguf_parameters(self):
79
+ super().set_gguf_parameters()
80
+ hparams = self.hparams
81
+ self.gguf_writer.add_vocab_size(hparams["vocab_size"])
82
+
83
+ if hparams.get("sliding_window") is not None:
84
+ self.gguf_writer.add_sliding_window(hparams["sliding_window"])
85
+ if "layer_types" in hparams:
86
+ self.gguf_writer.add_sliding_window_pattern([t == "sliding_attention" for t in hparams["layer_types"]])
87
+ elif "sliding_window_pattern" in hparams:
88
+ sliding_window_pattern = []
89
+ if isinstance(hparams["sliding_window_pattern"], str): # e.g. LLLG
90
+ for i in range(hparams["num_hidden_layers"]):
91
+ sliding_window_pattern.append(hparams["sliding_window_pattern"][i % len(hparams["sliding_window_pattern"])] == "L")
92
+ if isinstance(hparams["sliding_window_pattern"], int): # e.g. 4
93
+ for i in range(hparams["num_hidden_layers"]):
94
+ sliding_window_pattern.append((i + 1) % hparams["sliding_window_pattern"] != 0)
95
+ if len(sliding_window_pattern) == hparams["num_hidden_layers"]:
96
+ self.gguf_writer.add_sliding_window_pattern(sliding_window_pattern)
97
+
98
+ def generate_extra_tensors(self) -> Iterable[tuple[str, Tensor]]:
99
+ if rope_params := self.rope_parameters.get("full_attention", self.rope_parameters):
100
+ if rope_params.get("rope_type", '').lower() == "llama3":
101
+ base = rope_params.get("rope_theta", 10_000.0)
102
+ if (dim := self.hparams.get("head_dim")) is None:
103
+ dim = self.hparams["hidden_size"] // self.hparams["num_attention_heads"]
104
+ freqs = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.float32) / dim))
105
+
106
+ factor = rope_params.get("factor", 16.0)
107
+ low_freq_factor = rope_params.get("low_freq_factor", 1.0)
108
+ high_freq_factor = rope_params.get("high_freq_factor", 4.0)
109
+ old_context_len = rope_params.get("original_max_position_embeddings", 8192)
110
+
111
+ low_freq_wavelen = old_context_len / low_freq_factor
112
+ high_freq_wavelen = old_context_len / high_freq_factor
113
+
114
+ rope_factors = []
115
+ for freq in freqs:
116
+ wavelen = 2 * math.pi / freq
117
+ if wavelen < high_freq_wavelen:
118
+ rope_factors.append(1)
119
+ elif wavelen > low_freq_wavelen:
120
+ rope_factors.append(factor)
121
+ else:
122
+ smooth = (old_context_len / wavelen - low_freq_factor) / (high_freq_factor - low_freq_factor)
123
+ rope_factors.append(1 / ((1 - smooth) / factor + smooth))
124
+
125
+ yield (self.format_tensor_name(gguf.MODEL_TENSOR.ROPE_FREQS), torch.tensor(rope_factors, dtype=torch.float32))
126
+
127
+
128
+ # note: transformers >= 5.1 renamed the class to "ExaoneMoeForCausalLM" (lowercase 'e'),
129
+ # so accept both spellings - LG AI have updated the configs of already-released models
130
+ @ModelBase.register("ExaoneMoEForCausalLM", "ExaoneMoeForCausalLM")
131
+ @ModelBase.example("LGAI-EXAONE/K-EXAONE-236B-A23B")
132
+ class ExaoneMoEModel(Exaone4Model):
133
+ model_arch = gguf.MODEL_ARCH.EXAONE_MOE
134
+
135
+ def __init__(self, *args, **kwargs):
136
+ super().__init__(*args, **kwargs)
137
+ self.block_count = self.hparams["num_hidden_layers"] + self.hparams.get("num_nextn_predict_layers", 0)
138
+ self.tensor_map = gguf.get_tensor_name_map(self.model_arch, self.block_count)
139
+
140
+ def set_gguf_parameters(self):
141
+ super().set_gguf_parameters()
142
+ moe_intermediate_size = self.hparams["moe_intermediate_size"]
143
+ num_shared_experts = self.hparams["num_shared_experts"]
144
+ self.gguf_writer.add_expert_feed_forward_length(moe_intermediate_size)
145
+ self.gguf_writer.add_expert_shared_count(num_shared_experts)
146
+ self.gguf_writer.add_expert_shared_feed_forward_length(moe_intermediate_size * num_shared_experts)
147
+ self.gguf_writer.add_expert_weights_scale(self.hparams["routed_scaling_factor"])
148
+ self.gguf_writer.add_expert_weights_norm(self.hparams["norm_topk_prob"])
149
+ n_dense_layer = self.hparams.get("first_k_dense_replace", self.hparams.get("first_last_k_dense_replace", 0))
150
+ self.gguf_writer.add_leading_dense_block_count(n_dense_layer)
151
+ self.gguf_writer.add_nextn_predict_layers(self.hparams.get("num_nextn_predict_layers", 0))
152
+
153
+ self.gguf_writer.add_rope_scaling_type(gguf.RopeScalingType.NONE)
154
+
155
+ _experts: list[dict[str, Tensor]] | None = None
156
+
157
+ def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]:
158
+ if name.startswith("mtp."):
159
+ if name.find("layers.") != -1:
160
+ # `mtp.layers.0.[module_name]` format
161
+ name = name.replace(f"mtp.layers.{bid}", f"model.layers.{bid + self.hparams['num_hidden_layers']}")
162
+ else:
163
+ # mtp fc/norm weights
164
+ remapper = {
165
+ "mtp.fc": "model.layers.{bid}.eh_proj",
166
+ "mtp.pre_fc_norm_embedding": "model.layers.{bid}.enorm",
167
+ "mtp.pre_fc_norm_hidden": "model.layers.{bid}.hnorm",
168
+ "mtp.norm": "model.layers.{bid}.shared_head.norm",
169
+ }
170
+ _n = Path(name)
171
+ new_name = remapper[_n.stem] + _n.suffix
172
+
173
+ # set shared weights for all NextN/MTP layers
174
+ for bid in range(self.hparams['num_hidden_layers'], self.block_count):
175
+ yield from super().modify_tensors(data_torch, new_name.format(bid=bid), bid)
176
+ return
177
+
178
+ if name.find("mlp.experts") != -1:
179
+ n_experts = self.find_hparam(["num_local_experts", "num_experts"])
180
+ assert bid is not None
181
+
182
+ if self._experts is None:
183
+ self._experts = [{} for _ in range(self.block_count)]
184
+
185
+ self._experts[bid][name] = data_torch
186
+
187
+ if len(self._experts[bid]) >= n_experts * 3:
188
+ # merge the experts into a single 3d tensor
189
+ for w_name in ["down_proj", "gate_proj", "up_proj"]:
190
+ datas: list[Tensor] = []
191
+
192
+ for xid in range(n_experts):
193
+ ename = f"model.layers.{bid}.mlp.experts.{xid}.{w_name}.weight"
194
+ datas.append(self._experts[bid][ename])
195
+ del self._experts[bid][ename]
196
+
197
+ data_torch = torch.stack(datas, dim=0)
198
+
199
+ merged_name = f"model.layers.{bid}.mlp.experts.{w_name}.weight"
200
+
201
+ new_name = self.map_tensor_name(merged_name)
202
+
203
+ yield from super().modify_tensors(data_torch, new_name, bid)
204
+ return
205
+ else:
206
+ return
207
+
208
+ yield from super().modify_tensors(data_torch, name, bid)
209
+
210
+ def prepare_tensors(self):
211
+ super().prepare_tensors()
212
+ if self._experts is not None:
213
+ # flatten `list[dict[str, Tensor]]` into `list[str]`
214
+ experts = [k for d in self._experts for k in d.keys()]
215
+ if len(experts) > 0:
216
+ raise ValueError(f"Unprocessed experts: {experts}")
217
+
218
+
219
+ @ModelBase.register("Exaone4_5_ForConditionalGeneration")
220
+ @ModelBase.example("LGAI-EXAONE/EXAONE-4.5-33B")
221
+ class Exaone4_5_TextModel(Exaone4Model):
222
+ """Text tower of EXAONE 4.5; Tensors match EXAONE4"""
223
+
224
+ model_arch = gguf.MODEL_ARCH.EXAONE4
225
+
226
+ def __init__(self, *args, **kwargs):
227
+ super().__init__(*args, **kwargs)
228
+ n_nextn = int(self.hparams.get("num_nextn_predict_layers", 0) or 0)
229
+ if n_nextn > 0:
230
+ self.block_count = self.hparams["num_hidden_layers"] + n_nextn
231
+ self.tensor_map = gguf.get_tensor_name_map(self.model_arch, self.block_count)
232
+
233
+ def set_gguf_parameters(self):
234
+ super().set_gguf_parameters()
235
+ n_nextn = int(self.hparams.get("num_nextn_predict_layers", 0) or 0)
236
+ if n_nextn > 0:
237
+ self.gguf_writer.add_nextn_predict_layers(n_nextn)
238
+
239
+ def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]:
240
+ if name.startswith("mtp."):
241
+ n_nextn = int(self.hparams.get("num_nextn_predict_layers", 0) or 0)
242
+ if n_nextn <= 0:
243
+ return
244
+ nh = self.hparams["num_hidden_layers"]
245
+ if ".layers." in name:
246
+ share = self.hparams.get("mtp_share_layers", False)
247
+ mtp_bid = bid if bid is not None else 0
248
+ if share:
249
+ for k in range(n_nextn):
250
+ nn = name.replace(f"mtp.layers.{mtp_bid}", f"model.layers.{nh + k}")
251
+ yield from super().modify_tensors(data_torch, nn, nh + k)
252
+ return
253
+ name = name.replace(f"mtp.layers.{mtp_bid}", f"model.layers.{mtp_bid + nh}")
254
+ else:
255
+ remapper = {
256
+ "mtp.fc": gguf.MODEL_TENSOR.NEXTN_EH_PROJ,
257
+ "mtp.pre_fc_norm_embedding": gguf.MODEL_TENSOR.NEXTN_ENORM,
258
+ "mtp.pre_fc_norm_hidden": gguf.MODEL_TENSOR.NEXTN_HNORM,
259
+ "mtp.norm": gguf.MODEL_TENSOR.NEXTN_SHARED_HEAD_NORM,
260
+ }
261
+ _n = Path(name)
262
+ key = _n.stem
263
+ if key not in remapper:
264
+ return
265
+ for bid_mtp in range(nh, self.block_count):
266
+ mapped_name = self.format_tensor_name(remapper[key], bid_mtp, suffix=_n.suffix)
267
+ yield from ModelBase.modify_tensors(self, data_torch, mapped_name, bid_mtp)
268
+ return
269
+
270
+ yield from super().modify_tensors(data_torch, name, bid)
271
+
272
+
273
+ @ModelBase.register("Exaone4_5_ForConditionalGeneration")
274
+ @ModelBase.example("LGAI-EXAONE/EXAONE-4.5-33B")
275
+ class Exaone4_5VisionModel(Qwen2VLVisionModel):
276
+ """Vision tower for EXAONE 4.5; Qwen2-VL-style ViT (GQA) + patch merger"""
277
+
278
+ @classmethod
279
+ def filter_tensors(cls, item: tuple[str, Callable[[], Tensor]]) -> tuple[str, Callable[[], Tensor]] | None:
280
+ name, gen = item
281
+ name = name.replace("model.visual.", "visual.", 1)
282
+ return super().filter_tensors((name, gen))
283
+
284
+ def set_gguf_parameters(self):
285
+ MmprojModel.set_gguf_parameters(self)
286
+ assert self.hparams_vision is not None
287
+ hparams = self.hparams_vision
288
+ self.gguf_writer.add_clip_projector_type(gguf.VisionProjectorType.EXAONE4_5)
289
+ self.gguf_writer.add_vision_use_silu(True)
290
+ self.gguf_writer.add_vision_min_pixels(self.preprocessor_config["min_pixels"])
291
+ self.gguf_writer.add_vision_max_pixels(self.preprocessor_config["max_pixels"])
292
+ num_kv_head = self.find_vparam(["num_key_value_heads"], optional=True)
293
+ if num_kv_head is not None:
294
+ self.gguf_writer.add_vision_head_count_kv(num_kv_head)
295
+ eps = hparams.get("rms_norm_eps", self.global_config.get("rms_norm_eps", 1e-6))
296
+ self.gguf_writer.add_vision_attention_layernorm_eps(eps)
297
+ if (window_size := hparams.get("window_size")) is not None:
298
+ self.gguf_writer.add_vision_window_size(window_size)
299
+ fullatt_block_indexes = hparams.get("fullatt_block_indexes")
300
+ if fullatt_block_indexes:
301
+ n_wa_pattern = fullatt_block_indexes[0] + 1
302
+ for i in range(1, len(fullatt_block_indexes)):
303
+ if fullatt_block_indexes[i] - fullatt_block_indexes[i - 1] != n_wa_pattern:
304
+ raise ValueError(f"Invalid EXAONE4.5 fullatt_block_indexes: {fullatt_block_indexes}")
305
+ self.gguf_writer.add_vision_n_wa_pattern(n_wa_pattern)
306
+
307
+ def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]:
308
+ if ".qkv." in name:
309
+ yield from ModelBase.modify_tensors(self, data_torch, name, bid)
310
+ return
311
+
312
+ yield from Qwen2VLVisionModel.modify_tensors(self, data_torch, name, bid)
conversion/falcon.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import Iterable, TYPE_CHECKING
4
+
5
+ import torch
6
+
7
+ if TYPE_CHECKING:
8
+ from torch import Tensor
9
+
10
+ from .base import ModelBase, TextModel, gguf
11
+
12
+
13
+ @ModelBase.register("FalconForCausalLM", "RWForCausalLM")
14
+ @ModelBase.example("tiiuae/falcon-7b")
15
+ class FalconModel(TextModel):
16
+ model_arch = gguf.MODEL_ARCH.FALCON
17
+
18
+ def set_gguf_parameters(self):
19
+ n_head = self.hparams.get("num_attention_heads")
20
+ if n_head is None:
21
+ n_head = self.hparams["n_head"] # old name
22
+
23
+ n_head_kv = self.hparams.get("num_kv_heads")
24
+ if n_head_kv is None:
25
+ n_head_kv = self.hparams.get("n_head_kv", 1) # old name
26
+
27
+ self.gguf_writer.add_context_length(2048) # not in config.json
28
+ self.gguf_writer.add_tensor_data_layout("jploski") # qkv tensor transform
29
+ self.gguf_writer.add_embedding_length(self.hparams["hidden_size"])
30
+ self.gguf_writer.add_feed_forward_length(4 * self.hparams["hidden_size"])
31
+ self.gguf_writer.add_block_count(self.block_count)
32
+ self.gguf_writer.add_head_count(n_head)
33
+ self.gguf_writer.add_head_count_kv(n_head_kv)
34
+ self.gguf_writer.add_layer_norm_eps(self.hparams["layer_norm_epsilon"])
35
+ self.gguf_writer.add_file_type(self.ftype)
36
+
37
+ def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]:
38
+ # QKV tensor transform
39
+ # The original query_key_value tensor contains n_head_kv "kv groups",
40
+ # each consisting of n_head/n_head_kv query weights followed by one key
41
+ # and one value weight (shared by all query heads in the kv group).
42
+ # This layout makes it a big pain to work with in GGML.
43
+ # So we rearrange them here,, so that we have n_head query weights
44
+ # followed by n_head_kv key weights followed by n_head_kv value weights,
45
+ # in contiguous fashion.
46
+ # ref: https://github.com/jploski/ggml/blob/falcon40b/examples/falcon/convert-hf-to-ggml.py
47
+
48
+ if "query_key_value" in name:
49
+ n_head = self.find_hparam(["num_attention_heads", "n_head"])
50
+ n_head_kv = self.find_hparam(["num_kv_heads", "n_head_kv"], optional=True) or 1
51
+ head_dim = self.hparams["hidden_size"] // n_head
52
+
53
+ qkv = data_torch.view(n_head_kv, n_head // n_head_kv + 2, head_dim, head_dim * n_head)
54
+ q = qkv[:, :-2].reshape(n_head * head_dim, head_dim * n_head)
55
+ k = qkv[:, [-2]].reshape(n_head_kv * head_dim, head_dim * n_head)
56
+ v = qkv[:, [-1]].reshape(n_head_kv * head_dim, head_dim * n_head)
57
+ data_torch = torch.cat((q, k, v)).reshape_as(data_torch)
58
+
59
+ yield from super().modify_tensors(data_torch, name, bid)
conversion/falcon_h1.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import Any, Iterable, TYPE_CHECKING
4
+
5
+ if TYPE_CHECKING:
6
+ from torch import Tensor
7
+
8
+ from .base import ModelBase, gguf
9
+
10
+ from .llama import LlamaModel
11
+ from .mamba import Mamba2Model
12
+
13
+
14
+ @ModelBase.register("FalconH1ForCausalLM")
15
+ @ModelBase.example("tiiuae/Falcon-H1-0.5B-Base")
16
+ class FalconH1Model(Mamba2Model):
17
+ model_arch = gguf.MODEL_ARCH.FALCON_H1
18
+
19
+ def __init__(self, *args, **kwargs):
20
+ # Set the hparam prefixes for Falcon Mamba2
21
+ self.hparam_prefixes = ["mamba"]
22
+
23
+ # Initialize the base Mamba2Model
24
+ super().__init__(*args, **kwargs)
25
+
26
+ # Use Llama conversion for attention
27
+ self._transformer_model_class = LlamaModel
28
+
29
+ # n_group and d_inner are used during reshape_tensors for mamba2
30
+ self.n_group = self.find_hparam(["n_groups"])
31
+ self.d_inner = self.find_hparam(["mamba_d_ssm"])
32
+ self.d_head = self.find_hparam(["d_head"])
33
+
34
+ # Initialize any Falcon Mamba2 specific attributes
35
+ self.has_attention = True # Falcon Mamba2 has attention components
36
+
37
+ # Load Falcon-H1 multipliers from hyperparameters
38
+ self.attention_in_multiplier = self.find_hparam(["attention_in_multiplier"], optional=True)
39
+ self.attention_out_multiplier = self.find_hparam(["attention_out_multiplier"], optional=True)
40
+ self.ssm_in_multiplier = self.find_hparam(["ssm_in_multiplier"], optional=True)
41
+ self.ssm_out_multiplier = self.find_hparam(["ssm_out_multiplier"], optional=True)
42
+ self.mlp_multipliers = self.find_hparam(["mlp_multipliers"], optional=True)
43
+ self.ssm_multipliers = self.find_hparam(["ssm_multipliers"], optional=True)
44
+ self.intermediate_size = self.find_hparam(["intermediate_size"])
45
+ self.key_multiplier = self.find_hparam(["key_multiplier"], optional=True)
46
+
47
+ def find_hparam(self, keys: Iterable[str], *args, **kwargs) -> Any:
48
+ prefixed = []
49
+ for pfx in self.hparam_prefixes:
50
+ prefixed.extend(
51
+ "_".join([pfx, k])
52
+ for k in keys
53
+ )
54
+ keys = list(keys) + prefixed
55
+ return super().find_hparam(keys, *args, **kwargs)
56
+
57
+ def set_vocab(self):
58
+ self._set_vocab_gpt2()
59
+
60
+ def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]:
61
+ tensors = list(super().modify_tensors(data_torch, name, bid))
62
+ tensor = tensors[0][1]
63
+
64
+ if "down_proj" in name:
65
+ tensor = tensor * self.mlp_multipliers[1]
66
+ elif "gate_proj" in name:
67
+ tensor = tensor * self.mlp_multipliers[0]
68
+ elif "k_proj" in name:
69
+ tensor = tensor * self.key_multiplier * self.attention_in_multiplier
70
+ elif "q_proj" in name:
71
+ tensor = tensor * self.attention_in_multiplier
72
+ elif "v_proj" in name:
73
+ tensor = tensor * self.attention_in_multiplier
74
+ elif "o_proj" in name:
75
+ tensor = tensor * self.attention_out_multiplier
76
+ elif "out_proj" in name:
77
+ tensor = tensor * self.ssm_out_multiplier
78
+ elif "in_proj" in name:
79
+ tensor = tensor * self.ssm_in_multiplier
80
+ zxbcdt_multipliers = self.hparams["ssm_multipliers"]
81
+ intermediate_size = self.hparams["mamba_d_ssm"]
82
+ groups_time_state_size = self.hparams["mamba_n_groups"] * self.hparams["mamba_d_state"]
83
+ tensor[:intermediate_size, :] *= zxbcdt_multipliers[0]
84
+ tensor[intermediate_size:2 * intermediate_size, :] *= zxbcdt_multipliers[1]
85
+ tensor[2 * intermediate_size:2 * intermediate_size + groups_time_state_size, :] *= zxbcdt_multipliers[2]
86
+ tensor[2 * intermediate_size + groups_time_state_size:2 * intermediate_size + 2 * groups_time_state_size, :] *= zxbcdt_multipliers[3]
87
+ tensor[2 * intermediate_size + 2 * groups_time_state_size:, :] *= zxbcdt_multipliers[4]
88
+ elif "lm_head" in name:
89
+ tensor = tensor * self.hparams["lm_head_multiplier"]
90
+ elif "embed_tokens" in name:
91
+ tensor = tensor * self.hparams["embedding_multiplier"]
92
+ elif "mamba.norm" in name:
93
+ tensor = tensor.reshape(self.n_group, self.d_inner // self.n_group)
94
+
95
+ tensors = [(tensors[0][0], tensor)]
96
+ return tensors
97
+
98
+ def set_gguf_parameters(self):
99
+ super().set_gguf_parameters()
100
+
101
+ ## General Params ##
102
+ self.gguf_writer.add_vocab_size(self.hparams["vocab_size"])
103
+ # Override some Mamba2 defaults
104
+ self.gguf_writer.add_block_count(self.block_count)
105
+ self.gguf_writer.add_context_length(self.hparams.get("max_position_embeddings", 0))
106
+ self.gguf_writer.add_feed_forward_length(self.hparams["intermediate_size"])
107
+
108
+ ## Attention params ##
109
+ self.gguf_writer.add_head_count(self.hparams["num_attention_heads"]) # Override value 0 from Mamba2
110
+ self.gguf_writer.add_head_count_kv(self.hparams["num_key_value_heads"])
111
+ self.gguf_writer.add_key_length(self.hparams["head_dim"])
112
+ self.gguf_writer.add_value_length(self.hparams["head_dim"])
113
+
114
+ ## Validation ##
115
+ assert self.hparams.get("hidden_act") in [None, "silu"], "Only SILU activation supported"
116
+ assert self.d_inner % self.d_head == 0, f"SSM inner size {self.d_inner} not a multiple of head dim {self.d_head}"
117
+
118
+ # Add any other Falcon Mamba2 specific configuration
119
+ self.gguf_writer.add_rope_freq_base(self.rope_parameters["rope_theta"])