jagat-primitive-org commited on
Commit
9588df1
·
verified ·
1 Parent(s): e7dd45d

Mixed NVFP4/FP8-block: 15 expert layers NVFP4, 30 FP8-block

Browse files
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ tokenizer.json filter=lfs diff=lfs merge=lfs -text
chat_template.jinja ADDED
@@ -0,0 +1,994 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {{- bos_token }}
2
+ {%- if tool_presentation is defined -%}
3
+ {{- raise_exception("Unsupported argument: tool_presentation. Use tool_presentation_format with one of: json, xml, markdown.") -}}
4
+ {%- endif -%}
5
+ {%- if tool_calling_format is defined -%}
6
+ {{- raise_exception("Unsupported argument: tool_calling_format. Use tool_call_format with one of: json, xml, xml_typed.") -}}
7
+ {%- endif -%}
8
+ {%- if tool_format is defined -%}
9
+ {{- raise_exception("Unsupported argument: tool_format. Use tool_call_format with one of: json, xml, xml_typed.") -}}
10
+ {%- endif -%}
11
+ {%- set tool_presentation_fmt = tool_presentation_format | default('markdown') -%}
12
+ {%- set tool_call_fmt = tool_call_format | default('xml') -%}
13
+ {%- if tool_presentation_fmt != 'json' and tool_presentation_fmt != 'xml' and tool_presentation_fmt != 'markdown' -%}
14
+ {{- raise_exception("Unsupported tool_presentation_format: '" ~ tool_presentation_fmt ~ "'. Supported formats: json, xml, markdown.") -}}
15
+ {%- endif -%}
16
+ {%- if tool_call_fmt != 'json' and tool_call_fmt != 'xml' and tool_call_fmt != 'xml_typed' -%}
17
+ {{- raise_exception("Unsupported tool_call_format: '" ~ tool_call_fmt ~ "'. Supported formats: json, xml, xml_typed.") -}}
18
+ {%- endif -%}
19
+
20
+ {#- Renderability state, computed during validate_tools (single walk, no extra -#}
21
+ {#- traversal at render time): ok = working flag for the tool being validated; -#}
22
+ {#- bad = pipe-delimited indices of tools that must render as verbatim JSON. -#}
23
+ {%- set RB = namespace(ok=true, bad='|') -%}
24
+
25
+ {%- macro value_contains_mapping(v) -%}
26
+ {%- if v is mapping -%}
27
+ true
28
+ {%- elif v is sequence and v is not string -%}
29
+ {%- set f = namespace(x='false') -%}
30
+ {%- for c in v -%}{%- if value_contains_mapping(c) == 'true' -%}{%- set f.x = 'true' -%}{%- endif -%}{%- endfor -%}
31
+ {{- f.x -}}
32
+ {%- else -%}
33
+ false
34
+ {%- endif -%}
35
+ {%- endmacro -%}
36
+
37
+ {#- $ref inlining state: defs = local $defs of the tool being rendered; seen = -#}
38
+ {#- pipe-delimited names already expanded for this tool (each def inlines at most -#}
39
+ {#- once; later references render by def name; cycles terminate immediately). -#}
40
+ {#- $ref-sibling annotations (description/default/...) merge OVER the def at -#}
41
+ {#- the inline site, so use-site annotations win and are never dropped. -#}
42
+ {%- set REFS = namespace(defs={}, seen='|') -%}
43
+
44
+ {%- macro render_compact_type_name(type_name, spec) -%}
45
+ {%- if type_name == "array" -%}
46
+ array[{%- if 'items' in spec -%}{{ render_compact_type(spec['items']) }}{%- else -%}any{%- endif -%}]
47
+ {%- elif type_name -%}
48
+ {{- type_name -}}
49
+ {%- else -%}
50
+ any
51
+ {%- endif -%}
52
+ {%- endmacro -%}
53
+
54
+ {%- macro render_compact_type(spec) -%}
55
+ {%- if spec is not mapping -%}
56
+ any
57
+ {%- elif spec.type is defined and spec.type is sequence and spec.type is not string and spec.type | length > 0 -%}
58
+ {%- for type_name in spec.type -%}{{ render_compact_type_name(type_name, spec) }}{%- if not loop.last -%}|{%- endif -%}{%- endfor -%}
59
+ {%- elif spec.type is defined and spec.type is sequence and spec.type is not string -%}
60
+ any
61
+ {%- elif spec.type -%}
62
+ {{- render_compact_type_name(spec.type, spec) -}}
63
+ {%- elif spec['$ref'] is string -%}
64
+ {{- spec['$ref'].split('/') | last -}}
65
+ {%- elif spec.oneOf -%}
66
+ oneOf[{%- for variant in spec.oneOf -%}{{ render_compact_type(variant) }}{%- if not loop.last -%}|{%- endif -%}{%- endfor -%}]
67
+ {%- elif spec.anyOf -%}
68
+ anyOf[{%- for variant in spec.anyOf -%}{{ render_compact_type(variant) }}{%- if not loop.last -%}|{%- endif -%}{%- endfor -%}]
69
+ {%- elif spec.properties -%}
70
+ object
71
+ {%- elif 'items' in spec -%}
72
+ array[{{ render_compact_type(spec['items']) }}]
73
+ {%- else -%}
74
+ any
75
+ {%- endif -%}
76
+ {%- endmacro -%}
77
+
78
+ {%- macro render_markdown_type_name(type_name, spec) -%}
79
+ {%- if type_name == "array" -%}
80
+ array of {% if 'items' in spec %}{{ render_markdown_type(spec['items']) }}{% else %}any{% endif %}
81
+ {%- elif type_name -%}
82
+ {{- type_name -}}
83
+ {%- else -%}
84
+ any
85
+ {%- endif -%}
86
+ {%- endmacro -%}
87
+
88
+ {%- macro render_markdown_type(spec) -%}
89
+ {%- if spec is sameas true -%}
90
+ True
91
+ {%- elif spec is sameas false -%}
92
+ False
93
+ {%- elif spec is not mapping -%}
94
+ any
95
+ {%- elif spec.type is defined and spec.type is sequence and spec.type is not string and spec.type | length > 0 -%}
96
+ {%- for type_name in spec.type -%}{{ render_markdown_type_name(type_name, spec) }}{% if not loop.last %} or {% endif %}{%- endfor -%}
97
+ {%- elif spec.type is defined and spec.type is sequence and spec.type is not string -%}
98
+ any
99
+ {%- elif spec.type -%}
100
+ {{- render_markdown_type_name(spec.type, spec) -}}
101
+ {%- elif spec['$ref'] is string -%}
102
+ {{- spec['$ref'].split('/') | last -}}
103
+ {%- elif spec.oneOf -%}
104
+ oneOf[{%- for variant in spec.oneOf -%}{{ render_markdown_type(variant) }}{% if not loop.last %} or {% endif %}{%- endfor -%}]
105
+ {%- elif spec.anyOf -%}
106
+ anyOf[{%- for variant in spec.anyOf -%}{{ render_markdown_type(variant) }}{% if not loop.last %} or {% endif %}{%- endfor -%}]
107
+ {%- elif spec.properties -%}
108
+ object
109
+ {%- elif 'items' in spec -%}
110
+ array of {{ render_markdown_type(spec['items']) }}
111
+ {%- else -%}
112
+ any
113
+ {%- endif -%}
114
+ {%- endmacro -%}
115
+
116
+ {%- macro render_xml_text(value) -%}
117
+ {{- value.split() | join(" ") -}}
118
+ {%- endmacro -%}
119
+
120
+ {%- macro render_python_string(value) -%}
121
+ '{{- value.split() | join(" ") | replace("\\", "\\\\") | replace("'", "\\'") -}}'
122
+ {%- endmacro -%}
123
+
124
+ {%- macro render_python_repr(value) -%}
125
+ {%- if value is string -%}
126
+ {{ render_python_string(value) }}
127
+ {%- elif value is sameas true -%}
128
+ True
129
+ {%- elif value is sameas false -%}
130
+ False
131
+ {%- elif value is none -%}
132
+ None
133
+ {%- elif value is mapping -%}
134
+ {{- "{" -}}
135
+ {%- for key, child in value | items -%}
136
+ {{ render_python_repr(key) }}: {{ render_python_repr(child) }}{%- if not loop.last -%}, {% endif -%}
137
+ {%- endfor -%}
138
+ {{- "}" -}}
139
+ {%- elif value is sequence -%}
140
+ {{- "[" -}}
141
+ {%- for child in value -%}
142
+ {{ render_python_repr(child) }}{%- if not loop.last -%}, {% endif -%}
143
+ {%- endfor -%}
144
+ {{- "]" -}}
145
+ {%- else -%}
146
+ {{- value -}}
147
+ {%- endif -%}
148
+ {%- endmacro -%}
149
+
150
+ {%- macro render_xml_value(value) -%}
151
+ {%- if value is string -%}{{ render_xml_text(value) }}{%- else -%}{{ render_python_repr(value) }}{%- endif -%}
152
+ {%- endmacro -%}
153
+
154
+ {%- macro render_xml_enum_value(value) -%}
155
+ {%- if value is string -%}"{{- value | replace("\\", "\\\\") | replace("\"", "\\\"") -}}"{%- else -%}"{{- render_python_repr(value) | replace("\\", "\\\\") | replace("\"", "\\\"") -}}"{%- endif -%}
156
+ {%- endmacro -%}
157
+
158
+ {%- macro render_xml_enum(values) -%}
159
+ {%- for value in values -%}{{ render_xml_enum_value(value) }}{%- if not loop.last -%}|{%- endif -%}{%- endfor -%}
160
+ {%- endmacro -%}
161
+
162
+ {%- macro render_xml_default_attr(value) -%}
163
+ {{- " default=" }}{%- if value is string -%}"{{- value | replace("\\", "\\\\") | replace("\"", "\\\"") -}}"{%- else -%}{{ render_xml_value(value) }}{%- endif -%}
164
+ {%- endmacro -%}
165
+
166
+ {%- macro render_xml_attr(name, value) -%}
167
+ {{- " " + name + "=" }}{%- if value == "" -%}""{%- else -%}{{ render_xml_value(value) }}{%- endif -%}
168
+ {%- endmacro -%}
169
+
170
+ {%- macro validate_schema(spec, path, lenient=false, classify=true, in_variant=false) -%}
171
+ {%- if spec is mapping -%}
172
+ {%- if not lenient -%}
173
+ {%- if spec.required is defined -%}
174
+ {%- if spec.required is string or spec.required is not sequence -%}
175
+ {{- raise_exception("Schema '" + path + "' has 'required' but it is not a list.") -}}
176
+ {%- endif -%}
177
+ {%- if spec.required | length > 0 and not spec.properties and not in_variant -%}
178
+ {{- raise_exception("Schema '" + path + "' has required fields but no properties object to define them.") -}}
179
+ {%- endif -%}
180
+ {%- if spec.properties -%}
181
+ {%- for required_name in spec.required -%}
182
+ {%- if required_name not in spec.properties -%}
183
+ {{- raise_exception("Schema '" + path + "' marks '" + required_name + "' as required, but that property is not defined in properties.") -}}
184
+ {%- endif -%}
185
+ {%- endfor -%}
186
+ {%- endif -%}
187
+ {%- endif -%}
188
+ {%- endif -%}
189
+ {#- renderability classification, piggybacking on this walk (no raises here): -#}
190
+ {#- constructs the pretty renderer does not fully handle flip RB.ok so the -#}
191
+ {#- tool falls back to verbatim JSON. Skipped entirely for json presentation. -#}
192
+ {%- if classify -%}
193
+ {%- for key, value in spec | items -%}
194
+ {%- if key == '$ref' -%}
195
+ {%- if value is not string -%}{%- set RB.ok = false -%}
196
+ {%- elif not (value.startswith('#/$defs/') or value.startswith('#/definitions/')) -%}{%- set RB.ok = false -%}{%- endif -%}
197
+ {%- elif key == '$defs' or key == 'definitions' -%}
198
+ {%- if value is mapping -%}
199
+ {%- for dk, dv in value | items -%}
200
+ {{- validate_schema(dv, path + ".$defs." + dk, true) -}}
201
+ {%- endfor -%}
202
+ {%- else -%}{%- set RB.ok = false -%}{%- endif -%}
203
+ {%- elif key == 'type' -%}
204
+ {%- if value is mapping -%}{%- set RB.ok = false -%}{%- endif -%}
205
+ {%- elif key == 'enum' -%}
206
+ {%- if value is string or value is mapping or value is not sequence -%}{%- set RB.ok = false -%}{%- endif -%}
207
+ {%- elif key == 'items' -%}
208
+ {#- any items shape renders: mapping structurally, others via repr detail -#}
209
+ {%- elif key == 'oneOf' or key == 'anyOf' -%}
210
+ {%- if value is mapping or value is string or value is not sequence -%}{%- set RB.ok = false -%}{%- endif -%}
211
+ {%- elif key == 'required' -%}
212
+ {%- if value and not spec.properties -%}{%- set RB.ok = false -%}{%- endif -%}
213
+ {%- elif ('|' ~ key ~ '|') in '|description|default|title|examples|properties|patternProperties|additionalProperties|returns|' -%}
214
+ {%- elif value is mapping -%}
215
+ {%- for uk, uv in value | items -%}
216
+ {%- if value_contains_mapping(uv) == 'true' -%}{%- set RB.ok = false -%}{%- endif -%}
217
+ {%- endfor -%}
218
+ {%- elif value is sequence and value is not string -%}
219
+ {%- if value_contains_mapping(value) == 'true' -%}{%- set RB.ok = false -%}{%- endif -%}
220
+ {%- endif -%}
221
+ {%- endfor -%}
222
+ {%- endif -%}
223
+ {%- if spec.properties -%}
224
+ {%- for child_name, child_spec in spec.properties | items -%}
225
+ {{- validate_schema(child_spec, path + "." + child_name, lenient, classify) -}}
226
+ {%- endfor -%}
227
+ {%- endif -%}
228
+ {%- if 'items' in spec -%}{{- validate_schema(spec['items'], path + "[]", lenient, classify) -}}{%- endif -%}
229
+ {%- if spec.oneOf -%}
230
+ {%- for variant in spec.oneOf -%}{{- validate_schema(variant, path + ".oneOf[" + (loop.index0 | string) + "]", lenient, classify, true) -}}{%- endfor -%}
231
+ {%- endif -%}
232
+ {%- if spec.anyOf -%}
233
+ {%- for variant in spec.anyOf -%}{{- validate_schema(variant, path + ".anyOf[" + (loop.index0 | string) + "]", lenient, classify, true) -}}{%- endfor -%}
234
+ {%- endif -%}
235
+ {%- if spec.additionalProperties is mapping -%}{{- validate_schema(spec.additionalProperties, path + ".additionalProperties", lenient, classify) -}}{%- endif -%}
236
+ {%- if spec.patternProperties is mapping -%}
237
+ {%- for pattern, pattern_spec in spec.patternProperties | items -%}
238
+ {{- validate_schema(pattern_spec, path + ".patternProperties[" + pattern + "]", lenient, classify) -}}
239
+ {%- endfor -%}
240
+ {%- endif -%}
241
+ {%- if spec.returns is mapping -%}{{- validate_schema(spec.returns, path + ".returns", lenient, classify) -}}{%- endif -%}
242
+ {%- endif -%}
243
+ {%- endmacro -%}
244
+
245
+ {%- macro validate_tools(tools_list, classify=true) -%}
246
+ {%- set RB.bad = '|' -%}
247
+ {%- for tool in tools_list -%}
248
+ {%- set fn = tool.function if tool.function is defined else tool -%}
249
+ {%- set RB.ok = true -%}
250
+ {%- if fn.parameters is defined and fn.parameters is string -%}
251
+ {{- raise_exception("tool.function.parameters must be a dict, not a JSON string. Parse it before passing to the template.") -}}
252
+ {%- endif -%}
253
+ {%- if fn.parameters is not defined or fn.parameters is none -%}
254
+ {%- if fn.arguments is defined -%}
255
+ {{- raise_exception("Tool '" + fn.name + "' has 'arguments' instead of 'parameters'. Rename 'arguments' to 'parameters'.") -}}
256
+ {%- else -%}
257
+ {{- raise_exception("Tool '" + fn.name + "' is missing required 'parameters' field. Each tool must have a 'parameters' dict with 'type', 'properties', and 'required' keys.") -}}
258
+ {%- endif -%}
259
+ {%- endif -%}
260
+ {{- validate_schema(fn.parameters, "tool." + fn.name + ".parameters", false, classify) -}}
261
+ {%- if classify -%}
262
+ {%- if fn.parameters is mapping -%}
263
+ {#- unknown container-valued keys at the parameters ROOT are never rendered -#}
264
+ {#- by the pretty path (root extras are dropped) -> verbatim fallback. -#}
265
+ {%- for rk, rv in fn.parameters | items -%}
266
+ {%- if rk not in ['type', 'description', 'enum', 'default', 'properties', 'required', 'optional', 'title', 'items', 'oneOf', 'anyOf', 'additionalProperties', 'patternProperties', 'returns', 'examples', '$defs', 'definitions', '$ref'] -%}
267
+ {%- if rv is mapping or (rv is sequence and rv is not string) -%}{%- set RB.ok = false -%}{%- endif -%}
268
+ {%- endif -%}
269
+ {%- endfor -%}
270
+ {%- else -%}
271
+ {%- set RB.ok = false -%}
272
+ {%- endif -%}
273
+ {%- endif -%}
274
+ {%- if fn.returns is mapping -%}{{- validate_schema(fn.returns, "tool." + fn.name + ".returns", false, classify) -}}{%- endif -%}
275
+ {%- if classify and fn.returns is not defined and fn.response is mapping -%}{{- validate_schema(fn.response, "tool." + fn.name + ".response", true) -}}{%- endif -%}
276
+ {#- unknown container-valued keys at the FUNCTION level are never rendered -> fallback. -#}
277
+ {%- if classify -%}
278
+ {%- for fk, fv in fn | items -%}
279
+ {%- if fk not in ['name', 'description', 'parameters', 'returns', 'response', 'type', 'function'] -%}
280
+ {%- if fv is mapping or (fv is sequence and fv is not string) -%}{%- set RB.ok = false -%}{%- endif -%}
281
+ {%- endif -%}
282
+ {%- endfor -%}
283
+ {%- endif -%}
284
+ {%- if not RB.ok -%}{%- set RB.bad = RB.bad ~ loop.index0 ~ '|' -%}{%- endif -%}
285
+ {%- endfor -%}
286
+ {%- endmacro -%}
287
+
288
+ {%- macro render_tools_json(tools_list) -%}
289
+ {{- "<ifm|tools>" }}
290
+ {%- for tool in tools_list %}
291
+ {{- "\n" }}
292
+ {{- tool | tojson }}
293
+ {%- endfor %}
294
+ {{- "\n</ifm|tools>" }}
295
+ {%- endmacro -%}
296
+
297
+ {%- macro render_xml_schema_attrs(spec, include_value_attrs) -%}
298
+ {%- if spec is mapping -%}
299
+ {%- set structural_keys = ["type", "description", "enum", "default", "properties", "required", "items", "oneOf", "anyOf", "additionalProperties", "patternProperties", "returns"] -%}
300
+ {%- if include_value_attrs and spec.enum -%}{{- " enum=" }}{{ render_xml_enum(spec.enum) }}{%- endif -%}
301
+ {%- if include_value_attrs and spec.default is defined -%}{{ render_xml_default_attr(spec.default) }}{%- endif -%}
302
+ {%- if spec.additionalProperties is defined and spec.additionalProperties is not mapping -%}{{ render_xml_attr("additionalProperties", spec.additionalProperties) }}{%- endif -%}
303
+ {%- if spec.patternProperties is defined and spec.patternProperties is not mapping -%}{{ render_xml_attr("patternProperties", spec.patternProperties) }}{%- endif -%}
304
+ {%- for key, value in spec | items -%}
305
+ {%- if key not in structural_keys -%}
306
+ {{ render_xml_attr(key, value) }}
307
+ {%- endif -%}
308
+ {%- endfor -%}
309
+ {%- endif -%}
310
+ {%- endmacro -%}
311
+
312
+ {%- macro xml_schema_has_children(spec, include_properties, include_description) -%}
313
+ {%- if spec is not mapping -%}
314
+ false
315
+ {%- elif (include_description and spec.description is defined) or (include_properties and spec.properties) or 'items' in spec or spec.oneOf or spec.anyOf or spec.additionalProperties is mapping or spec.patternProperties is mapping or spec.returns is defined -%}
316
+ true
317
+ {%- else -%}
318
+ false
319
+ {%- endif -%}
320
+ {%- endmacro -%}
321
+
322
+ {%- macro render_xml_schema_node(tag, spec, include_properties) -%}
323
+ {%- if spec is mapping and spec['$ref'] is string -%}
324
+ {%- set _r = spec['$ref'] -%}
325
+ {%- set _k = _r[8:] if _r.startswith('#/$defs/') else (_r[14:] if _r.startswith('#/definitions/') else none) -%}
326
+ {%- if _k is not none and ('|' + _k + '|') not in REFS.seen and REFS.defs[_k] is mapping -%}
327
+ {%- set spec = dict((REFS.defs[_k] | items | list) + (spec | items | rejectattr('0', 'equalto', '$ref') | list)) -%}
328
+ {%- set REFS.seen = REFS.seen + _k + '|' -%}
329
+ {%- if spec['$ref'] is string -%}
330
+ {%- set _r2 = spec['$ref'] -%}
331
+ {%- set _k2 = _r2[8:] if _r2.startswith('#/$defs/') else (_r2[14:] if _r2.startswith('#/definitions/') else none) -%}
332
+ {%- if _k2 is not none and REFS.defs[_k2] is mapping -%}
333
+ {%- set spec = dict((REFS.defs[_k2] | items | list) + (spec | items | rejectattr('0', 'equalto', '$ref') | list)) -%}
334
+ {%- set REFS.seen = REFS.seen + _k2 + '|' -%}
335
+ {%- endif -%}
336
+ {%- endif -%}
337
+ {%- endif -%}
338
+ {%- endif -%}
339
+ {%- if spec is mapping -%}
340
+ {{- "<" + tag + " type=" + render_compact_type(spec) }}{{ render_xml_schema_attrs(spec, true) }}
341
+ {%- if xml_schema_has_children(spec, include_properties, true) == 'true' -%}
342
+ {{- ">" }}{{ render_xml_schema_children(spec, include_properties, true) }}{{- "</" + tag + ">" }}
343
+ {%- else -%}
344
+ {{- "/>" }}
345
+ {%- endif -%}
346
+ {%- else -%}
347
+ {{- "<" + tag + ">" }}{{ render_xml_value(spec) }}{{- "</" + tag + ">" }}
348
+ {%- endif -%}
349
+ {%- endmacro -%}
350
+
351
+ {%- macro render_xml_pattern_property(pattern, spec) -%}
352
+ {%- if spec is mapping and spec['$ref'] is string -%}
353
+ {%- set _r = spec['$ref'] -%}
354
+ {%- set _k = _r[8:] if _r.startswith('#/$defs/') else (_r[14:] if _r.startswith('#/definitions/') else none) -%}
355
+ {%- if _k is not none and ('|' + _k + '|') not in REFS.seen and REFS.defs[_k] is mapping -%}
356
+ {%- set spec = dict((REFS.defs[_k] | items | list) + (spec | items | rejectattr('0', 'equalto', '$ref') | list)) -%}
357
+ {%- set REFS.seen = REFS.seen + _k + '|' -%}
358
+ {%- if spec['$ref'] is string -%}
359
+ {%- set _r2 = spec['$ref'] -%}
360
+ {%- set _k2 = _r2[8:] if _r2.startswith('#/$defs/') else (_r2[14:] if _r2.startswith('#/definitions/') else none) -%}
361
+ {%- if _k2 is not none and REFS.defs[_k2] is mapping -%}
362
+ {%- set spec = dict((REFS.defs[_k2] | items | list) + (spec | items | rejectattr('0', 'equalto', '$ref') | list)) -%}
363
+ {%- set REFS.seen = REFS.seen + _k2 + '|' -%}
364
+ {%- endif -%}
365
+ {%- endif -%}
366
+ {%- endif -%}
367
+ {%- endif -%}
368
+ {%- if spec is mapping -%}
369
+ {{- "<patternProperty" }}{{ render_xml_attr("pattern", pattern) }}{{- " type=" + render_compact_type(spec) }}{{ render_xml_schema_attrs(spec, true) }}
370
+ {%- if xml_schema_has_children(spec, true, true) == 'true' -%}
371
+ {{- ">" }}{{ render_xml_schema_children(spec, true, true) }}{{- "</patternProperty>" }}
372
+ {%- else -%}
373
+ {{- "/>" }}
374
+ {%- endif -%}
375
+ {%- else -%}
376
+ {{- "<patternProperty" }}{{ render_xml_attr("pattern", pattern) }}{{- ">" }}{{ render_xml_value(spec) }}{{- "</patternProperty>" }}
377
+ {%- endif -%}
378
+ {%- endmacro -%}
379
+
380
+ {%- macro render_xml_schema_children(spec, include_properties, include_description) -%}
381
+ {%- if include_description and spec.description is defined -%}{{- "<description>" }}{{ spec.description }}{{- "</description>" }}{%- endif -%}
382
+ {%- if include_properties and spec.properties -%}
383
+ {%- for child_name, child_spec in spec.properties | items -%}
384
+ {{- render_xml_param(child_name, child_spec, spec.required or []) }}
385
+ {%- endfor -%}
386
+ {%- endif -%}
387
+ {%- if 'items' in spec -%}{{ render_xml_schema_node("items", spec['items'], true) }}{%- endif -%}
388
+ {%- if spec.oneOf -%}
389
+ {{- "<oneOf>" }}
390
+ {%- for variant in spec.oneOf -%}{{ render_xml_schema_node("variant", variant, true) }}{%- endfor -%}
391
+ {{- "</oneOf>" }}
392
+ {%- endif -%}
393
+ {%- if spec.anyOf -%}
394
+ {{- "<anyOf>" }}
395
+ {%- for variant in spec.anyOf -%}{{ render_xml_schema_node("variant", variant, true) }}{%- endfor -%}
396
+ {{- "</anyOf>" }}
397
+ {%- endif -%}
398
+ {%- if spec.additionalProperties is mapping -%}{{ render_xml_schema_node("additionalProperties", spec.additionalProperties, true) }}{%- endif -%}
399
+ {%- if spec.patternProperties is mapping -%}
400
+ {{- "<patternProperties>" }}
401
+ {%- for pattern, pattern_spec in spec.patternProperties | items -%}{{ render_xml_pattern_property(pattern, pattern_spec) }}{%- endfor -%}
402
+ {{- "</patternProperties>" }}
403
+ {%- elif spec.patternProperties is defined -%}<patternProperties>{{ render_xml_value(spec.patternProperties) }}</patternProperties>{%- endif -%}
404
+ {%- if spec.returns is mapping -%}{{ render_xml_schema_node("returns", spec.returns, true) }}{%- elif spec.returns is defined -%}<returns>{{ render_xml_value(spec.returns) }}</returns>{%- endif -%}
405
+ {%- endmacro -%}
406
+
407
+ {%- macro render_xml_param(name, spec, required_list) -%}
408
+ {%- if spec is mapping and spec['$ref'] is string -%}
409
+ {%- set _r = spec['$ref'] -%}
410
+ {%- set _k = _r[8:] if _r.startswith('#/$defs/') else (_r[14:] if _r.startswith('#/definitions/') else none) -%}
411
+ {%- if _k is not none and ('|' + _k + '|') not in REFS.seen and REFS.defs[_k] is mapping -%}
412
+ {%- set spec = dict((REFS.defs[_k] | items | list) + (spec | items | rejectattr('0', 'equalto', '$ref') | list)) -%}
413
+ {%- set REFS.seen = REFS.seen + _k + '|' -%}
414
+ {%- if spec['$ref'] is string -%}
415
+ {%- set _r2 = spec['$ref'] -%}
416
+ {%- set _k2 = _r2[8:] if _r2.startswith('#/$defs/') else (_r2[14:] if _r2.startswith('#/definitions/') else none) -%}
417
+ {%- if _k2 is not none and REFS.defs[_k2] is mapping -%}
418
+ {%- set spec = dict((REFS.defs[_k2] | items | list) + (spec | items | rejectattr('0', 'equalto', '$ref') | list)) -%}
419
+ {%- set REFS.seen = REFS.seen + _k2 + '|' -%}
420
+ {%- endif -%}
421
+ {%- endif -%}
422
+ {%- endif -%}
423
+ {%- endif -%}
424
+ {{- "<param name=" + name + " type=" + render_compact_type(spec) }}
425
+ {%- if name in (required_list or []) -%}{{- " required=true" }}{%- endif -%}
426
+ {%- if spec.enum -%}{{- " enum=" }}{{ render_xml_enum(spec.enum) }}{%- endif -%}
427
+ {%- if spec.default is defined -%}{{ render_xml_default_attr(spec.default) }}{%- endif -%}
428
+ {{- render_xml_schema_attrs(spec, false) }}
429
+ {%- if spec.description or xml_schema_has_children(spec, true, false) == 'true' -%}
430
+ {{- ">" }}
431
+ {%- if spec.description -%}{{ spec.description }}{%- endif -%}
432
+ {{- render_xml_schema_children(spec, true, false) }}
433
+ {{- "</param>" }}
434
+ {%- else -%}
435
+ {{- "/>" }}
436
+ {%- endif -%}
437
+ {%- endmacro -%}
438
+
439
+ {%- macro render_tools_xml(tools_list) -%}
440
+ {{- "<ifm|tools>" }}
441
+ {%- for tool in tools_list -%}
442
+ {%- set fn = tool.function if tool.function is defined else tool -%}
443
+ {%- set REFS.defs = fn.parameters['$defs'] if (fn.parameters is mapping and fn.parameters['$defs'] is mapping) else (fn.parameters['definitions'] if (fn.parameters is mapping and fn.parameters['definitions'] is mapping) else {}) -%}
444
+ {%- set REFS.seen = '|' -%}
445
+ {%- set fnp = namespace(p=fn.parameters) -%}
446
+ {%- if fnp.p is mapping and fnp.p['$ref'] is string -%}
447
+ {%- set _r = fnp.p['$ref'] -%}
448
+ {%- set _k = _r[8:] if _r.startswith('#/$defs/') else (_r[14:] if _r.startswith('#/definitions/') else none) -%}
449
+ {%- if _k is not none and REFS.defs[_k] is mapping -%}
450
+ {%- set fnp.p = dict((REFS.defs[_k] | items | list) + (fnp.p | items | rejectattr('0', 'equalto', '$ref') | list)) -%}
451
+ {%- set REFS.seen = REFS.seen + _k + '|' -%}
452
+ {%- endif -%}
453
+ {%- endif -%}
454
+ {{- "\n<function name=" + fn.name + ">" }}
455
+ {%- if fn.description -%}
456
+ {{- "<description>" }}{{ fn.description }}{{- "</description>" }}
457
+ {%- endif -%}
458
+ {{- "<parameters>" }}
459
+ {%- if fnp.p and fnp.p.properties -%}
460
+ {%- for pname, pspec in fnp.p.properties | items -%}
461
+ {{- render_xml_param(pname, pspec, fnp.p.required or []) }}
462
+ {%- endfor -%}
463
+ {%- elif fnp.p is mapping and (fnp.p.oneOf or fnp.p.anyOf or 'items' in fnp.p) -%}
464
+ {{- render_xml_schema_children(fnp.p, true, false) }}
465
+ {%- endif -%}
466
+ {{- "</parameters>" }}
467
+ {%- set fn_ret = fn.returns if fn.returns is defined else fn.response -%}
468
+ {%- if fn_ret is mapping -%}{{ render_xml_schema_node("returns", fn_ret, true) }}{%- elif fn_ret is defined -%}<returns>{{ render_xml_value(fn_ret) }}</returns>{%- endif -%}
469
+ {{- "</function>" }}
470
+ {%- endfor -%}
471
+ {{- "\n</ifm|tools>" }}
472
+ {%- endmacro -%}
473
+
474
+ {%- macro render_markdown_literal(value) -%}
475
+ {%- if value is string and value == "" -%}""
476
+ {%- elif value is string -%}`{{ value | replace("\n", "\\n") }}`
477
+ {%- else -%}`{{ render_python_repr(value) }}`
478
+ {%- endif -%}
479
+ {%- endmacro -%}
480
+
481
+ {%- macro render_allowed_values(values) -%}
482
+ {%- for value in values -%}{{ render_markdown_literal(value) }}{% if not loop.last %}, {% endif %}{%- endfor -%}
483
+ {%- endmacro -%}
484
+
485
+ {%- macro render_markdown_value(value) -%}
486
+ {%- if value is string and value == "" -%}""{%- elif value is string -%}{{ value }}{%- else -%}{{ render_python_repr(value) }}{%- endif -%}
487
+ {%- endmacro -%}
488
+
489
+ {%- macro render_markdown_detail(indent, label, value) -%}
490
+ {{- "\n" + indent + " - " + label + ": " }}{{ render_markdown_value(value) }}
491
+ {%- endmacro -%}
492
+
493
+ {%- macro render_markdown_metadata_detail(label, value) -%}
494
+ {{- "\n- " + label + ": " }}{{ render_markdown_value(value) }}
495
+ {%- endmacro -%}
496
+
497
+ {%- macro render_markdown_schema_annotations(spec, indent, include_value_details) -%}
498
+ {%- if include_value_details and spec.description is defined -%}{{ render_markdown_detail(indent, "Description", spec.description | replace("\n", "\n" + indent + " ")) }}{%- endif -%}
499
+ {%- if include_value_details and spec.enum is defined -%}{{- "\n" + indent + " - Allowed values: " }}{{ render_allowed_values(spec.enum) }}{%- endif -%}
500
+ {%- if include_value_details and spec.default is defined -%}{{- "\n" + indent + " - Default: " }}{{ render_markdown_literal(spec.default) }}{%- endif -%}
501
+ {%- if spec.additionalProperties is defined -%}
502
+ {%- if spec.additionalProperties is mapping -%}
503
+ {{- "\n" + indent + " - Additional properties *(" + render_markdown_type(spec.additionalProperties) + ")*" }}
504
+ {{- render_markdown_schema_details(spec.additionalProperties, indent + " ", true) }}
505
+ {%- else -%}
506
+ {{ render_markdown_detail(indent, "Additional properties", spec.additionalProperties) }}
507
+ {%- endif -%}
508
+ {%- endif -%}
509
+ {%- endmacro -%}
510
+
511
+ {%- macro render_markdown_metadata_annotations(spec) -%}
512
+ {%- if spec.description is defined -%}{{ render_markdown_metadata_detail("Description", spec.description | replace("\n", "\n ")) }}{%- endif -%}
513
+ {%- if spec.enum is defined -%}{{- "\n- Allowed values: " }}{{ render_allowed_values(spec.enum) }}{%- endif -%}
514
+ {%- if spec.default is defined -%}{{- "\n- Default: " }}{{ render_markdown_literal(spec.default) }}{%- endif -%}
515
+ {%- if spec.additionalProperties is defined -%}
516
+ {%- if spec.additionalProperties is mapping -%}
517
+ {{- "\n- Additional properties *(" + render_markdown_type(spec.additionalProperties) + ")*" }}
518
+ {{- render_markdown_schema_details(spec.additionalProperties, "", true) }}
519
+ {%- else -%}
520
+ {{ render_markdown_metadata_detail("Additional properties", spec.additionalProperties) }}
521
+ {%- endif -%}
522
+ {%- endif -%}
523
+ {%- endmacro -%}
524
+
525
+ {%- macro render_markdown_schema_extras(spec, indent) -%}
526
+ {%- set rendered_keys = ["type", "description", "enum", "default", "properties", "required", "items", "oneOf", "anyOf", "additionalProperties", "patternProperties", "returns"] -%}
527
+ {%- for key, value in spec | items -%}
528
+ {%- if key not in rendered_keys -%}
529
+ {{- "\n" + indent + " - " + key + ": " }}{{ render_markdown_value(value) }}
530
+ {%- endif -%}
531
+ {%- endfor -%}
532
+ {%- endmacro -%}
533
+
534
+ {%- macro render_markdown_metadata_extras(spec) -%}
535
+ {%- set rendered_keys = ["type", "description", "enum", "default", "properties", "required", "items", "oneOf", "anyOf", "additionalProperties", "patternProperties", "returns"] -%}
536
+ {%- for key, value in spec | items -%}
537
+ {%- if key not in rendered_keys -%}
538
+ {{- "\n- " + key + ": " }}{{ render_markdown_value(value) }}
539
+ {%- endif -%}
540
+ {%- endfor -%}
541
+ {%- endmacro -%}
542
+
543
+ {%- macro markdown_schema_has_extra(spec) -%}
544
+ {%- set rendered_keys = ["type", "description", "enum", "default", "properties", "required", "items", "oneOf", "anyOf", "additionalProperties", "patternProperties", "returns"] -%}
545
+ {%- set found = namespace(value='false') -%}
546
+ {%- for key, value in spec | items -%}
547
+ {%- if key not in rendered_keys -%}{%- set found.value = 'true' -%}{%- endif -%}
548
+ {%- endfor -%}
549
+ {{- found.value -}}
550
+ {%- endmacro -%}
551
+
552
+ {%- macro markdown_parameter_schema_has_details(spec) -%}
553
+ {%- if spec.description is defined or spec.enum is defined or spec.default is defined or spec.additionalProperties is defined or spec.patternProperties is defined or 'items' in spec or spec.oneOf or spec.anyOf or spec.returns is defined or markdown_schema_has_extra(spec) == 'true' -%}
554
+ true
555
+ {%- else -%}
556
+ false
557
+ {%- endif -%}
558
+ {%- endmacro -%}
559
+
560
+ {%- macro render_markdown_schema_structure(spec, indent, include_properties) -%}
561
+ {%- if include_properties and spec.properties -%}
562
+ {%- for child_name, child_spec in spec.properties | items -%}
563
+ {{- render_markdown_param(child_name, child_spec, spec.required or [], indent + " ") }}
564
+ {%- endfor -%}
565
+ {%- endif -%}
566
+ {%- if 'items' in spec and spec['items'] is mapping -%}
567
+ {{- "\n" + indent + " - Items *(" + render_markdown_type(spec['items']) + ")*" }}
568
+ {{- render_markdown_schema_details(spec['items'], indent + " ", true) }}
569
+ {%- elif 'items' in spec -%}
570
+ {{ render_markdown_detail(indent, "Items", spec['items']) }}
571
+ {%- endif -%}
572
+ {%- if spec.oneOf -%}
573
+ {{- "\n" + indent + " - oneOf:" }}
574
+ {%- for variant in spec.oneOf -%}
575
+ {{- "\n" + indent + " - Variant " }}{{ loop.index }}{{- " *(" + render_markdown_type(variant) + ")*" }}
576
+ {{- render_markdown_schema_details(variant, indent + " ", true) }}
577
+ {%- endfor -%}
578
+ {%- endif -%}
579
+ {%- if spec.anyOf -%}
580
+ {{- "\n" + indent + " - anyOf:" }}
581
+ {%- for variant in spec.anyOf -%}
582
+ {{- "\n" + indent + " - Variant " }}{{ loop.index }}{{- " *(" + render_markdown_type(variant) + ")*" }}
583
+ {{- render_markdown_schema_details(variant, indent + " ", true) }}
584
+ {%- endfor -%}
585
+ {%- endif -%}
586
+ {%- if spec.patternProperties is mapping -%}
587
+ {{- "\n" + indent + " - Pattern properties:" }}
588
+ {%- for pattern, pattern_spec in spec.patternProperties | items -%}
589
+ {%- if pattern_spec is mapping -%}
590
+ {{- "\n" + indent + " - `" + pattern + "` *(" + render_markdown_type(pattern_spec) + ")*" }}
591
+ {{- render_markdown_schema_details(pattern_spec, indent + " ", true) }}
592
+ {%- else -%}
593
+ {{- "\n" + indent + " - `" + pattern + "`: " }}{{ render_markdown_value(pattern_spec) }}
594
+ {%- endif -%}
595
+ {%- endfor -%}
596
+ {%- elif spec.patternProperties is defined -%}
597
+ {{ render_markdown_detail(indent, "Pattern properties", spec.patternProperties) }}
598
+ {%- endif -%}
599
+ {%- if spec.returns is mapping -%}
600
+ {{- "\n" + indent + " - Returns *(" + render_markdown_type(spec.returns) + ")*" }}
601
+ {{- render_markdown_schema_details(spec.returns, indent + " ", true) }}
602
+ {%- elif spec.returns is defined -%}
603
+ {{ render_markdown_detail(indent, "Returns", spec.returns) }}
604
+ {%- endif -%}
605
+ {%- endmacro -%}
606
+
607
+ {%- macro render_markdown_schema_details(spec, indent, include_value_details) -%}
608
+ {%- if spec is mapping and spec['$ref'] is string -%}
609
+ {%- set _r = spec['$ref'] -%}
610
+ {%- set _k = _r[8:] if _r.startswith('#/$defs/') else (_r[14:] if _r.startswith('#/definitions/') else none) -%}
611
+ {%- if _k is not none and ('|' + _k + '|') not in REFS.seen and REFS.defs[_k] is mapping -%}
612
+ {%- set spec = dict((REFS.defs[_k] | items | list) + (spec | items | rejectattr('0', 'equalto', '$ref') | list)) -%}
613
+ {%- set REFS.seen = REFS.seen + _k + '|' -%}
614
+ {%- if spec['$ref'] is string -%}
615
+ {%- set _r2 = spec['$ref'] -%}
616
+ {%- set _k2 = _r2[8:] if _r2.startswith('#/$defs/') else (_r2[14:] if _r2.startswith('#/definitions/') else none) -%}
617
+ {%- if _k2 is not none and REFS.defs[_k2] is mapping -%}
618
+ {%- set spec = dict((REFS.defs[_k2] | items | list) + (spec | items | rejectattr('0', 'equalto', '$ref') | list)) -%}
619
+ {%- set REFS.seen = REFS.seen + _k2 + '|' -%}
620
+ {%- endif -%}
621
+ {%- endif -%}
622
+ {%- endif -%}
623
+ {%- endif -%}
624
+ {%- if spec is mapping -%}
625
+ {{- render_markdown_schema_annotations(spec, indent, include_value_details) }}
626
+ {{- render_markdown_schema_structure(spec, indent, true) }}
627
+ {{- render_markdown_schema_extras(spec, indent) }}
628
+ {%- elif spec is not sameas true and spec is not sameas false -%}
629
+ {{- "\n" + indent + " - Value: " }}{{ render_markdown_literal(spec) }}
630
+ {%- endif -%}
631
+ {%- endmacro -%}
632
+
633
+ {%- macro render_markdown_parameter_schema(spec) -%}
634
+ {%- if spec is mapping and spec['$ref'] is string -%}
635
+ {%- set _r = spec['$ref'] -%}
636
+ {%- set _k = _r[8:] if _r.startswith('#/$defs/') else (_r[14:] if _r.startswith('#/definitions/') else none) -%}
637
+ {%- if _k is not none and ('|' + _k + '|') not in REFS.seen and REFS.defs[_k] is mapping -%}
638
+ {%- set spec = dict((REFS.defs[_k] | items | list) + (spec | items | rejectattr('0', 'equalto', '$ref') | list)) -%}
639
+ {%- set REFS.seen = REFS.seen + _k + '|' -%}
640
+ {%- if spec['$ref'] is string -%}
641
+ {%- set _r2 = spec['$ref'] -%}
642
+ {%- set _k2 = _r2[8:] if _r2.startswith('#/$defs/') else (_r2[14:] if _r2.startswith('#/definitions/') else none) -%}
643
+ {%- if _k2 is not none and REFS.defs[_k2] is mapping -%}
644
+ {%- set spec = dict((REFS.defs[_k2] | items | list) + (spec | items | rejectattr('0', 'equalto', '$ref') | list)) -%}
645
+ {%- set REFS.seen = REFS.seen + _k2 + '|' -%}
646
+ {%- endif -%}
647
+ {%- endif -%}
648
+ {%- endif -%}
649
+ {%- endif -%}
650
+ {%- if spec is mapping -%}
651
+ {{- render_markdown_metadata_annotations(spec) }}
652
+ {%- if 'items' in spec and spec['items'] is mapping -%}
653
+ {{- "\n- Items *(" + render_markdown_type(spec['items']) + ")*" }}
654
+ {{- render_markdown_schema_details(spec['items'], "", true) }}
655
+ {%- elif 'items' in spec -%}
656
+ {{ render_markdown_metadata_detail("Items", spec['items']) }}
657
+ {%- endif -%}
658
+ {%- if spec.oneOf -%}
659
+ {{- "\n- oneOf:" }}
660
+ {%- for variant in spec.oneOf -%}
661
+ {{- "\n - Variant " }}{{ loop.index }}{{- " *(" + render_markdown_type(variant) + ")*" }}
662
+ {{- render_markdown_schema_details(variant, " ", true) }}
663
+ {%- endfor -%}
664
+ {%- endif -%}
665
+ {%- if spec.anyOf -%}
666
+ {{- "\n- anyOf:" }}
667
+ {%- for variant in spec.anyOf -%}
668
+ {{- "\n - Variant " }}{{ loop.index }}{{- " *(" + render_markdown_type(variant) + ")*" }}
669
+ {{- render_markdown_schema_details(variant, " ", true) }}
670
+ {%- endfor -%}
671
+ {%- endif -%}
672
+ {%- if spec.patternProperties is mapping -%}
673
+ {{- "\n- Pattern properties:" }}
674
+ {%- for pattern, pattern_spec in spec.patternProperties | items -%}
675
+ {%- if pattern_spec is mapping -%}
676
+ {{- "\n - `" + pattern + "` *(" + render_markdown_type(pattern_spec) + ")*" }}
677
+ {{- render_markdown_schema_details(pattern_spec, " ", true) }}
678
+ {%- else -%}
679
+ {{- "\n - `" + pattern + "`: " }}{{ render_markdown_value(pattern_spec) }}
680
+ {%- endif -%}
681
+ {%- endfor -%}
682
+ {%- elif spec.patternProperties is defined -%}
683
+ {{ render_markdown_metadata_detail("Pattern properties", spec.patternProperties) }}
684
+ {%- endif -%}
685
+ {%- if spec.returns is mapping -%}
686
+ {{- "\n- Returns *(" + render_markdown_type(spec.returns) + ")*" }}
687
+ {{- render_markdown_schema_details(spec.returns, "", true) }}
688
+ {%- elif spec.returns is defined -%}
689
+ {{ render_markdown_metadata_detail("Returns", spec.returns) }}
690
+ {%- endif -%}
691
+ {{- render_markdown_metadata_extras(spec) }}
692
+ {%- endif -%}
693
+ {%- endmacro -%}
694
+
695
+ {%- macro render_markdown_param(name, spec, required_list, indent) -%}
696
+ {%- if spec is mapping and spec['$ref'] is string -%}
697
+ {%- set _r = spec['$ref'] -%}
698
+ {%- set _k = _r[8:] if _r.startswith('#/$defs/') else (_r[14:] if _r.startswith('#/definitions/') else none) -%}
699
+ {%- if _k is not none and ('|' + _k + '|') not in REFS.seen and REFS.defs[_k] is mapping -%}
700
+ {%- set spec = dict((REFS.defs[_k] | items | list) + (spec | items | rejectattr('0', 'equalto', '$ref') | list)) -%}
701
+ {%- set REFS.seen = REFS.seen + _k + '|' -%}
702
+ {%- if spec['$ref'] is string -%}
703
+ {%- set _r2 = spec['$ref'] -%}
704
+ {%- set _k2 = _r2[8:] if _r2.startswith('#/$defs/') else (_r2[14:] if _r2.startswith('#/definitions/') else none) -%}
705
+ {%- if _k2 is not none and REFS.defs[_k2] is mapping -%}
706
+ {%- set spec = dict((REFS.defs[_k2] | items | list) + (spec | items | rejectattr('0', 'equalto', '$ref') | list)) -%}
707
+ {%- set REFS.seen = REFS.seen + _k2 + '|' -%}
708
+ {%- endif -%}
709
+ {%- endif -%}
710
+ {%- endif -%}
711
+ {%- endif -%}
712
+ {{- "\n" + indent + "- `" + name + "` *(" + render_markdown_type(spec) }}
713
+ {%- if name in (required_list or []) -%}{{- ", required" }}{%- endif -%}
714
+ {{- ")*" }}
715
+ {%- if spec.description -%}{{- " - " + spec.description | replace("\n", "\n" + indent + " ") }}{%- endif -%}
716
+ {%- if spec.enum -%}
717
+ {{- "\n" + indent + " - Allowed values: " }}{{ render_allowed_values(spec.enum) }}
718
+ {%- endif -%}
719
+ {%- if spec.default is defined -%}
720
+ {{- "\n" + indent + " - Default: " }}{{ render_markdown_literal(spec.default) }}
721
+ {%- endif -%}
722
+ {{- render_markdown_schema_details(spec, indent, false) }}
723
+ {%- endmacro -%}
724
+
725
+ {%- macro render_tools_markdown(tools_list) -%}
726
+ {{- "<ifm|tools>" }}
727
+ {%- for tool in tools_list -%}
728
+ {%- set fn = tool.function if tool.function is defined else tool -%}
729
+ {%- set REFS.defs = fn.parameters['$defs'] if (fn.parameters is mapping and fn.parameters['$defs'] is mapping) else (fn.parameters['definitions'] if (fn.parameters is mapping and fn.parameters['definitions'] is mapping) else {}) -%}
730
+ {%- set REFS.seen = '|' -%}
731
+ {%- set fnp = namespace(p=fn.parameters) -%}
732
+ {%- if fnp.p is mapping and fnp.p['$ref'] is string -%}
733
+ {%- set _r = fnp.p['$ref'] -%}
734
+ {%- set _k = _r[8:] if _r.startswith('#/$defs/') else (_r[14:] if _r.startswith('#/definitions/') else none) -%}
735
+ {%- if _k is not none and REFS.defs[_k] is mapping -%}
736
+ {%- set fnp.p = dict((REFS.defs[_k] | items | list) + (fnp.p | items | rejectattr('0', 'equalto', '$ref') | list)) -%}
737
+ {%- set REFS.seen = REFS.seen + _k + '|' -%}
738
+ {%- endif -%}
739
+ {%- endif -%}
740
+ {{- "\n## " + fn.name }}
741
+ {%- if fn.description -%}
742
+ {{- "\n" + fn.description }}
743
+ {%- endif -%}
744
+ {{- "\n\n**Parameters**" }}
745
+ {%- if fnp.p and fnp.p.properties -%}
746
+ {%- for pname, pspec in fnp.p.properties | items -%}
747
+ {{- render_markdown_param(pname, pspec, fnp.p.required or [], "") }}
748
+ {%- endfor -%}
749
+ {%- elif fnp.p is mapping and (fnp.p.oneOf or fnp.p.anyOf or 'items' in fnp.p) -%}
750
+ {{- render_markdown_parameter_schema(fnp.p) }}
751
+ {%- else -%}
752
+ {{- "\n- None" }}
753
+ {%- endif -%}
754
+ {%- set fn_ret = fn.returns if fn.returns is defined else fn.response -%}
755
+ {%- if fn_ret is mapping -%}
756
+ {{- "\n\n**Returns**" }}
757
+ {{- "\n- Return *(" + render_markdown_type(fn_ret) + ")*" }}
758
+ {{- render_markdown_schema_details(fn_ret, "", true) }}
759
+ {%- elif fn_ret is defined -%}
760
+ {{- "\n\n**Returns**\n- " }}{{ render_markdown_value(fn_ret) }}
761
+ {%- endif -%}
762
+ {%- if not loop.last -%}{{- "\n" }}{%- endif -%}
763
+ {%- endfor -%}
764
+ {{- "\n</ifm|tools>" }}
765
+ {%- endmacro -%}
766
+
767
+ {%- macro render_tool_presentation(tools_list, fmt) -%}
768
+ {%- if fmt == 'json' -%}
769
+ {{- render_tools_json(tools_list) }}
770
+ {%- elif RB.bad != '|' -%}
771
+ {#- some tool uses constructs the pretty renderers cannot represent (verdicts -#}
772
+ {#- computed during validate_tools): render the WHOLE toolset exactly as the -#}
773
+ {#- json presentation would, so the block stays uniform and model-familiar. -#}
774
+ {{- render_tools_json(tools_list) }}
775
+ {%- elif fmt == 'xml' -%}
776
+ {{- render_tools_xml(tools_list) }}
777
+ {%- elif fmt == 'markdown' -%}
778
+ {{- render_tools_markdown(tools_list) }}
779
+ {%- else -%}
780
+ {{- raise_exception("Unsupported tool_presentation_format: '" + fmt + "'. Supported formats: json, xml, markdown.") }}
781
+ {%- endif -%}
782
+ {%- endmacro -%}
783
+
784
+ {%- macro render_call_instructions(fmt) -%}
785
+ {%- if fmt == 'json' -%}
786
+ {{- "Wrap all tool calls in a single <ifm|tool_calls></ifm|tool_calls> block. For each call, emit one JSON object with the function name and arguments on the same line inside <ifm|tool_call></ifm|tool_call> tags:\n\n<ifm|tool_calls>\n<ifm|tool_call>{\"name\": <function-name>, \"arguments\": <args-json-object>}</ifm|tool_call>\n</ifm|tool_calls>" }}
787
+ {%- elif fmt == 'xml' -%}
788
+ {{- "Wrap all tool calls in a single <ifm|tool_calls></ifm|tool_calls> block. For each call, write the function name at the start of <ifm|tool_call>, followed by paired <ifm|arg_key> and <ifm|arg_value> tags for each argument:\n\n<ifm|tool_calls>\n<ifm|tool_call>$FUNCTION_NAME\n<ifm|arg_key>$PARAMETER_NAME</ifm|arg_key>\n<ifm|arg_value>$PARAMETER_VALUE</ifm|arg_value>\n...\n</ifm|tool_call>\n</ifm|tool_calls>\n\nString and scalar parameters should be written as plain text. Array and object parameters should be written as JSON literals." }}
789
+ {%- elif fmt == 'xml_typed' -%}
790
+ {{- "Wrap all tool calls in a single <ifm|tool_calls></ifm|tool_calls> block. For each call, write the function name at the start of <ifm|tool_call>, followed by <ifm|arg_key>, <ifm|arg_type>, and <ifm|arg_value> tags for each argument:\n\n<ifm|tool_calls>\n<ifm|tool_call>$FUNCTION_NAME\n<ifm|arg_key>$PARAMETER_NAME</ifm|arg_key>\n<ifm|arg_type>$ARGUMENT_TYPE</ifm|arg_type>\n<ifm|arg_value>$PARAMETER_VALUE</ifm|arg_value>\n...\n</ifm|tool_call>\n</ifm|tool_calls>\n\nUse the parameter type shown in the tool definition. If that type contains anyOf or oneOf, use the actual argument value type instead. String and scalar parameters should be written as plain text. Array and object parameters should be written as JSON literals." }}
791
+ {%- else -%}
792
+ {{- raise_exception("Unsupported tool_call_format: '" + fmt + "'. Supported formats: json, xml, xml_typed.") }}
793
+ {%- endif -%}
794
+ {%- endmacro -%}
795
+
796
+ {%- macro render_system_with_tools(tools_list, system_content, presentation_fmt, call_fmt) -%}
797
+ {{- "<|ifm|im_start|>system\n# Tools\nYou may call one or more tools to assist with the user query.\n\nAvailable tools are:\n\n" }}
798
+ {{- render_tool_presentation(tools_list, presentation_fmt) }}
799
+ {{- "\n\nWhen calling tools, you MUST follow the tool-call format below:\n\n" }}
800
+ {{- render_call_instructions(call_fmt) }}
801
+ {%- if system_content -%}
802
+ {{- "\n\n" + system_content }}
803
+ {%- endif -%}
804
+ {{- "<|ifm|im_end|>" }}
805
+ {%- endmacro -%}
806
+
807
+ {%- macro render_argument_value(value) -%}
808
+ {%- if value is string -%}{{- value -}}{%- else -%}{{- value | tojson -}}{%- endif -%}
809
+ {%- endmacro -%}
810
+
811
+ {%- macro render_value_type(value) -%}
812
+ {%- if value is none -%}null
813
+ {%- elif value is boolean -%}boolean
814
+ {%- elif value is integer -%}integer
815
+ {%- elif value is number -%}number
816
+ {%- elif value is string -%}string
817
+ {%- elif value is mapping -%}object
818
+ {%- elif value is sequence -%}array
819
+ {%- else -%}any
820
+ {%- endif -%}
821
+ {%- endmacro -%}
822
+
823
+ {%- macro schema_has_combinator(spec) -%}
824
+ {%- if spec.oneOf or spec.anyOf -%}
825
+ true
826
+ {%- elif spec.type is defined and spec.type is sequence and spec.type is not string and spec.type | length > 1 -%}
827
+ true
828
+ {%- elif spec.type == "array" and 'items' in spec -%}
829
+ {{- schema_has_combinator(spec['items']) -}}
830
+ {%- elif spec.properties -%}
831
+ {%- set found = namespace(value='false') -%}
832
+ {%- for child_name, child_spec in spec.properties | items -%}
833
+ {%- if schema_has_combinator(child_spec) == 'true' -%}
834
+ {%- set found.value = 'true' -%}
835
+ {%- endif -%}
836
+ {%- endfor -%}
837
+ {{- found.value -}}
838
+ {%- else -%}
839
+ false
840
+ {%- endif -%}
841
+ {%- endmacro -%}
842
+
843
+ {%- macro render_arg_type(tools_list, tool_name, arg_name, value) -%}
844
+ {%- set found = namespace(type='any') -%}
845
+ {%- for tool in tools_list -%}
846
+ {%- set fn = tool.function if tool.function is defined else tool -%}
847
+ {%- if fn.name == tool_name and fn.parameters and fn.parameters.properties and arg_name in fn.parameters.properties -%}
848
+ {%- set spec = fn.parameters.properties[arg_name] -%}
849
+ {%- if spec is mapping and spec['$ref'] is string -%}
850
+ {%- set _r = spec['$ref'] -%}
851
+ {%- set _k = _r[8:] if _r.startswith('#/$defs/') else (_r[14:] if _r.startswith('#/definitions/') else none) -%}
852
+ {%- set _d = fn.parameters['$defs'] if fn.parameters['$defs'] is mapping else fn.parameters['definitions'] -%}
853
+ {%- set spec = dict((_d[_k] | items | list) + (spec | items | rejectattr('0', 'equalto', '$ref') | list)) if (_k is not none and _d is mapping and _d[_k] is mapping) else spec -%}
854
+ {%- endif -%}
855
+ {%- if schema_has_combinator(spec) == 'true' -%}
856
+ {%- set found.type = render_value_type(value) -%}
857
+ {%- else -%}
858
+ {%- set found.type = render_compact_type(spec) -%}
859
+ {%- endif -%}
860
+ {%- endif -%}
861
+ {%- endfor -%}
862
+ {{- found.type -}}
863
+ {%- endmacro -%}
864
+
865
+ {%- macro render_tool_calls_block(tool_calls, fmt, tools_list) -%}
866
+ {{- "<ifm|tool_calls>" }}
867
+ {%- for raw_tool_call in tool_calls -%}
868
+ {%- set tool_call = raw_tool_call.function if raw_tool_call.function else raw_tool_call -%}
869
+ {%- if tool_call.arguments is string -%}
870
+ {{- raise_exception("tool_call.arguments must be a dict, not a JSON string. Parse it before passing to the template.") -}}
871
+ {%- endif -%}
872
+ {%- if fmt == 'json' -%}
873
+ {{- "\n<ifm|tool_call>{\"name\": \"" + tool_call.name + "\", \"arguments\": " }}{{ tool_call.arguments | tojson }}{{- "}</ifm|tool_call>" }}
874
+ {%- elif fmt == 'xml' or fmt == 'xml_typed' -%}
875
+ {{- "\n<ifm|tool_call>" + tool_call.name + "\n" }}
876
+ {%- for key, value in tool_call.arguments | items -%}
877
+ {{- "<ifm|arg_key>" + key + "</ifm|arg_key>\n" }}
878
+ {%- if fmt == 'xml_typed' -%}
879
+ {{- "<ifm|arg_type>" + render_arg_type(tools_list, tool_call.name, key, value) + "</ifm|arg_type>\n" }}
880
+ {%- endif -%}
881
+ {{- "<ifm|arg_value>" }}{{ render_argument_value(value) }}{{- "</ifm|arg_value>\n" }}
882
+ {%- endfor -%}
883
+ {{- "</ifm|tool_call>" }}
884
+ {%- else -%}
885
+ {{- raise_exception("Unsupported tool_call_format: '" + fmt + "'. Supported formats: json, xml, xml_typed.") -}}
886
+ {%- endif -%}
887
+ {%- endfor -%}
888
+ {{- "\n</ifm|tool_calls>" }}
889
+ {%- endmacro -%}
890
+
891
+ {%- macro render_tool_response_messages(raw_content) -%}
892
+ {%- if raw_content is string -%}
893
+ {{- '<|ifm|im_start|>tool\n' + raw_content + '<|ifm|im_end|>' }}
894
+ {%- elif raw_content is sequence and raw_content is not string and raw_content is not mapping -%}
895
+ {%- if raw_content | length == 0 -%}
896
+ {{- raise_exception("tool message content list must not be empty.") -}}
897
+ {%- endif -%}
898
+ {{- '<|ifm|im_start|>tool\n' -}}
899
+ {%- for item in raw_content -%}
900
+ {%- if not loop.first -%}{{- '\n' -}}{%- endif -%}
901
+ {%- if item is string -%}
902
+ {{- item -}}
903
+ {%- elif item is mapping and item.text is string -%}
904
+ {{- item.text -}}
905
+ {%- else -%}
906
+ {{- (item | tojson) -}}
907
+ {%- endif -%}
908
+ {%- endfor -%}
909
+ {{- '<|ifm|im_end|>' -}}
910
+ {%- else -%}
911
+ {{- '<|ifm|im_start|>tool\n' }}{{ raw_content | tojson }}{{- '<|ifm|im_end|>' }}
912
+ {%- endif -%}
913
+ {%- endmacro -%}
914
+
915
+ {%- set available_tools = tools if tools else [] -%}
916
+ {%- if (not available_tools) and messages[0].role == 'system' and messages[0].get('tools') -%}
917
+ {%- set available_tools = messages[0]['tools'] -%}
918
+ {%- endif -%}
919
+ {%- if available_tools -%}
920
+ {{- validate_tools(available_tools, tool_presentation_fmt != 'json') }}
921
+ {%- set system_content = '' -%}
922
+ {%- if messages[0].role == 'system' and messages[0].content -%}
923
+ {%- set system_content = messages[0].content -%}
924
+ {%- endif -%}
925
+ {{- render_system_with_tools(available_tools, system_content, tool_presentation_fmt, tool_call_fmt) }}
926
+ {%- else -%}
927
+ {%- if messages[0].role == 'system' -%}
928
+ {{- '<|ifm|im_start|>system\n' + messages[0].content + '<|ifm|im_end|>' }}
929
+ {%- endif -%}
930
+ {%- endif -%}
931
+
932
+ {%- for message in messages -%}
933
+ {%- if message.content is string -%}
934
+ {%- set content = message.content -%}
935
+ {%- else -%}
936
+ {%- set content = '' -%}
937
+ {%- endif -%}
938
+ {%- if (message.role == "user") or (message.role == "system" and not loop.first) -%}
939
+ {{- '<|ifm|im_start|>' + message.role + '\n' + content + '<|ifm|im_end|>' }}
940
+ {%- elif message.role == "assistant" -%}
941
+ {%- set thinking_content = '' -%}
942
+ {%- set think_tag = 'ifm|think' -%}
943
+ {%- if message.think is defined and message.think is string -%}
944
+ {%- set thinking_content = message.think -%}
945
+ {%- set think_tag = 'ifm|think' -%}
946
+ {%- elif message.think_fast is defined and message.think_fast is string -%}
947
+ {%- set thinking_content = message.think_fast -%}
948
+ {%- set think_tag = 'ifm|think_fast' -%}
949
+ {%- elif message.think_faster is defined and message.think_faster is string -%}
950
+ {%- set thinking_content = message.think_faster -%}
951
+ {%- set think_tag = 'ifm|think_faster' -%}
952
+ {%- elif message.reasoning_content is defined and message.reasoning_content is string -%}
953
+ {%- set thinking_content = message.reasoning_content -%}
954
+ {%- set think_tag = 'ifm|think' -%}
955
+ {%- elif message.reasoning is defined and message.reasoning is string -%}
956
+ {%- set thinking_content = message.reasoning -%}
957
+ {%- set think_tag = 'ifm|think' -%}
958
+ {%- elif message.think is not defined and message.reasoning is not defined and message.reasoning_content is not defined and message.think_fast is not defined and message.think_faster is not defined -%}
959
+ {{- raise_exception("Assistant message is missing a thinking field. Provide one of: think, reasoning, reasoning_content, think_fast, think_faster.") -}}
960
+ {%- else -%}
961
+ {{- raise_exception("Assistant thinking fields must be strings. Provide one of: think, reasoning, reasoning_content, think_fast, think_faster as a string.") -}}
962
+ {%- endif -%}
963
+ {{- '<|ifm|im_start|>' + message.role }}
964
+ {% generation %}
965
+ {%- if think_tag -%}
966
+ {%- if thinking_content -%}
967
+ {{- '<' + think_tag + '>\n' + thinking_content + '</' + think_tag + '>' + content }}
968
+ {%- else -%}
969
+ {{- '<' + think_tag + '>\n</' + think_tag + '>' + content }}
970
+ {%- endif -%}
971
+ {%- else -%}
972
+ {{- content }}
973
+ {%- endif -%}
974
+ {%- if message.tool_calls -%}
975
+ {{- render_tool_calls_block(message.tool_calls, tool_call_fmt, available_tools) }}
976
+ {%- endif -%}
977
+ {{- '<|ifm|im_end|>' -}}
978
+ {%- endgeneration -%}
979
+ {%- elif message.role == "tool" -%}
980
+ {{- render_tool_response_messages(message.content) }}
981
+ {%- endif -%}
982
+ {%- endfor -%}
983
+ {%- if add_generation_prompt -%}
984
+ {%- set effort = reasoning_effort | default('high') -%}
985
+ {%- if effort == 'high' -%}
986
+ {{- '<|ifm|im_start|>assistant\n<ifm|think>\n' }}
987
+ {%- elif effort == 'medium' -%}
988
+ {{- '<|ifm|im_start|>assistant\n<ifm|think_fast>\n' }}
989
+ {%- elif effort == 'low' -%}
990
+ {{- '<|ifm|im_start|>assistant\n<ifm|think_faster>\n' }}
991
+ {%- else -%}
992
+ {{- raise_exception("Unsupported reasoning_effort: '" + effort + "'. Supported values: high, medium, low.") -}}
993
+ {%- endif -%}
994
+ {%- endif -%}
config.json ADDED
The diff for this file is too large to render. See raw diff
 
configuration_k2_horizon.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """K2Horizon model configuration"""
15
+
16
+ from huggingface_hub.dataclasses import strict
17
+
18
+ from transformers.configuration_utils import PreTrainedConfig
19
+ from transformers.modeling_rope_utils import RopeParameters
20
+
21
+
22
+ @strict
23
+ class K2HorizonConfig(PreTrainedConfig):
24
+ r"""
25
+ decoder_sparse_step (`int`, *optional*, defaults to 1):
26
+ The frequency of the MoE layer.
27
+ mlp_only_layers (`list[int]`, *optional*, defaults to `[]`):
28
+ Indicate which layers use K2HorizonMLP rather than K2HorizonSparseMoeBlock
29
+ The list contains layer index, from 0 to num_layers-1 if we have num_layers layers
30
+ If `mlp_only_layers` is empty, `decoder_sparse_step` is used to determine the sparsity.
31
+
32
+ ```python
33
+ >>> from transformers import K2HorizonModel, K2HorizonConfig
34
+
35
+ >>> # Initializing a K2Horizon style configuration
36
+ >>> configuration = K2HorizonConfig()
37
+ >>> model = K2HorizonModel(configuration)
38
+
39
+ >>> # Accessing the model configuration
40
+ >>> configuration = model.config
41
+ ```
42
+ """
43
+
44
+ model_type = "k2_horizon"
45
+ keys_to_ignore_at_inference = ["past_key_values"]
46
+
47
+ vocab_size: int = 151936
48
+ hidden_size: int = 2048
49
+ intermediate_size: int = 6144
50
+ num_hidden_layers: int = 24
51
+ num_attention_heads: int = 32
52
+ num_key_value_heads: int = 4
53
+ hidden_act: str = "silu"
54
+ max_position_embeddings: int = 32768
55
+ initializer_range: float = 0.02
56
+ rms_norm_eps: float = 1e-6
57
+ use_cache: bool = True
58
+ tie_word_embeddings: bool = False
59
+ rope_parameters: RopeParameters | dict | None = None
60
+ attention_bias: bool = False
61
+ use_sliding_window: bool = False
62
+ sliding_window: int | None = 4096
63
+ attention_dropout: float | int = 0.0
64
+ decoder_sparse_step: int = 1
65
+ moe_intermediate_size: int = 768
66
+ num_experts_per_tok: int = 8
67
+ num_experts: int = 128
68
+ norm_topk_prob: bool = False
69
+ output_router_logits: bool = False
70
+ router_aux_loss_coef: float = 0.001
71
+ mlp_only_layers: list[int] | None = None
72
+ pad_token_id: int | None = None
73
+ bos_token_id: int | None = None
74
+ eos_token_id: int | list[int] | None = None
75
+
76
+ head_dim: int = 128
77
+ query_key_norm: bool = True
78
+ moe_gate_bias: bool = False
79
+ layernorm_num_groups: int = 1
80
+ num_shared_experts: int = 0
81
+ router_score_func: str = "softmax"
82
+ router_scaling_factor: float | None = 1.0
83
+ rope_head_dim: int | None = None
84
+ attention_gate_func: str | None = None
85
+ mova_num_experts: int = 0
86
+ mova_num_experts_per_tok: int = 0
87
+
88
+ def __post_init__(self, **kwargs):
89
+ self.sliding_window = self.sliding_window if self.use_sliding_window else None
90
+ self.mlp_only_layers = [] if self.mlp_only_layers is None else self.mlp_only_layers
91
+ if self.router_scaling_factor is None:
92
+ self.router_scaling_factor = 1.0
93
+ super().__post_init__(**kwargs)
94
+
95
+
96
+ __all__ = ["K2HorizonConfig"]
generation_config.json ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token_id": 0,
3
+ "eos_token_id": [
4
+ 1,
5
+ 250019
6
+ ],
7
+ "transformers_version": "5.15.0"
8
+ }
model-00001-of-00009.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:20f968b20d056805f5beaa5eaec91108a83c3413cf5f2b84caf2cd54192933cd
3
+ size 4999816512
model-00002-of-00009.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:729ac6d480fbf3254558306096338dcb8bf60fea718169ac4ab3565de9979089
3
+ size 4998702672
model-00003-of-00009.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:43462d07a0a66e8bfd0a6c034b18661df47bddbb24213bd6b272a7b6d4812f84
3
+ size 5000409424
model-00004-of-00009.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ef4259b35026e7dcc64ddd84e442e5601a7dba919417821b372f9d1b561d1935
3
+ size 5000295928
model-00005-of-00009.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0750c723c194269a6dbbd1fbe7e027287f4140dd394fce7ad84da0bcff2ab715
3
+ size 5000446144
model-00006-of-00009.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:613ba0b29e52f334572f64f29b081de1fb329a4a979ff88dfc08b1ade410e97e
3
+ size 4999632056
model-00007-of-00009.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b9ef077468670db9aeaac1dc2a8b111743b4ccd9b7163d1b85a032c372f27919
3
+ size 4995867416
model-00008-of-00009.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:51cd26d6e8e49e95026c09f801dfd28e32be94afb13800c553e4fc9c89bd37b3
3
+ size 4998735488
model-00009-of-00009.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1ed0904511ada394ff0b1a0b2fc37005b6e0922b8818e1a47c01f1d4986e2a1d
3
+ size 4489985160
model.safetensors.index.json ADDED
The diff for this file is too large to render. See raw diff
 
modeling_k2_horizon.py ADDED
@@ -0,0 +1,1116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/qwen3_moe/modular_qwen3_moe.py.
3
+ # Do NOT edit this file manually as any edits will be overwritten by the generation of
4
+ # the file from the modular. If any change should be done, please apply the change to the
5
+ # modular_qwen3_moe.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # coding=utf-8
8
+ # Copyright 2025 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.
9
+ #
10
+ # Licensed under the Apache License, Version 2.0 (the "License");
11
+ # you may not use this file except in compliance with the License.
12
+ # You may obtain a copy of the License at
13
+ #
14
+ # http://www.apache.org/licenses/LICENSE-2.0
15
+ #
16
+ # Unless required by applicable law or agreed to in writing, software
17
+ # distributed under the License is distributed on an "AS IS" BASIS,
18
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19
+ # See the License for the specific language governing permissions and
20
+ # limitations under the License.
21
+
22
+ from typing import Callable, Optional, Union
23
+
24
+ import math
25
+ import torch
26
+ import torch.nn.functional as F
27
+ from torch import nn
28
+
29
+ from transformers.activations import ACT2FN
30
+ from transformers.cache_utils import Cache, DynamicCache
31
+ from transformers.generation import GenerationMixin
32
+ from transformers.masking_utils import create_causal_mask, create_sliding_window_causal_mask
33
+ from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
34
+ from transformers.modeling_layers import (
35
+ GenericForQuestionAnswering,
36
+ GenericForSequenceClassification,
37
+ GenericForTokenClassification,
38
+ GradientCheckpointingLayer,
39
+ )
40
+ from transformers.modeling_outputs import MoeCausalLMOutputWithPast, MoeModelOutputWithPast
41
+ from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
42
+ from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
43
+ from transformers.processing_utils import Unpack
44
+ from transformers.utils import TransformersKwargs, auto_docstring, can_return_tuple
45
+ from transformers.utils.generic import maybe_autocast
46
+ from transformers.utils.deprecation import deprecate_kwarg
47
+ from transformers.utils.output_capturing import OutputRecorder
48
+
49
+ from .configuration_k2_horizon import K2HorizonConfig
50
+
51
+
52
+ def rotate_half(x):
53
+ """Rotates half the hidden dims of the input."""
54
+ x1 = x[..., : x.shape[-1] // 2]
55
+ x2 = x[..., x.shape[-1] // 2:]
56
+ return torch.cat((-x2, x1), dim=-1)
57
+
58
+
59
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
60
+ """Applies Rotary Position Embedding to the query and key tensors.
61
+
62
+ Args:
63
+ q (`torch.Tensor`): The query tensor.
64
+ k (`torch.Tensor`): The key tensor.
65
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
66
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
67
+ position_ids (`torch.Tensor`, *optional*):
68
+ Deprecated and unused.
69
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
70
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
71
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
72
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
73
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
74
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
75
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
76
+ Returns:
77
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
78
+ """
79
+ cos = cos.unsqueeze(unsqueeze_dim)
80
+ sin = sin.unsqueeze(unsqueeze_dim)
81
+ q_embed = (q * cos) + (rotate_half(q) * sin)
82
+ k_embed = (k * cos) + (rotate_half(k) * sin)
83
+ return q_embed, k_embed
84
+
85
+
86
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
87
+ """
88
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
89
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
90
+ """
91
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
92
+ if n_rep == 1:
93
+ return hidden_states
94
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
95
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
96
+
97
+
98
+ def split_to_interleaved(x):
99
+ # Split halves: x0 x1 x2 x3 ... y0 y1 y2 y3 ...
100
+ # Interleaved: x0 y0 x1 y1 x2 y2 x3 y3 ...
101
+ return x.reshape(*x.shape[:-1], 2, -1).transpose(-1, -2).reshape(*x.shape[:-1], -1)
102
+
103
+
104
+ def interleaved_to_split(x):
105
+ # Interleaved: x0 y0 x1 y1 x2 y2 x3 y3 ...
106
+ # Split halves: x0 x1 x2 x3 ... y0 y1 y2 y3 ...
107
+ return x.reshape(*x.shape[:-1], -1, 2).transpose(-1, -2).reshape(*x.shape[:-1], -1)
108
+
109
+
110
+ def eager_attention_forward(
111
+ module: nn.Module,
112
+ query: torch.Tensor,
113
+ key: torch.Tensor,
114
+ value: torch.Tensor,
115
+ attention_mask: Optional[torch.Tensor],
116
+ scaling: float,
117
+ dropout: float = 0.0,
118
+ **kwargs: Unpack[TransformersKwargs],
119
+ ):
120
+ key_states = repeat_kv(key, module.num_key_value_groups)
121
+ value_states = repeat_kv(value, module.num_key_value_groups)
122
+
123
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
124
+ if attention_mask is not None:
125
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
126
+ attn_weights = attn_weights + causal_mask
127
+
128
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
129
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
130
+ attn_output = torch.matmul(attn_weights, value_states)
131
+ attn_output = attn_output.transpose(1, 2).contiguous()
132
+
133
+ return attn_output, attn_weights
134
+
135
+
136
+ def calc_router_weights(
137
+ router_logits: torch.Tensor,
138
+ router_bias: Optional[torch.Tensor],
139
+ score_func: str,
140
+ top_k: int,
141
+ scaling_factor: Optional[float],
142
+ ) -> tuple[torch.Tensor, torch.Tensor]:
143
+ """Return native-XLLM-compatible routing weights and selected experts.
144
+
145
+ XLLM applies router bias only to the values used for top-k selection. The
146
+ selected routes are still weighted by the original router probabilities,
147
+ then optionally normalized and scaled.
148
+ """
149
+ if score_func == "softmax":
150
+ routing_scores = F.softmax(router_logits, dim=-1, dtype=torch.float32)
151
+ elif score_func == "sigmoid":
152
+ routing_scores = torch.sigmoid(router_logits.to(torch.float32))
153
+ else:
154
+ raise ValueError(f"Unsupported router score function: {score_func}")
155
+
156
+ selection_scores = routing_scores
157
+ if router_bias is not None:
158
+ selection_scores = selection_scores + router_bias.to(selection_scores)
159
+
160
+ selected_indices = torch.topk(selection_scores, top_k, dim=-1).indices
161
+ routing_weights = torch.gather(routing_scores, dim=-1, index=selected_indices)
162
+ if top_k > 1:
163
+ routing_weights = routing_weights / routing_weights.sum(dim=-1, keepdim=True)
164
+ if scaling_factor is not None:
165
+ routing_weights = routing_weights * scaling_factor
166
+ return routing_weights, selected_indices
167
+
168
+
169
+ def combine_routed_experts(
170
+ hidden_states: torch.Tensor,
171
+ routing_weights: torch.Tensor,
172
+ selected_indices: torch.Tensor,
173
+ experts: nn.ModuleList,
174
+ activation: Optional[Callable[[torch.Tensor], torch.Tensor]] = None,
175
+ ) -> torch.Tensor:
176
+ num_tokens, hidden_dim = hidden_states.shape
177
+ final_hidden_states = torch.zeros(
178
+ (num_tokens, experts[0].out_features),
179
+ dtype=hidden_states.dtype,
180
+ device=hidden_states.device,
181
+ )
182
+ expert_mask = torch.nn.functional.one_hot(
183
+ selected_indices, num_classes=len(experts)
184
+ ).permute(2, 1, 0)
185
+
186
+ for expert_idx in torch.nonzero(expert_mask.sum(dim=(-1, -2)), as_tuple=False).flatten():
187
+ topk_positions, token_positions = torch.where(expert_mask[int(expert_idx)])
188
+ expert_states = experts[int(expert_idx)](hidden_states[token_positions])
189
+ if activation is not None:
190
+ expert_states = activation(expert_states)
191
+ expert_states = expert_states * routing_weights[token_positions, topk_positions, None].to(expert_states.dtype)
192
+ final_hidden_states.index_add_(0, token_positions, expert_states.to(hidden_states.dtype))
193
+
194
+ return final_hidden_states
195
+
196
+
197
+ class K2HorizonAttention(nn.Module):
198
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
199
+
200
+ def __init__(self, config: K2HorizonConfig, layer_idx: int):
201
+ super().__init__()
202
+ self.config = config
203
+ self.layer_idx = layer_idx
204
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
205
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
206
+ self.scaling = self.head_dim ** -0.5
207
+ self.attention_dropout = config.attention_dropout
208
+ self.is_causal = True
209
+
210
+ self.rope_head_dim = self.head_dim if config.rope_head_dim is None else config.rope_head_dim
211
+
212
+ self.q_proj = nn.Linear(
213
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
214
+ )
215
+ self.k_proj = nn.Linear(
216
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
217
+ )
218
+ self.v_proj = nn.Linear(
219
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
220
+ )
221
+ self.o_proj = nn.Linear(
222
+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
223
+ )
224
+
225
+ self.gate_func = config.attention_gate_func
226
+ if self.gate_func is not None:
227
+ self.gate_proj = nn.Linear(
228
+ config.hidden_size,
229
+ config.num_attention_heads * self.head_dim,
230
+ bias=False)
231
+
232
+ if config.query_key_norm:
233
+ self.q_norm = K2HorizonRMSNorm(
234
+ hidden_size=config.num_attention_heads * self.head_dim,
235
+ n_groups=config.num_attention_heads,
236
+ eps=config.rms_norm_eps)
237
+ self.k_norm = K2HorizonRMSNorm(
238
+ hidden_size=config.num_key_value_heads * self.head_dim,
239
+ n_groups=config.num_key_value_heads,
240
+ eps=config.rms_norm_eps)
241
+
242
+ self.sliding_window = getattr(config, "sliding_window", None)
243
+
244
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
245
+ def forward(
246
+ self,
247
+ hidden_states: torch.Tensor,
248
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
249
+ attention_mask: Optional[torch.Tensor],
250
+ past_key_values: Optional[Cache] = None,
251
+ cache_position: Optional[torch.LongTensor] = None,
252
+ **kwargs: Unpack[FlashAttentionKwargs],
253
+ ) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
254
+ input_shape = hidden_states.shape[:-1]
255
+ hidden_shape = (*input_shape, -1, self.head_dim)
256
+
257
+ if self.config.query_key_norm:
258
+ query_states = self.q_norm(self.q_proj(hidden_states)).view(hidden_shape).transpose(1, 2)
259
+ key_states = self.k_norm(self.k_proj(hidden_states)).view(hidden_shape).transpose(1, 2)
260
+ else:
261
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
262
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
263
+
264
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
265
+
266
+ cos, sin = position_embeddings
267
+ if self.rope_head_dim == self.head_dim:
268
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
269
+ else:
270
+ query_states, query_states_ = torch.split(
271
+ split_to_interleaved(query_states),
272
+ split_size_or_sections=[self.rope_head_dim, self.head_dim - self.rope_head_dim],
273
+ dim=-1)
274
+
275
+ key_states, key_states_ = torch.split(
276
+ split_to_interleaved(key_states),
277
+ split_size_or_sections=[self.rope_head_dim, self.head_dim - self.rope_head_dim],
278
+ dim=-1)
279
+
280
+ query_states, key_states = apply_rotary_pos_emb(
281
+ interleaved_to_split(query_states),
282
+ interleaved_to_split(key_states),
283
+ cos,
284
+ sin)
285
+
286
+ query_states = interleaved_to_split(torch.cat(
287
+ [split_to_interleaved(query_states), query_states_], dim=-1))
288
+ key_states = interleaved_to_split(torch.cat(
289
+ [split_to_interleaved(key_states), key_states_], dim=-1))
290
+
291
+ if past_key_values is not None:
292
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
293
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
294
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
295
+
296
+ attention_interface: Callable = eager_attention_forward
297
+ if self.config._attn_implementation != "eager":
298
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
299
+
300
+ attn_output, attn_weights = attention_interface(
301
+ self,
302
+ query_states,
303
+ key_states,
304
+ value_states,
305
+ attention_mask,
306
+ dropout=0.0 if not self.training else self.attention_dropout,
307
+ scaling=self.scaling,
308
+ sliding_window=self.sliding_window, # diff with Llama
309
+ **kwargs,
310
+ )
311
+
312
+ if self.gate_func is not None:
313
+ gate = self.gate_proj(hidden_states).view(
314
+ input_shape + (-1, self.head_dim))
315
+ if self.gate_func == 'silu':
316
+ gate = F.silu(gate)
317
+ else:
318
+ assert self.gate_func == 'softplus'
319
+ gate = F.softplus(gate, beta=math.log(2))
320
+
321
+ attn_output = attn_output * gate
322
+
323
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
324
+ attn_output = self.o_proj(attn_output)
325
+ return attn_output, attn_weights
326
+
327
+
328
+ def apply_rotary_pos_emb_xllm(q, k, freqs_cis):
329
+ if q.shape[-1] % 2 != 0 or k.shape[-1] % 2 != 0:
330
+ raise ValueError(f"RoPE dimensions must be even, got q={q.shape[-1]} and k={k.shape[-1]}")
331
+ q_ = torch.view_as_complex(q.float().reshape(*q.shape[:-1], -1, 2))
332
+ k_ = torch.view_as_complex(k.float().reshape(*k.shape[:-1], -1, 2))
333
+ if freqs_cis.ndim == 2:
334
+ freqs_cis = freqs_cis.unsqueeze(1)
335
+ elif freqs_cis.ndim == 3:
336
+ freqs_cis = freqs_cis.unsqueeze(2)
337
+ else:
338
+ raise ValueError(f"Unsupported freqs_cis shape: {tuple(freqs_cis.shape)}")
339
+ if freqs_cis.shape[-1] != q_.shape[-1] or freqs_cis.shape[-1] != k_.shape[-1]:
340
+ raise ValueError(
341
+ "RoPE frequency dimension mismatch: "
342
+ f"q_rope_dim={q.shape[-1]}, k_rope_dim={k.shape[-1]}, "
343
+ f"q_complex_dim={q_.shape[-1]}, k_complex_dim={k_.shape[-1]}, "
344
+ f"freqs_complex_dim={freqs_cis.shape[-1]}, freqs_shape={tuple(freqs_cis.shape)}"
345
+ )
346
+ q_embed = torch.view_as_real(q_ * freqs_cis).flatten(-2).to(q.dtype)
347
+ k_embed = torch.view_as_real(k_ * freqs_cis).flatten(-2).to(k.dtype)
348
+ return q_embed, k_embed
349
+
350
+
351
+ class K2HorizonMoVAAttention(nn.Module):
352
+ """MoVA attention with routed value experts and optional post-attention gate."""
353
+
354
+ def __init__(self, config: K2HorizonConfig, layer_idx: int):
355
+ super().__init__()
356
+ self.config = config
357
+ self.layer_idx = layer_idx
358
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
359
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
360
+ self.scaling = self.head_dim**-0.5
361
+ self.attention_dropout = config.attention_dropout
362
+ self.is_causal = True
363
+
364
+ self.num_experts_per_tok = config.mova_num_experts_per_tok
365
+ self.router_score_func = config.router_score_func
366
+ self.router_scaling_factor = config.router_scaling_factor
367
+ self.gate_func = config.attention_gate_func
368
+
369
+ self.rope_head_dim = self.head_dim if config.rope_head_dim is None else config.rope_head_dim
370
+
371
+ self.q_proj = nn.Linear(
372
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
373
+ )
374
+ self.k_proj = nn.Linear(
375
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
376
+ )
377
+ self.o_proj = nn.Linear(
378
+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
379
+ )
380
+ self.v_router = nn.Linear(
381
+ config.hidden_size,
382
+ config.mova_num_experts,
383
+ bias=config.moe_gate_bias)
384
+ self.v_experts = nn.ModuleList([
385
+ nn.Linear(
386
+ config.hidden_size,
387
+ config.num_key_value_heads * self.head_dim,
388
+ bias=False
389
+ ) for _ in range(config.mova_num_experts)
390
+ ])
391
+
392
+ if self.gate_func is not None:
393
+ self.gate_proj = nn.Linear(
394
+ config.hidden_size,
395
+ config.num_attention_heads * self.head_dim,
396
+ bias=False)
397
+
398
+ if config.query_key_norm:
399
+ self.q_norm = K2HorizonRMSNorm(
400
+ hidden_size=config.num_attention_heads * self.head_dim,
401
+ n_groups=config.num_attention_heads,
402
+ eps=config.rms_norm_eps,
403
+ )
404
+ self.k_norm = K2HorizonRMSNorm(
405
+ hidden_size=config.num_key_value_heads * self.head_dim,
406
+ n_groups=config.num_key_value_heads,
407
+ eps=config.rms_norm_eps,
408
+ )
409
+
410
+ self.sliding_window = getattr(config, "sliding_window", None)
411
+
412
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
413
+ def forward(
414
+ self,
415
+ hidden_states: torch.Tensor,
416
+ position_embeddings: torch.Tensor,
417
+ attention_mask: Optional[torch.Tensor],
418
+ past_key_values: Optional[Cache] = None,
419
+ cache_position: Optional[torch.LongTensor] = None,
420
+ **kwargs: Unpack[FlashAttentionKwargs],
421
+ ) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
422
+ input_shape = hidden_states.shape[:-1]
423
+ hidden_shape = (*input_shape, -1, self.head_dim)
424
+ flat_hidden_states = hidden_states.reshape(-1, hidden_states.shape[-1])
425
+
426
+ # Match native MOVAttention router semantics exactly: compute logits with
427
+ # the weight-only linear and apply router bias only to selection scores.
428
+ router_logits = F.linear(flat_hidden_states, self.v_router.weight)
429
+ routing_weights, selected_values = calc_router_weights(
430
+ router_logits=router_logits,
431
+ router_bias=self.v_router.bias,
432
+ score_func=self.router_score_func,
433
+ top_k=self.num_experts_per_tok,
434
+ scaling_factor=self.router_scaling_factor,
435
+ )
436
+
437
+ mixed_value_states = combine_routed_experts(
438
+ hidden_states=flat_hidden_states,
439
+ routing_weights=routing_weights,
440
+ selected_indices=selected_values,
441
+ experts=self.v_experts,
442
+ activation=F.silu)
443
+
444
+ value_states = mixed_value_states.view(hidden_shape).transpose(1, 2)
445
+
446
+ if self.config.query_key_norm:
447
+ query_states = self.q_norm(self.q_proj(hidden_states)).view(hidden_shape).transpose(1, 2)
448
+ key_states = self.k_norm(self.k_proj(hidden_states)).view(hidden_shape).transpose(1, 2)
449
+ else:
450
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
451
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
452
+
453
+ cos, sin = position_embeddings
454
+ if self.rope_head_dim == self.head_dim:
455
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
456
+ else:
457
+ query_states, query_states_ = torch.split(
458
+ split_to_interleaved(query_states),
459
+ split_size_or_sections=[self.rope_head_dim, self.head_dim - self.rope_head_dim],
460
+ dim=-1)
461
+
462
+ key_states, key_states_ = torch.split(
463
+ split_to_interleaved(key_states),
464
+ split_size_or_sections=[self.rope_head_dim, self.head_dim - self.rope_head_dim],
465
+ dim=-1)
466
+
467
+ query_states, key_states = apply_rotary_pos_emb(
468
+ interleaved_to_split(query_states),
469
+ interleaved_to_split(key_states),
470
+ cos,
471
+ sin)
472
+
473
+ query_states = interleaved_to_split(torch.cat(
474
+ [split_to_interleaved(query_states), query_states_], dim=-1))
475
+ key_states = interleaved_to_split(torch.cat(
476
+ [split_to_interleaved(key_states), key_states_], dim=-1))
477
+
478
+ if past_key_values is not None:
479
+ cache_kwargs = {"cache_position": cache_position}
480
+ key_states, value_states = past_key_values.update(
481
+ key_states, value_states, self.layer_idx, cache_kwargs
482
+ )
483
+
484
+ attention_interface: Callable = eager_attention_forward
485
+ if self.config._attn_implementation != "eager":
486
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
487
+
488
+ attn_output, attn_weights = attention_interface(
489
+ self,
490
+ query_states,
491
+ key_states,
492
+ value_states,
493
+ attention_mask,
494
+ dropout=0.0 if not self.training else self.attention_dropout,
495
+ scaling=self.scaling,
496
+ sliding_window=self.sliding_window,
497
+ **kwargs,
498
+ )
499
+
500
+ if self.gate_func is not None:
501
+ gate = self.gate_proj(hidden_states).view(input_shape + (-1, self.head_dim))
502
+ if self.gate_func == 'silu':
503
+ gate = F.silu(gate)
504
+ else:
505
+ assert self.gate_func == 'softplus'
506
+ gate = F.softplus(gate, beta=math.log(2))
507
+
508
+ attn_output = attn_output * gate
509
+
510
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
511
+ attn_output = self.o_proj(attn_output)
512
+ return attn_output, attn_weights
513
+
514
+
515
+ class K2HorizonMLP(nn.Module):
516
+ def __init__(self, config, intermediate_size=None):
517
+ super().__init__()
518
+ self.config = config
519
+ self.hidden_size = config.hidden_size
520
+ self.intermediate_size = intermediate_size if intermediate_size is not None else config.intermediate_size
521
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
522
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
523
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
524
+ self.act_fn = ACT2FN[config.hidden_act]
525
+
526
+ def forward(self, x):
527
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
528
+ return down_proj
529
+
530
+
531
+ class K2HorizonSparseMoeBlock(nn.Module):
532
+ def __init__(self, config):
533
+ super().__init__()
534
+ self.num_experts = config.num_experts
535
+ self.top_k = config.num_experts_per_tok
536
+ self.norm_topk_prob = config.norm_topk_prob
537
+ self.num_shared_experts = config.num_shared_experts
538
+ self.router_score_func = config.router_score_func
539
+ self.router_scaling_factor = config.router_scaling_factor
540
+
541
+ # gating
542
+ self.gate = nn.Linear(config.hidden_size, config.num_experts, bias=config.moe_gate_bias)
543
+ self.experts = nn.ModuleList(
544
+ [K2HorizonMLP(config, intermediate_size=config.moe_intermediate_size) for _ in range(self.num_experts)]
545
+ )
546
+
547
+ if config.num_shared_experts > 0:
548
+ self.shared_experts = K2HorizonMLP(
549
+ config=config,
550
+ intermediate_size=config.moe_intermediate_size * config.num_shared_experts)
551
+
552
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
553
+ """ """
554
+ residuals = hidden_states
555
+
556
+ batch_size, sequence_length, hidden_dim = hidden_states.shape
557
+ hidden_states = hidden_states.view(-1, hidden_dim)
558
+ # router_logits: (batch * sequence_length, n_experts)
559
+ # router_logits = self.gate(hidden_states)
560
+ router_logits = F.linear(hidden_states, self.gate.weight)
561
+
562
+ if self.router_score_func == "softmax":
563
+ routing_weights = F.softmax(router_logits, dim=1, dtype=torch.float)
564
+ else:
565
+ assert self.router_score_func == "sigmoid"
566
+ routing_weights = F.sigmoid(router_logits.to(torch.float32))
567
+
568
+ routing_weights_for_choice = routing_weights
569
+ if self.gate.bias is not None:
570
+ routing_weights_for_choice = routing_weights + self.gate.bias.to(routing_weights.dtype)
571
+
572
+ _, selected_experts = torch.topk(routing_weights_for_choice, self.top_k, dim=-1)
573
+ routing_weights = torch.gather(routing_weights, dim=-1, index=selected_experts)
574
+
575
+ if self.norm_topk_prob: # only diff with mixtral sparse moe block!
576
+ routing_weights /= routing_weights.sum(dim=-1, keepdim=True)
577
+ routing_weights = routing_weights * self.router_scaling_factor
578
+ # we cast back to the input dtype
579
+ routing_weights = routing_weights.to(hidden_states.dtype)
580
+
581
+ final_hidden_states = torch.zeros(
582
+ (batch_size * sequence_length, hidden_dim), dtype=hidden_states.dtype, device=hidden_states.device
583
+ )
584
+
585
+ # One hot encode the selected experts to create an expert mask
586
+ # this will be used to easily index which expert is going to be sollicitated
587
+ expert_mask = torch.nn.functional.one_hot(selected_experts, num_classes=self.num_experts).permute(2, 1, 0)
588
+
589
+ # Loop over all available experts in the model and perform the computation on each expert
590
+ expert_hit = torch.greater(expert_mask.sum(dim=(-1, -2)), 0).nonzero()
591
+ for expert_idx in expert_hit:
592
+ expert_layer = self.experts[expert_idx]
593
+ idx, top_x = torch.where(expert_mask[expert_idx].squeeze(0))
594
+
595
+ # Index the correct hidden states and compute the expert hidden state for
596
+ # the current expert. We need to make sure to multiply the output hidden
597
+ # states by `routing_weights` on the corresponding tokens (top-1 and top-2)
598
+ current_state = hidden_states[None, top_x].reshape(-1, hidden_dim)
599
+ current_hidden_states = expert_layer(current_state) * routing_weights[top_x, idx, None]
600
+
601
+ # However `index_add_` only support torch tensors for indexing so we'll use
602
+ # the `top_x` tensor here.
603
+ final_hidden_states.index_add_(0, top_x, current_hidden_states.to(hidden_states.dtype))
604
+ final_hidden_states = final_hidden_states.reshape(batch_size, sequence_length, hidden_dim)
605
+
606
+ if self.num_shared_experts > 0:
607
+ final_hidden_states = final_hidden_states + self.shared_experts(residuals)
608
+
609
+ return final_hidden_states, router_logits
610
+
611
+
612
+ # @use_kernel_forward_from_hub("RMSNorm")
613
+ class K2HorizonRMSNorm(nn.Module):
614
+ def __init__(self, hidden_size: int, n_groups: int, eps=1e-6):
615
+ """
616
+ K2HorizonRMSNorm is equivalent to T5LayerNorm
617
+ """
618
+ super().__init__()
619
+ self.n_groups = n_groups
620
+ self.hidden_size = hidden_size
621
+ assert hidden_size % n_groups == 0
622
+ self.weight = nn.Parameter(torch.ones(hidden_size))
623
+ self.variance_epsilon = eps
624
+
625
+ def forward(self, hidden_states):
626
+ input_dtype = hidden_states.dtype
627
+ hidden_states = hidden_states.to(torch.float32)
628
+
629
+ hidden_states = hidden_states.reshape(*hidden_states.shape[:-1], self.n_groups, -1)
630
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
631
+
632
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
633
+ hidden_states = hidden_states.reshape(*hidden_states.shape[:-2], -1)
634
+ hidden_states = self.weight * hidden_states
635
+
636
+ return hidden_states.to(input_dtype)
637
+
638
+ def extra_repr(self):
639
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
640
+
641
+
642
+ class K2HorizonDecoderLayer(GradientCheckpointingLayer):
643
+ def __init__(self, config: K2HorizonConfig, layer_idx: int):
644
+ super().__init__()
645
+ self.hidden_size = config.hidden_size
646
+
647
+ is_sparse_layer = (layer_idx not in config.mlp_only_layers) and (
648
+ config.num_experts > 0 and (layer_idx + 1) % config.decoder_sparse_step == 0)
649
+
650
+ if is_sparse_layer and config.mova_num_experts > 0:
651
+ self.self_attn = K2HorizonMoVAAttention(config=config, layer_idx=layer_idx)
652
+ else:
653
+ self.self_attn = K2HorizonAttention(config, layer_idx)
654
+
655
+ if is_sparse_layer:
656
+ self.mlp = K2HorizonSparseMoeBlock(config)
657
+ else:
658
+ self.mlp = K2HorizonMLP(config, intermediate_size=config.intermediate_size)
659
+
660
+ assert config.hidden_size % config.layernorm_num_groups == 0
661
+ self.input_layernorm = K2HorizonRMSNorm(
662
+ hidden_size=config.hidden_size,
663
+ n_groups=config.layernorm_num_groups,
664
+ eps=config.rms_norm_eps)
665
+ self.post_attention_layernorm = K2HorizonRMSNorm(
666
+ hidden_size=config.hidden_size,
667
+ n_groups=config.layernorm_num_groups,
668
+ eps=config.rms_norm_eps)
669
+
670
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
671
+ def forward(
672
+ self,
673
+ hidden_states: torch.Tensor,
674
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
675
+ attention_mask: Optional[torch.Tensor] = None,
676
+ position_ids: Optional[torch.LongTensor] = None,
677
+ past_key_values: Optional[Cache] = None,
678
+ cache_position: Optional[torch.LongTensor] = None,
679
+ **kwargs: Unpack[FlashAttentionKwargs],
680
+ ) -> torch.FloatTensor:
681
+ """
682
+ Args:
683
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
684
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
685
+ `(batch, sequence_length)` where padding elements are indicated by 0.
686
+ output_attentions (`bool`, *optional*):
687
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
688
+ returned tensors for more detail.
689
+ output_router_logits (`bool`, *optional*):
690
+ Whether or not to return the logits of all the routers. They are useful for computing the router loss,
691
+ and should not be returned during inference.
692
+ use_cache (`bool`, *optional*):
693
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
694
+ (see `past_key_values`).
695
+ past_key_values (`Cache`, *optional*): cached past key and value projection states
696
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
697
+ Indices depicting the position of the input sequence tokens in the sequence.
698
+ position_embeddings (`tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
699
+ Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
700
+ with `head_dim` being the embedding dimension of each attention head.
701
+ kwargs (`dict`, *optional*):
702
+ Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
703
+ into the model
704
+ """
705
+ residual = hidden_states
706
+ hidden_states = self.input_layernorm(hidden_states)
707
+
708
+ # Self Attention
709
+ hidden_states, _ = self.self_attn(
710
+ hidden_states=hidden_states,
711
+ position_embeddings=position_embeddings,
712
+ attention_mask=attention_mask,
713
+ position_ids=position_ids,
714
+ past_key_values=past_key_values,
715
+ cache_position=cache_position,
716
+ **kwargs,
717
+ )
718
+
719
+ hidden_states = residual + hidden_states
720
+
721
+ # Fully Connected
722
+ residual = hidden_states
723
+ hidden_states = self.post_attention_layernorm(hidden_states)
724
+ hidden_states = self.mlp(hidden_states)
725
+ # For the MoE layers, we need to unpack
726
+ if isinstance(hidden_states, tuple):
727
+ hidden_states, _ = hidden_states
728
+ hidden_states = residual + hidden_states
729
+
730
+ return hidden_states
731
+
732
+
733
+ class K2HorizonRotaryEmbedding(nn.Module):
734
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
735
+
736
+ def __init__(self, config: K2HorizonConfig, device=None):
737
+ super().__init__()
738
+ self.max_seq_len_cached = config.max_position_embeddings
739
+ self.original_max_seq_len = config.max_position_embeddings
740
+
741
+ self.config = config
742
+
743
+ self.rope_type = self.config.rope_parameters["rope_type"]
744
+ rope_init_fn: Callable = self.compute_default_rope_parameters
745
+ if self.rope_type != "default":
746
+ rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
747
+ inv_freq, self.attention_scaling = rope_init_fn(self.config, device)
748
+
749
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
750
+ self.register_buffer("original_inv_freq", inv_freq.clone(), persistent=False)
751
+
752
+ @staticmethod
753
+ def compute_default_rope_parameters(
754
+ config: K2HorizonConfig | None = None,
755
+ device: Optional["torch.device"] = None,
756
+ seq_len: int | None = None,
757
+ ) -> tuple["torch.Tensor", float]:
758
+ """
759
+ Computes the inverse frequencies according to the original RoPE implementation
760
+ Args:
761
+ config ([`~transformers.PreTrainedConfig`]):
762
+ The model configuration.
763
+ device (`torch.device`):
764
+ The device to use for initialization of the inverse frequencies.
765
+ seq_len (`int`, *optional*):
766
+ The current sequence length. Unused for this type of RoPE.
767
+ Returns:
768
+ Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
769
+ post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
770
+ """
771
+ base = config.rope_parameters["rope_theta"]
772
+ # dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
773
+ dim = (
774
+ config.rope_head_dim
775
+ if config.rope_head_dim is not None
776
+ else getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
777
+ )
778
+
779
+ attention_factor = 1.0 # Unused in this type of RoPE
780
+
781
+ # Compute the inverse frequencies
782
+ inv_freq = 1.0 / (
783
+ base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
784
+ )
785
+ return inv_freq, attention_factor
786
+
787
+ @torch.no_grad()
788
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
789
+ def forward(self, x, position_ids):
790
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
791
+ position_ids_expanded = position_ids[:, None, :].float()
792
+
793
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
794
+ with maybe_autocast(device_type=device_type, enabled=False): # Force float32
795
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
796
+ emb = torch.cat((freqs, freqs), dim=-1)
797
+ cos = emb.cos() * self.attention_scaling
798
+ sin = emb.sin() * self.attention_scaling
799
+
800
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
801
+
802
+
803
+ @auto_docstring
804
+ class K2HorizonPreTrainedModel(PreTrainedModel):
805
+ config: K2HorizonConfig
806
+ base_model_prefix = "model"
807
+ supports_gradient_checkpointing = True
808
+ _no_split_modules = ["K2HorizonDecoderLayer"]
809
+ _skip_keys_device_placement = ["past_key_values"]
810
+ _supports_flash_attn = True
811
+ _supports_sdpa = True
812
+ _supports_flex_attn = True
813
+ _can_compile_fullgraph = False # MoE models don't work with torch.compile (`torch.where(condition)` not supported)
814
+ _supports_attention_backend = True
815
+ _can_record_outputs = {
816
+ "router_logits": OutputRecorder(K2HorizonSparseMoeBlock, index=1),
817
+ "hidden_states": K2HorizonDecoderLayer,
818
+ "attentions": K2HorizonAttention,
819
+ }
820
+
821
+
822
+ @auto_docstring
823
+ class K2HorizonModel(K2HorizonPreTrainedModel):
824
+ def __init__(self, config: K2HorizonConfig):
825
+ super().__init__(config)
826
+ # self.padding_idx = config.pad_token_id
827
+ self.padding_idx = getattr(config, "padding_idx", None)
828
+ self.vocab_size = config.vocab_size
829
+
830
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
831
+ self.layers = nn.ModuleList(
832
+ [K2HorizonDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
833
+ )
834
+
835
+ assert config.hidden_size % config.layernorm_num_groups == 0
836
+ self.norm = K2HorizonRMSNorm(
837
+ hidden_size=config.hidden_size,
838
+ n_groups=config.layernorm_num_groups,
839
+ eps=config.rms_norm_eps)
840
+
841
+ self.rotary_emb = K2HorizonRotaryEmbedding(config=config)
842
+ self.gradient_checkpointing = False
843
+
844
+ # Initialize weights and apply final processing
845
+ self.post_init()
846
+
847
+ @auto_docstring
848
+ def forward(
849
+ self,
850
+ input_ids: Optional[torch.LongTensor] = None,
851
+ attention_mask: Optional[torch.Tensor] = None,
852
+ position_ids: Optional[torch.LongTensor] = None,
853
+ past_key_values: Optional[Cache] = None,
854
+ inputs_embeds: Optional[torch.FloatTensor] = None,
855
+ use_cache: Optional[bool] = None,
856
+ cache_position: Optional[torch.LongTensor] = None,
857
+ **kwargs: Unpack[TransformersKwargs],
858
+ ) -> MoeModelOutputWithPast:
859
+ if (input_ids is None) ^ (inputs_embeds is not None):
860
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
861
+
862
+ if use_cache and past_key_values is None:
863
+ past_key_values = DynamicCache(config=self.config)
864
+
865
+ if inputs_embeds is None:
866
+ inputs_embeds = self.embed_tokens(input_ids)
867
+
868
+ if cache_position is None:
869
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
870
+ cache_position = torch.arange(
871
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
872
+ )
873
+ if position_ids is None:
874
+ position_ids = cache_position.unsqueeze(0)
875
+
876
+ mask_function = create_causal_mask if self.config.sliding_window is None else create_sliding_window_causal_mask
877
+ causal_mask = mask_function(
878
+ config=self.config,
879
+ inputs_embeds=inputs_embeds,
880
+ attention_mask=attention_mask,
881
+ past_key_values=past_key_values,
882
+ position_ids=position_ids,
883
+ )
884
+
885
+ hidden_states = inputs_embeds
886
+
887
+ # create position embeddings to be shared across the decoder layers
888
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
889
+
890
+ for layer_idx, decoder_layer in enumerate(self.layers[: self.config.num_hidden_layers]):
891
+ hidden_states = decoder_layer(
892
+ hidden_states,
893
+ position_embeddings=position_embeddings,
894
+ attention_mask=causal_mask,
895
+ position_ids=position_ids,
896
+ past_key_values=past_key_values,
897
+ use_cache=use_cache,
898
+ cache_position=cache_position,
899
+ **kwargs,
900
+ )
901
+
902
+ hidden_states = self.norm(hidden_states)
903
+
904
+ return MoeModelOutputWithPast( # only diff with Mistral is the output type, we need MoE
905
+ last_hidden_state=hidden_states,
906
+ past_key_values=past_key_values,
907
+ )
908
+
909
+
910
+ def load_balancing_loss_func(
911
+ gate_logits: Union[torch.Tensor, tuple[torch.Tensor], None],
912
+ num_experts: Optional[int] = None,
913
+ top_k=2,
914
+ attention_mask: Optional[torch.Tensor] = None,
915
+ ) -> Union[torch.Tensor, int]:
916
+ r"""
917
+ Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.
918
+
919
+ See Switch Transformer (https://huggingface.co/papers/2101.03961) for more details. This function implements the loss
920
+ function presented in equations (4) - (6) of the paper. It aims at penalizing cases where the routing between
921
+ experts is too unbalanced.
922
+
923
+ Args:
924
+ gate_logits:
925
+ Logits from the `gate`, should be a tuple of model.config.num_hidden_layers tensors of
926
+ shape [batch_size X sequence_length, num_experts].
927
+ num_experts:
928
+ Number of experts
929
+ top_k:
930
+ The number of experts to route per-token, can be also interpreted as the `top-k` routing
931
+ parameter.
932
+ attention_mask (`torch.Tensor`, *optional*):
933
+ The attention_mask used in forward function
934
+ shape [batch_size X sequence_length] if not None.
935
+
936
+ Returns:
937
+ The auxiliary loss.
938
+ """
939
+ if gate_logits is None or not isinstance(gate_logits, tuple):
940
+ return 0
941
+
942
+ if isinstance(gate_logits, tuple):
943
+ compute_device = gate_logits[0].device
944
+ concatenated_gate_logits = torch.cat([layer_gate.to(compute_device) for layer_gate in gate_logits], dim=0)
945
+
946
+ routing_weights = torch.nn.functional.softmax(concatenated_gate_logits, dim=-1)
947
+
948
+ _, selected_experts = torch.topk(routing_weights, top_k, dim=-1)
949
+
950
+ expert_mask = torch.nn.functional.one_hot(selected_experts, num_experts)
951
+
952
+ if attention_mask is None:
953
+ # Compute the percentage of tokens routed to each experts
954
+ tokens_per_expert = torch.mean(expert_mask.float(), dim=0)
955
+
956
+ # Compute the average probability of routing to these experts
957
+ router_prob_per_expert = torch.mean(routing_weights, dim=0)
958
+ else:
959
+ batch_size, sequence_length = attention_mask.shape
960
+ num_hidden_layers = concatenated_gate_logits.shape[0] // (batch_size * sequence_length)
961
+
962
+ # Compute the mask that masks all padding tokens as 0 with the same shape of expert_mask
963
+ expert_attention_mask = (
964
+ attention_mask[None, :, :, None, None]
965
+ .expand((num_hidden_layers, batch_size, sequence_length, top_k, num_experts))
966
+ .reshape(-1, top_k, num_experts)
967
+ .to(compute_device)
968
+ )
969
+
970
+ # Compute the percentage of tokens routed to each experts
971
+ tokens_per_expert = torch.sum(expert_mask.float() * expert_attention_mask, dim=0) / torch.sum(
972
+ expert_attention_mask, dim=0
973
+ )
974
+
975
+ # Compute the mask that masks all padding tokens as 0 with the same shape of tokens_per_expert
976
+ router_per_expert_attention_mask = (
977
+ attention_mask[None, :, :, None]
978
+ .expand((num_hidden_layers, batch_size, sequence_length, num_experts))
979
+ .reshape(-1, num_experts)
980
+ .to(compute_device)
981
+ )
982
+
983
+ # Compute the average probability of routing to these experts
984
+ router_prob_per_expert = torch.sum(routing_weights * router_per_expert_attention_mask, dim=0) / torch.sum(
985
+ router_per_expert_attention_mask, dim=0
986
+ )
987
+
988
+ overall_loss = torch.sum(tokens_per_expert * router_prob_per_expert.unsqueeze(0))
989
+ return overall_loss * num_experts
990
+
991
+
992
+ @auto_docstring
993
+ class K2HorizonForCausalLM(K2HorizonPreTrainedModel, GenerationMixin):
994
+ # _tied_weights_keys = ["lm_head.weight"]
995
+ # _tp_plan = {"lm_head": "colwise_rep"}
996
+ # _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
997
+
998
+ def __init__(self, config):
999
+ super().__init__(config)
1000
+ self.model = K2HorizonModel(config)
1001
+ self.vocab_size = config.vocab_size
1002
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1003
+ self.router_aux_loss_coef = config.router_aux_loss_coef
1004
+ self.num_experts = config.num_experts
1005
+ self.num_experts_per_tok = config.num_experts_per_tok
1006
+
1007
+ # Initialize weights and apply final processing
1008
+ self.post_init()
1009
+
1010
+ @can_return_tuple
1011
+ @auto_docstring
1012
+ def forward(
1013
+ self,
1014
+ input_ids: Optional[torch.LongTensor] = None,
1015
+ attention_mask: Optional[torch.Tensor] = None,
1016
+ position_ids: Optional[torch.LongTensor] = None,
1017
+ past_key_values: Optional[Cache] = None,
1018
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1019
+ labels: Optional[torch.LongTensor] = None,
1020
+ use_cache: Optional[bool] = None,
1021
+ output_router_logits: Optional[bool] = None,
1022
+ cache_position: Optional[torch.LongTensor] = None,
1023
+ logits_to_keep: Union[int, torch.Tensor] = 0,
1024
+ **kwargs: Unpack[TransformersKwargs],
1025
+ ) -> MoeCausalLMOutputWithPast:
1026
+ r"""
1027
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1028
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1029
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1030
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1031
+
1032
+ Example:
1033
+
1034
+ ```python
1035
+ >>> from transformers import AutoTokenizer, K2HorizonForCausalLM
1036
+
1037
+ >>> model = K2HorizonForCausalLM.from_pretrained("Qwen/Qwen3-MoE-15B-A2B")
1038
+ >>> tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3-MoE-15B-A2B")
1039
+
1040
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1041
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1042
+
1043
+ >>> # Generate
1044
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1045
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1046
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1047
+ ```"""
1048
+
1049
+ output_router_logits = (
1050
+ output_router_logits if output_router_logits is not None else self.config.output_router_logits
1051
+ )
1052
+
1053
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1054
+ outputs: MoeModelOutputWithPast = self.model(
1055
+ input_ids=input_ids,
1056
+ attention_mask=attention_mask,
1057
+ position_ids=position_ids,
1058
+ past_key_values=past_key_values,
1059
+ inputs_embeds=inputs_embeds,
1060
+ use_cache=use_cache,
1061
+ output_router_logits=output_router_logits,
1062
+ cache_position=cache_position,
1063
+ **kwargs,
1064
+ )
1065
+
1066
+ hidden_states = outputs.last_hidden_state
1067
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
1068
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
1069
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
1070
+
1071
+ loss = None
1072
+ if labels is not None:
1073
+ loss = self.loss_function(logits, labels, self.vocab_size, **kwargs)
1074
+
1075
+ aux_loss = None
1076
+ if output_router_logits:
1077
+ aux_loss = load_balancing_loss_func(
1078
+ outputs.router_logits,
1079
+ self.num_experts,
1080
+ self.num_experts_per_tok,
1081
+ attention_mask,
1082
+ )
1083
+ if labels is not None:
1084
+ loss += self.router_aux_loss_coef * aux_loss.to(loss.device) # make sure to reside in the same device
1085
+
1086
+ return MoeCausalLMOutputWithPast(
1087
+ loss=loss,
1088
+ aux_loss=aux_loss,
1089
+ logits=logits,
1090
+ past_key_values=outputs.past_key_values,
1091
+ hidden_states=outputs.hidden_states,
1092
+ attentions=outputs.attentions,
1093
+ router_logits=outputs.router_logits,
1094
+ )
1095
+
1096
+
1097
+ class K2HorizonForSequenceClassification(GenericForSequenceClassification, K2HorizonPreTrainedModel):
1098
+ pass
1099
+
1100
+
1101
+ class K2HorizonForTokenClassification(GenericForTokenClassification, K2HorizonPreTrainedModel):
1102
+ pass
1103
+
1104
+
1105
+ class K2HorizonForQuestionAnswering(GenericForQuestionAnswering, K2HorizonPreTrainedModel):
1106
+ base_model_prefix = "transformer" # For BC, where `transformer` was used instead of `model`
1107
+
1108
+
1109
+ __all__ = [
1110
+ "K2HorizonForCausalLM",
1111
+ "K2HorizonForQuestionAnswering",
1112
+ "K2HorizonModel",
1113
+ "K2HorizonPreTrainedModel",
1114
+ "K2HorizonForSequenceClassification",
1115
+ "K2HorizonForTokenClassification",
1116
+ ]
special_tokens_map.json ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {
2
+ "bos_token": "<|ifm|begin_of_text|>",
3
+ "eos_token": "<|ifm|endoftext|>"
4
+ }
tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:53d6dc22c1d38cb292e09784f7d40a7ec8706dc4532f3eed3f5fcdccd929f977
3
+ size 20637359
tokenizer_config.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "backend": "tokenizers",
3
+ "bos_token": "<|ifm|begin_of_text|>",
4
+ "clean_up_tokenization_spaces": false,
5
+ "eos_token": "<|ifm|endoftext|>",
6
+ "is_local": true,
7
+ "local_files_only": false,
8
+ "model_max_length": 1000000000000000019884624838656,
9
+ "tokenizer_class": "TokenizersBackend"
10
+ }