Skip to content

Get up and running with Kimi, GLM, MiniMax, DeepSeek, gpt-oss, Qwen, Gemma and other models.

mlx: implement Nemotron 3 Nano Omni (#17060)

Daniel Hiltgenbb7bba885e0c
diff --git a/model/parsers/nemotron3nano.go b/model/parsers/nemotron3nano.go
index e7e471e84..ac6033f64 100644
--- a/model/parsers/nemotron3nano.go
+++ b/model/parsers/nemotron3nano.go
@@ -143,10 +143,11 @@ func (p *Nemotron3NanoParser) emitThinking(bufStr string) string {
maxOverlap := max(thinkOverlap, toolOverlap)
if maxOverlap > 0 {
- unambiguous := bufStr[:len(bufStr)-maxOverlap]
- unambiguous = strings.TrimRightFunc(unambiguous, unicode.IsSpace)
+ beforePartialTag := bufStr[:len(bufStr)-maxOverlap]
+ ambiguousStart := len(beforePartialTag) - trailingWhitespaceLen(beforePartialTag)
+ unambiguous := bufStr[:ambiguousStart]
p.buffer.Reset()
- p.buffer.WriteString(bufStr[len(bufStr)-maxOverlap:])
+ p.buffer.WriteString(bufStr[ambiguousStart:])
return unambiguous
}
diff --git a/model/parsers/nemotron3nano_test.go b/model/parsers/nemotron3nano_test.go
index c52dd34cb..5232c0bcc 100644
--- a/model/parsers/nemotron3nano_test.go
+++ b/model/parsers/nemotron3nano_test.go
@@ -212,6 +212,27 @@ func TestNemotron3NanoParser_Streaming(t *testing.T) {
expectedThinking: "Think first",
expectedContent: "Done.",
},
+ {
+ name: "partial tool call tag fakeout while thinking preserves whitespace",
+ chunks: []string{"reasoning ending with ", "<tool_call", " fakeout", "</think>", "Done."},
+ thinkValue: &api.ThinkValue{Value: true},
+ expectedThinking: "reasoning ending with <tool_call fakeout",
+ expectedContent: "Done.",
+ },
+ {
+ name: "partial think close tag fakeout preserves whitespace",
+ chunks: []string{"reasoning ending with ", "</think", " fakeout", "</think>", "Done."},
+ thinkValue: &api.ThinkValue{Value: true},
+ expectedThinking: "reasoning ending with </think fakeout",
+ expectedContent: "Done.",
+ },
+ {
+ name: "leading partial think tag fakeout is thinking",
+ chunks: []string{"<th", "oughts are literal", "</think>", "Done."},
+ thinkValue: &api.ThinkValue{Value: true},
+ expectedThinking: "<thoughts are literal",
+ expectedContent: "Done.",
+ },
}
for _, tt := range tests {
diff --git a/model/renderers/nemotron3nano.go b/model/renderers/nemotron3nano.go
index eb4c939e2..be2cdc4cf 100644
--- a/model/renderers/nemotron3nano.go
+++ b/model/renderers/nemotron3nano.go
@@ -41,7 +41,6 @@ func (r *Nemotron3NanoRenderer) Render(messages []api.Message, tools []api.Tool,
}
}
- sb.WriteString("\n\n\n")
sb.WriteString("<|im_start|>system\n")
if systemMessage != "" {
sb.WriteString(systemMessage)
@@ -53,7 +52,7 @@ func (r *Nemotron3NanoRenderer) Render(messages []api.Message, tools []api.Tool,
}
sb.WriteString(r.renderTools(tools))
}
- sb.WriteString("<|im_end|>\n\n")
+ sb.WriteString("<|im_end|>\n")
for i, message := range loopMessages {
switch message.Role {
@@ -75,7 +74,9 @@ func (r *Nemotron3NanoRenderer) Render(messages []api.Message, tools []api.Tool,
case "user", "system":
sb.WriteString("<|im_start|>" + message.Role + "\n")
- sb.WriteString(r.renderMessageContent(message, imageOffset))
+ // The template strips toggle text from user and system turns
+ // alike, keeping any real closing tag intact.
+ sb.WriteString(strings.TrimSpace(stripThinkToggles(r.renderMessageContent(message, imageOffset))))
imageOffset += len(message.Images)
sb.WriteString("<|im_end|>\n")
@@ -86,7 +87,8 @@ func (r *Nemotron3NanoRenderer) Render(messages []api.Message, tools []api.Tool,
content := r.renderMessageContent(message, imageOffset)
imageOffset += len(message.Images)
- if !prevWasTool {
+ // A tool message with nothing before it opens no user block.
+ if i > 0 && !prevWasTool {
sb.WriteString("<|im_start|>user\n")
}
sb.WriteString("<tool_response>\n")
@@ -102,8 +104,6 @@ func (r *Nemotron3NanoRenderer) Render(messages []api.Message, tools []api.Tool,
}
}
- sb.WriteString("\n")
-
// Add generation prompt
if enableThinking {
sb.WriteString("<|im_start|>assistant\n<think>\n")
@@ -229,12 +229,35 @@ func (r *Nemotron3NanoRenderer) writeToolCalls(sb *strings.Builder, toolCalls []
}
func (r *Nemotron3NanoRenderer) formatArgValue(value any) string {
- switch v := value.(type) {
- case map[string]any, []any:
- return r.pythonJSON(v)
- default:
- return fmt.Sprintf("%v", v)
+ return r.templateValue(value)
+}
+
+// templateValue prints a value the way the template does: JSON for mappings
+// and non-string sequences, Python's str() otherwise, so scalars render True,
+// False and None. Container-ness comes from the marshaled form because callers
+// may pass schema types rather than plain maps and slices.
+func (r *Nemotron3NanoRenderer) templateValue(value any) string {
+ if value == nil {
+ return "None"
+ }
+
+ b, err := json.Marshal(value)
+ if err != nil {
+ return "None"
}
+ if len(b) > 0 && (b[0] == '{' || b[0] == '[') {
+ return r.pythonJSON(value)
+ }
+
+ switch string(b) {
+ case "null":
+ return "None"
+ case "true":
+ return "True"
+ case "false":
+ return "False"
+ }
+ return fmt.Sprintf("%v", value)
}
func (r *Nemotron3NanoRenderer) renderMessageContent(message api.Message, imageOffset int) string {
@@ -297,12 +320,17 @@ func (r *Nemotron3NanoRenderer) resolveThinking(messages []api.Message, thinkVal
}
func (r *Nemotron3NanoRenderer) sanitizeSystemMessage(content string) string {
- system := nemotron3NanoRenderContent(content)
- system = strings.ReplaceAll(system, "</think>", "<_end_think>")
- system = strings.ReplaceAll(system, "/think", "")
- system = strings.ReplaceAll(system, "/no_think", "")
- system = strings.ReplaceAll(system, "<_end_think>", "</think>")
- return system
+ return stripThinkToggles(nemotron3NanoRenderContent(content))
+}
+
+// stripThinkToggles removes the inline /think and /no_think markers the
+// template deletes once they have been read, while preserving a genuine
+// </think> tag that would otherwise be caught by the /think match.
+func stripThinkToggles(s string) string {
+ s = strings.ReplaceAll(s, "</think>", "<_end_think>")
+ s = strings.ReplaceAll(s, "/think", "")
+ s = strings.ReplaceAll(s, "/no_think", "")
+ return strings.ReplaceAll(s, "<_end_think>", "</think>")
}
func (r *Nemotron3NanoRenderer) formatPropertyType(propertyType api.PropertyType) string {
@@ -333,10 +361,10 @@ func (r *Nemotron3NanoRenderer) renderToolPropertyExtraKeys(sb *strings.Builder,
func (r *Nemotron3NanoRenderer) renderToolParameterExtraKeys(sb *strings.Builder, params api.ToolFunctionParameters) {
if params.Defs != nil {
- sb.WriteString("\n<$defs>" + r.pythonJSON(params.Defs) + "</$defs>")
+ sb.WriteString("\n<$defs>" + r.templateValue(params.Defs) + "</$defs>")
}
if params.Items != nil {
- sb.WriteString("\n<items>" + r.pythonJSON(params.Items) + "</items>")
+ sb.WriteString("\n<items>" + r.templateValue(params.Items) + "</items>")
}
}
diff --git a/model/renderers/nemotron3nano_reference_test.go b/model/renderers/nemotron3nano_reference_test.go
index 8a39f0c4d..17c2b6b70 100644
--- a/model/renderers/nemotron3nano_reference_test.go
+++ b/model/renderers/nemotron3nano_reference_test.go
@@ -16,151 +16,25 @@ import (
const nemotron3NanoTemplate = "testdata/nemotron3nano_chat_template.jinja2"
-func TestNemotron3NanoRendererMatchesReference(t *testing.T) {
- toolText := `<|im_start|>system
-# Tools
-
-You have access to the following functions:
-
-<tools>
-<function>
-<name>search_docs</name>
-<description>Search docs</description>
-<parameters>
-<parameter>
-<name>query</name>
-<type>string</type>
-<description>Search query</description>
-<enum>["api", "cli"]</enum>
-</parameter>
-<parameter>
-<name>mode</name>
-<type>['string', 'null']</type>
-<description>Mode</description>
-<anyOf>[{"type": "string"}, {"type": "number"}]</anyOf>
-</parameter>
-<parameter>
-<name>payload</name>
-<type>object</type>
-<description>Payload</description>
-<properties>{"enabled": {"type": "boolean"}}</properties>
-<required>["enabled"]</required>
-</parameter>
-<parameter>
-<name>tags</name>
-<type>array</type>
-<description>Tags</description>
-<items>{"type": "string"}</items>
-</parameter>
-<$defs>{"shared": {"type": "string"}}</$defs>
-<required>["query"]</required>
-</parameters>
-</function>
-</tools>
-
-If you choose to call a function ONLY reply in the following format with NO suffix:
-
-<tool_call>
-<function=example_function_name>
-<parameter=example_parameter_1>
-value_1
-</parameter>
-<parameter=example_parameter_2>
-This is the value for the second parameter
-that can span
-multiple lines
-</parameter>
-</function>
-</tool_call>
-
-<IMPORTANT>
-Reminder:
-- Function calls MUST follow the specified format: an inner <function=...></function> block must be nested within <tool_call></tool_call> XML tags
-- Required parameters MUST be specified
-- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after
-- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls
-</IMPORTANT><|im_end|>
-`
- toolTextWithSystem := `<|im_start|>system
-Follow policy.
-
-# Tools
-
-You have access to the following functions:
-
-<tools>
-<function>
-<name>search_docs</name>
-<description>Search docs</description>
-<parameters>
-<parameter>
-<name>query</name>
-<type>string</type>
-<description>Search query</description>
-<enum>["api", "cli"]</enum>
-</parameter>
-<parameter>
-<name>mode</name>
-<type>['string', 'null']</type>
-<description>Mode</description>
-<anyOf>[{"type": "string"}, {"type": "number"}]</anyOf>
-</parameter>
-<parameter>
-<name>payload</name>
-<type>object</type>
-<description>Payload</description>
-<properties>{"enabled": {"type": "boolean"}}</properties>
-<required>["enabled"]</required>
-</parameter>
-<parameter>
-<name>tags</name>
-<type>array</type>
-<description>Tags</description>
-<items>{"type": "string"}</items>
-</parameter>
-<$defs>{"shared": {"type": "string"}}</$defs>
-<required>["query"]</required>
-</parameters>
-</function>
-</tools>
-
-If you choose to call a function ONLY reply in the following format with NO suffix:
-
-<tool_call>
-<function=example_function_name>
-<parameter=example_parameter_1>
-value_1
-</parameter>
-<parameter=example_parameter_2>
-This is the value for the second parameter
-that can span
-multiple lines
-</parameter>
-</function>
-</tool_call>
-
-<IMPORTANT>
-Reminder:
-- Function calls MUST follow the specified format: an inner <function=...></function> block must be nested within <tool_call></tool_call> XML tags
-- Required parameters MUST be specified
-- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after
-- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls
-</IMPORTANT><|im_end|>
-`
+// nemotronReferenceCase is one reference conversation. The same inputs drive
+// every Nemotron flavor's parity test; only the template and the frozen
+// expectations differ.
+type nemotronReferenceCase struct {
+ name string
+ messages []api.Message
+ tools []api.Tool
+ think *api.ThinkValue
+ expected string
+}
- tests := []struct {
- name string
- messages []api.Message
- tools []api.Tool
- think *api.ThinkValue
- expected string
- }{
+func nemotronReferenceCases() []nemotronReferenceCase {
+ return []nemotronReferenceCase{
{
name: "no system default thinking on",
messages: []api.Message{
{Role: "user", Content: "Hello"},
},
- expected: "\n\n\n<|im_start|>system\n<|im_end|>\n\n<|im_start|>user\nHello<|im_end|>\n\n<|im_start|>assistant\n<think>\n",
+ expected: "<|im_start|>system\n<|im_end|>\n<|im_start|>user\nHello<|im_end|>\n<|im_start|>assistant\n<think>\n",
},
{
name: "no system explicit thinking off",
@@ -168,7 +42,7 @@ Reminder:
{Role: "user", Content: "Hello"},
},
think: thinkFalse(),
- expected: "\n\n\n<|im_start|>system\n<|im_end|>\n\n<|im_start|>user\nHello<|im_end|>\n\n<|im_start|>assistant\n<think></think>",
+ expected: "<|im_start|>system\n<|im_end|>\n<|im_start|>user\nHello<|im_end|>\n<|im_start|>assistant\n<think></think>",
},
{
name: "literal endthink does not enable thinking",
@@ -176,7 +50,7 @@ Reminder:
{Role: "user", Content: "literal </think> only"},
},
think: thinkFalse(),
- expected: "\n\n\n<|im_start|>system\n<|im_end|>\n\n<|im_start|>user\nliteral </think> only<|im_end|>\n\n<|im_start|>assistant\n<think></think>",
+ expected: "<|im_start|>system\n<|im_end|>\n<|im_start|>user\nliteral </think> only<|im_end|>\n<|im_start|>assistant\n<think></think>",
},
{
name: "user no think toggle",
@@ -184,7 +58,7 @@ Reminder:
{Role: "user", Content: "Hello /no_think"},
},
think: thinkTrue(),
- expected: "\n\n\n<|im_start|>system\n<|im_end|>\n\n<|im_start|>user\nHello /no_think<|im_end|>\n\n<|im_start|>assistant\n<think></think>",
+ expected: "<|im_start|>system\n<|im_end|>\n<|im_start|>user\nHello<|im_end|>\n<|im_start|>assistant\n<think></think>",
},
{
name: "system think toggle overrides false",
@@ -193,7 +67,7 @@ Reminder:
{Role: "user", Content: "Hello"},
},
think: thinkFalse(),
- expected: "\n\n\n<|im_start|>system\nPolicy <|im_end|>\n\n<|im_start|>user\nHello<|im_end|>\n\n<|im_start|>assistant\n<think>\n",
+ expected: "<|im_start|>system\nPolicy <|im_end|>\n<|im_start|>user\nHello<|im_end|>\n<|im_start|>assistant\n<think>\n",
},
{
name: "later toggle wins",
@@ -202,7 +76,7 @@ Reminder:
{Role: "user", Content: "Actually /think"},
},
think: thinkFalse(),
- expected: "\n\n\n<|im_start|>system\nPolicy <|im_end|>\n\n<|im_start|>user\nActually /think<|im_end|>\n\n<|im_start|>assistant\n<think>\n",
+ expected: "<|im_start|>system\nPolicy <|im_end|>\n<|im_start|>user\nActually<|im_end|>\n<|im_start|>assistant\n<think>\n",
},
{
name: "system sanitizes toggles but preserves closing tag",
@@ -211,7 +85,7 @@ Reminder:
{Role: "user", Content: "Hello"},
},
think: thinkFalse(),
- expected: "\n\n\n<|im_start|>system\nA B C </think><|im_end|>\n\n<|im_start|>user\nHello<|im_end|>\n\n<|im_start|>assistant\n<think>\n",
+ expected: "<|im_start|>system\nA B C </think><|im_end|>\n<|im_start|>user\nHello<|im_end|>\n<|im_start|>assistant\n<think>\n",
},
{
name: "assistant plain content adds empty think block",
@@ -220,7 +94,7 @@ Reminder:
{Role: "assistant", Content: "Hello there"},
},
think: thinkTrue(),
- expected: "\n\n\n<|im_start|>system\n<|im_end|>\n\n<|im_start|>user\nHi<|im_end|>\n<|im_start|>assistant\n<think></think>Hello there<|im_end|>\n\n<|im_start|>assistant\n<think>\n",
+ expected: "<|im_start|>system\n<|im_end|>\n<|im_start|>user\nHi<|im_end|>\n<|im_start|>assistant\n<think></think>Hello there<|im_end|>\n<|im_start|>assistant\n<think>\n",
},
{
name: "assistant reasoning content",
@@ -229,7 +103,7 @@ Reminder:
{Role: "assistant", Content: "Answer", Thinking: "Need to think"},
},
think: thinkTrue(),
- expected: "\n\n\n<|im_start|>system\n<|im_end|>\n\n<|im_start|>user\nHi<|im_end|>\n<|im_start|>assistant\n<think>\nNeed to think\n</think>\nAnswer<|im_end|>\n\n<|im_start|>assistant\n<think>\n",
+ expected: "<|im_start|>system\n<|im_end|>\n<|im_start|>user\nHi<|im_end|>\n<|im_start|>assistant\n<think>\nNeed to think\n</think>\nAnswer<|im_end|>\n<|im_start|>assistant\n<think>\n",
},
{
name: "assistant preserves existing think tags",
@@ -238,7 +112,7 @@ Reminder:
{Role: "assistant", Content: "<think>kept</think>Answer"},
},
think: thinkTrue(),
- expected: "\n\n\n<|im_start|>system\n<|im_end|>\n\n<|im_start|>user\nHi<|im_end|>\n<|im_start|>assistant\n<think>kept</think>Answer<|im_end|>\n\n<|im_start|>assistant\n<think>\n",
+ expected: "<|im_start|>system\n<|im_end|>\n<|im_start|>user\nHi<|im_end|>\n<|im_start|>assistant\n<think>kept</think>Answer<|im_end|>\n<|im_start|>assistant\n<think>\n",
},
{
name: "tools without system",
@@ -247,7 +121,7 @@ Reminder:
},
tools: nemotron3NanoReferenceTools(),
think: thinkTrue(),
- expected: "\n\n\n" + toolText + "\n<|im_start|>user\nUse a tool<|im_end|>\n\n<|im_start|>assistant\n<think>\n",
+ expected: "<|im_start|>system\n# Tools\n\nYou have access to the following functions:\n\n<tools>\n<function>\n<name>search_docs</name>\n<description>Search docs</description>\n<parameters>\n<parameter>\n<name>query</name>\n<type>string</type>\n<description>Search query</description>\n<enum>[\"api\", \"cli\"]</enum>\n</parameter>\n<parameter>\n<name>mode</name>\n<type>['string', 'null']</type>\n<description>Mode</description>\n<anyOf>[{\"type\": \"string\"}, {\"type\": \"number\"}]</anyOf>\n</parameter>\n<parameter>\n<name>payload</name>\n<type>object</type>\n<description>Payload</description>\n<properties>{\"enabled\": {\"type\": \"boolean\"}}</properties>\n<required>[\"enabled\"]</required>\n</parameter>\n<parameter>\n<name>tags</name>\n<type>array</type>\n<description>Tags</description>\n<items>{\"type\": \"string\"}</items>\n</parameter>\n<$defs>{\"shared\": {\"type\": \"string\"}}</$defs>\n<required>[\"query\"]</required>\n</parameters>\n</function>\n</tools>\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n<tool_call>\n<function=example_function_name>\n<parameter=example_parameter_1>\nvalue_1\n</parameter>\n<parameter=example_parameter_2>\nThis is the value for the second parameter\nthat can span\nmultiple lines\n</parameter>\n</function>\n</tool_call>\n\n<IMPORTANT>\nReminder:\n- Function calls MUST follow the specified format: an inner <function=...></function> block must be nested within <tool_call></tool_call> XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n</IMPORTANT><|im_end|>\n<|im_start|>user\nUse a tool<|im_end|>\n<|im_start|>assistant\n<think>\n",
},
{
name: "system with tools",
@@ -257,7 +131,7 @@ Reminder:
},
tools: nemotron3NanoReferenceTools(),
think: thinkTrue(),
- expected: "\n\n\n" + toolTextWithSystem + "\n<|im_start|>user\nUse a tool<|im_end|>\n\n<|im_start|>assistant\n<think>\n",
+ expected: "<|im_start|>system\nFollow policy.\n\n# Tools\n\nYou have access to the following functions:\n\n<tools>\n<function>\n<name>search_docs</name>\n<description>Search docs</description>\n<parameters>\n<parameter>\n<name>query</name>\n<type>string</type>\n<description>Search query</description>\n<enum>[\"api\", \"cli\"]</enum>\n</parameter>\n<parameter>\n<name>mode</name>\n<type>['string', 'null']</type>\n<description>Mode</description>\n<anyOf>[{\"type\": \"string\"}, {\"type\": \"number\"}]</anyOf>\n</parameter>\n<parameter>\n<name>payload</name>\n<type>object</type>\n<description>Payload</description>\n<properties>{\"enabled\": {\"type\": \"boolean\"}}</properties>\n<required>[\"enabled\"]</required>\n</parameter>\n<parameter>\n<name>tags</name>\n<type>array</type>\n<description>Tags</description>\n<items>{\"type\": \"string\"}</items>\n</parameter>\n<$defs>{\"shared\": {\"type\": \"string\"}}</$defs>\n<required>[\"query\"]</required>\n</parameters>\n</function>\n</tools>\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n<tool_call>\n<function=example_function_name>\n<parameter=example_parameter_1>\nvalue_1\n</parameter>\n<parameter=example_parameter_2>\nThis is the value for the second parameter\nthat can span\nmultiple lines\n</parameter>\n</function>\n</tool_call>\n\n<IMPORTANT>\nReminder:\n- Function calls MUST follow the specified format: an inner <function=...></function> block must be nested within <tool_call></tool_call> XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n</IMPORTANT><|im_end|>\n<|im_start|>user\nUse a tool<|im_end|>\n<|im_start|>assistant\n<think>\n",
},
{
name: "assistant tool call with content",
@@ -275,7 +149,7 @@ Reminder:
},
},
think: thinkTrue(),
- expected: "\n\n\n<|im_start|>system\n<|im_end|>\n\n<|im_start|>user\nWeather?<|im_end|>\n<|im_start|>assistant\n<think></think>Checking now.\n<tool_call>\n<function=get_weather>\n<parameter=city>\nParis\n</parameter>\n</function>\n</tool_call>\n<|im_end|>\n\n<|im_start|>assistant\n<think>\n",
+ expected: "<|im_start|>system\n<|im_end|>\n<|im_start|>user\nWeather?<|im_end|>\n<|im_start|>assistant\n<think></think>Checking now.\n<tool_call>\n<function=get_weather>\n<parameter=city>\nParis\n</parameter>\n</function>\n</tool_call>\n<|im_end|>\n<|im_start|>assistant\n<think>\n",
},
{
name: "assistant tool call with structured arguments",
@@ -295,7 +169,7 @@ Reminder:
},
},
think: thinkTrue(),
- expected: "\n\n\n<|im_start|>system\n<|im_end|>\n\n<|im_start|>user\nCreate data<|im_end|>\n<|im_start|>assistant\n<think></think>\n<tool_call>\n<function=create>\n<parameter=payload>\n{\"count\": 42, \"nested\": {\"value\": \"ok\"}}\n</parameter>\n<parameter=tags>\n[\"a\", \"b\"]\n</parameter>\n</function>\n</tool_call>\n<|im_end|>\n\n<|im_start|>assistant\n<think>\n",
+ expected: "<|im_start|>system\n<|im_end|>\n<|im_start|>user\nCreate data<|im_end|>\n<|im_start|>assistant\n<think></think>\n<tool_call>\n<function=create>\n<parameter=payload>\n{\"count\": 42, \"nested\": {\"value\": \"ok\"}}\n</parameter>\n<parameter=tags>\n[\"a\", \"b\"]\n</parameter>\n</function>\n</tool_call>\n<|im_end|>\n<|im_start|>assistant\n<think>\n",
},
{
name: "assistant tool call truncated with reasoning",
@@ -315,7 +189,7 @@ Reminder:
{Role: "user", Content: "And tomorrow?"},
},
think: thinkTrue(),
- expected: "\n\n\n<|im_start|>system\n<|im_end|>\n\n<|im_start|>user\nWeather?<|im_end|>\n<|im_start|>assistant\n<think></think>Checking now.\n<tool_call>\n<function=get_weather>\n<parameter=city>\nParis\n</parameter>\n</function>\n</tool_call>\n<|im_end|>\n<|im_start|>user\nAnd tomorrow?<|im_end|>\n\n<|im_start|>assistant\n<think>\n",
+ expected: "<|im_start|>system\n<|im_end|>\n<|im_start|>user\nWeather?<|im_end|>\n<|im_start|>assistant\n<think></think>Checking now.\n<tool_call>\n<function=get_weather>\n<parameter=city>\nParis\n</parameter>\n</function>\n</tool_call>\n<|im_end|>\n<|im_start|>user\nAnd tomorrow?<|im_end|>\n<|im_start|>assistant\n<think>\n",
},
{
name: "assistant tool call truncated open think only",
@@ -334,7 +208,7 @@ Reminder:
{Role: "user", Content: "And tomorrow?"},
},
think: thinkTrue(),
- expected: "\n\n\n<|im_start|>system\n<|im_end|>\n\n<|im_start|>user\nWeather?<|im_end|>\n<|im_start|>assistant\n<think></think>\n<tool_call>\n<function=get_weather>\n<parameter=city>\nParis\n</parameter>\n</function>\n</tool_call>\n<|im_end|>\n<|im_start|>user\nAnd tomorrow?<|im_end|>\n\n<|im_start|>assistant\n<think>\n",
+ expected: "<|im_start|>system\n<|im_end|>\n<|im_start|>user\nWeather?<|im_end|>\n<|im_start|>assistant\n<think></think>\n<tool_call>\n<function=get_weather>\n<parameter=city>\nParis\n</parameter>\n</function>\n</tool_call>\n<|im_end|>\n<|im_start|>user\nAnd tomorrow?<|im_end|>\n<|im_start|>assistant\n<think>\n",
},
{
name: "assistant tool call empty content",
@@ -352,7 +226,7 @@ Reminder:
},
},
think: thinkTrue(),
- expected: "\n\n\n<|im_start|>system\n<|im_end|>\n\n<|im_start|>user\nWeather?<|im_end|>\n<|im_start|>assistant\n<think></think>\n<tool_call>\n<function=get_weather>\n<parameter=city>\nParis\n</parameter>\n</function>\n</tool_call>\n<|im_end|>\n\n<|im_start|>assistant\n<think>\n",
+ expected: "<|im_start|>system\n<|im_end|>\n<|im_start|>user\nWeather?<|im_end|>\n<|im_start|>assistant\n<think></think>\n<tool_call>\n<function=get_weather>\n<parameter=city>\nParis\n</parameter>\n</function>\n</tool_call>\n<|im_end|>\n<|im_start|>assistant\n<think>\n",
},
{
name: "assistant truncated with think pair",
@@ -362,7 +236,7 @@ Reminder:
{Role: "user", Content: "Next"},
},
think: thinkTrue(),
- expected: "\n\n\n<|im_start|>system\n<|im_end|>\n\n<|im_start|>user\nHi<|im_end|>\n<|im_start|>assistant\n<think></think>Visible<|im_end|>\n<|im_start|>user\nNext<|im_end|>\n\n<|im_start|>assistant\n<think>\n",
+ expected: "<|im_start|>system\n<|im_end|>\n<|im_start|>user\nHi<|im_end|>\n<|im_start|>assistant\n<think></think>Visible<|im_end|>\n<|im_start|>user\nNext<|im_end|>\n<|im_start|>assistant\n<think>\n",
},
{
name: "assistant truncated reasoning content",
@@ -372,7 +246,7 @@ Reminder:
{Role: "user", Content: "Next"},
},
think: thinkTrue(),
- expected: "\n\n\n<|im_start|>system\n<|im_end|>\n\n<|im_start|>user\nHi<|im_end|>\n<|im_start|>assistant\n<think></think>\nVisible<|im_end|>\n<|im_start|>user\nNext<|im_end|>\n\n<|im_start|>assistant\n<think>\n",
+ expected: "<|im_start|>system\n<|im_end|>\n<|im_start|>user\nHi<|im_end|>\n<|im_start|>assistant\n<think></think>\nVisible<|im_end|>\n<|im_start|>user\nNext<|im_end|>\n<|im_start|>assistant\n<think>\n",
},
{
name: "assistant truncated plain content",
@@ -382,7 +256,7 @@ Reminder:
{Role: "user", Content: "Next"},
},
think: thinkTrue(),
- expected: "\n\n\n<|im_start|>system\n<|im_end|>\n\n<|im_start|>user\nHi<|im_end|>\n<|im_start|>assistant\n<think></think>Visible<|im_end|>\n<|im_start|>user\nNext<|im_end|>\n\n<|im_start|>assistant\n<think>\n",
+ expected: "<|im_start|>system\n<|im_end|>\n<|im_start|>user\nHi<|im_end|>\n<|im_start|>assistant\n<think></think>Visible<|im_end|>\n<|im_start|>user\nNext<|im_end|>\n<|im_start|>assistant\n<think>\n",
},
{
name: "assistant truncated empty content",
@@ -392,7 +266,7 @@ Reminder:
{Role: "user", Content: "Next"},
},
think: thinkTrue(),
- expected: "\n\n\n<|im_start|>system\n<|im_end|>\n\n<|im_start|>user\nHi<|im_end|>\n<|im_start|>assistant\n<think></think><|im_end|>\n<|im_start|>user\nNext<|im_end|>\n\n<|im_start|>assistant\n<think>\n",
+ expected: "<|im_start|>system\n<|im_end|>\n<|im_start|>user\nHi<|im_end|>\n<|im_start|>assistant\n<think></think><|im_end|>\n<|im_start|>user\nNext<|im_end|>\n<|im_start|>assistant\n<think>\n",
},
{
name: "consecutive tool messages grouped",
@@ -411,7 +285,7 @@ Reminder:
{Role: "tool", Content: "two"},
},
think: thinkTrue(),
- expected: "\n\n\n<|im_start|>system\n<|im_end|>\n\n<|im_start|>user\nDo work<|im_end|>\n<|im_start|>assistant\n<think></think>\n<tool_call>\n<function=step>\n<parameter=value>\n1\n</parameter>\n</function>\n</tool_call>\n<|im_end|>\n<|im_start|>user\n<tool_response>\none\n</tool_response>\n<tool_response>\ntwo\n</tool_response>\n<|im_end|>\n\n<|im_start|>assistant\n<think>\n",
+ expected: "<|im_start|>system\n<|im_end|>\n<|im_start|>user\nDo work<|im_end|>\n<|im_start|>assistant\n<think></think>\n<tool_call>\n<function=step>\n<parameter=value>\n1\n</parameter>\n</function>\n</tool_call>\n<|im_end|>\n<|im_start|>user\n<tool_response>\none\n</tool_response>\n<tool_response>\ntwo\n</tool_response>\n<|im_end|>\n<|im_start|>assistant\n<think>\n",
},
{
name: "fallback role",
@@ -419,9 +293,13 @@ Reminder:
{Role: "developer", Content: "Custom role content"},
},
think: thinkTrue(),
- expected: "\n\n\n<|im_start|>system\n<|im_end|>\n\n<|im_start|>developer\nCustom role content<|im_end|>\n\n<|im_start|>assistant\n<think>\n",
+ expected: "<|im_start|>system\n<|im_end|>\n<|im_start|>developer\nCustom role content<|im_end|>\n<|im_start|>assistant\n<think>\n",
},
}
+}
+
+func TestNemotron3NanoRendererMatchesReference(t *testing.T) {
+ tests := nemotronReferenceCases()
verifyJinja2 := os.Getenv("VERIFY_JINJA2") != ""
if verifyJinja2 {
@@ -506,6 +384,13 @@ func nemotron3NanoReferenceTools() []api.Tool {
}
func renderNemotron3NanoWithJinja2(t *testing.T, messages []api.Message, tools []api.Tool, think *api.ThinkValue) string {
+ return renderNemotronWithJinja2(t, nemotron3NanoTemplate, messages, tools, think)
+}
+
+// renderNemotronWithJinja2 renders through the real jinja engine using the
+// named testdata template, so each Nemotron flavor is checked against the
+// template its checkpoint ships.
+func renderNemotronWithJinja2(t *testing.T, templateRel string, messages []api.Message, tools []api.Tool, think *api.ThinkValue) string {
t.Helper()
type jinja2ToolCall struct {
@@ -536,12 +421,15 @@ func renderNemotron3NanoWithJinja2(t *testing.T, messages []api.Message, tools [
for _, tc := range m.ToolCalls {
jtc := jinja2ToolCall{ID: tc.ID}
jtc.Function.Name = tc.Function.Name
- var args map[string]any
- raw, _ := tc.Function.Arguments.MarshalJSON()
- if err := json.Unmarshal(raw, &args); err != nil {
- t.Fatalf("failed to unmarshal tool args: %v", err)
+ // Pass the arguments through as raw JSON. Decoding into a Go map
+ // would drop their order, and re-marshaling would re-emit them
+ // sorted -- the template renders one <parameter=...> per key in
+ // order, so that silently changes the reference.
+ raw, err := tc.Function.Arguments.MarshalJSON()
+ if err != nil {
+ t.Fatalf("failed to marshal tool args: %v", err)
}
- jtc.Function.Arguments = args
+ jtc.Function.Arguments = json.RawMessage(raw)
jm.ToolCalls = append(jm.ToolCalls, jtc)
}
jMsgs = append(jMsgs, jm)
@@ -571,7 +459,7 @@ func renderNemotron3NanoWithJinja2(t *testing.T, messages []api.Message, tools [
}
repoRoot := nemotron3NanoRepoRoot(t)
- templatePath := filepath.Join(repoRoot, "model", "renderers", nemotron3NanoTemplate)
+ templatePath := filepath.Join(repoRoot, "model", "renderers", templateRel)
pythonPath := filepath.Join(repoRoot, ".venv", "bin", "python3")
script := `
import json
@@ -594,7 +482,7 @@ elif thinking == "false":
print(tmpl.render(**kwargs), end="")
`
- cmd := exec.Command(pythonPath, "-c", script, templatePath, string(msgsJSON), toolsJSON, thinking)
+ cmd := exec.CommandContext(t.Context(), pythonPath, "-c", script, templatePath, string(msgsJSON), toolsJSON, thinking)
var stdout, stderr strings.Builder
cmd.Stdout = &stdout
cmd.Stderr = &stderr
diff --git a/model/renderers/nemotron3nano_test.go b/model/renderers/nemotron3nano_test.go
index 79daf8c68..08a64f769 100644
--- a/model/renderers/nemotron3nano_test.go
+++ b/model/renderers/nemotron3nano_test.go
@@ -19,14 +19,14 @@ func TestNemotron3NanoRenderer_Images(t *testing.T) {
msgs: []api.Message{
{Role: "user", Content: "Describe this image.", Images: []api.ImageData{api.ImageData("img1")}},
},
- expected: "\n\n\n<|im_start|>system\n<|im_end|>\n\n<|im_start|>user\n[img-0] Describe this image.<|im_end|>\n\n<|im_start|>assistant\n<think>\n",
+ expected: "<|im_start|>system\n<|im_end|>\n<|im_start|>user\n[img-0] Describe this image.<|im_end|>\n<|im_start|>assistant\n<think>\n",
},
{
name: "generic image placeholder is rewritten",
msgs: []api.Message{
{Role: "user", Content: "[img]Describe this image.", Images: []api.ImageData{api.ImageData("img1")}},
},
- expected: "\n\n\n<|im_start|>system\n<|im_end|>\n\n<|im_start|>user\n[img-0]Describe this image.<|im_end|>\n\n<|im_start|>assistant\n<think>\n",
+ expected: "<|im_start|>system\n<|im_end|>\n<|im_start|>user\n[img-0]Describe this image.<|im_end|>\n<|im_start|>assistant\n<think>\n",
},
{
name: "image offsets increment across messages",
@@ -35,7 +35,7 @@ func TestNemotron3NanoRenderer_Images(t *testing.T) {
{Role: "assistant", Content: "It shows something."},
{Role: "user", Content: "Compare these.", Images: []api.ImageData{api.ImageData("img2"), api.ImageData("img3")}},
},
- expected: "\n\n\n<|im_start|>system\n<|im_end|>\n\n<|im_start|>user\n[img-0] Describe the first image.<|im_end|>\n<|im_start|>assistant\n<think></think>It shows something.<|im_end|>\n<|im_start|>user\n[img-1][img-2] Compare these.<|im_end|>\n\n<|im_start|>assistant\n<think>\n",
+ expected: "<|im_start|>system\n<|im_end|>\n<|im_start|>user\n[img-0] Describe the first image.<|im_end|>\n<|im_start|>assistant\n<think></think>It shows something.<|im_end|>\n<|im_start|>user\n[img-1][img-2] Compare these.<|im_end|>\n<|im_start|>assistant\n<think>\n",
},
}
diff --git a/model/renderers/nemotron_cases_test.go b/model/renderers/nemotron_cases_test.go
new file mode 100644
index 000000000..740ffa275
--- /dev/null
+++ b/model/renderers/nemotron_cases_test.go
@@ -0,0 +1,740 @@
+package renderers
+
+import "github.com/ollama/ollama/api"
+
+// nemotronExtraCases covers template branches the base reference table does
+// not reach: tool-schema shapes, agentic tool loops, and content edge cases.
+// Each entry names the branch it exercises. Shared by every flavor's parity
+// test, which supply their own expectations.
+func nemotronExtraCases() []nemotronReferenceCase {
+ mkTool := func(name, desc string, params *api.ToolFunctionParameters) api.Tool {
+ t := api.Tool{Type: "function"}
+ t.Function.Name = name
+ t.Function.Description = desc
+ if params != nil {
+ t.Function.Parameters = *params
+ }
+ return t
+ }
+ strProp := func(key string, p api.ToolProperty) *api.ToolPropertiesMap {
+ return testPropsOrdered([]orderedProp{{Key: key, Value: p}})
+ }
+
+ return []nemotronReferenceCase{
+ {
+ // tool.description undefined (line 56)
+ name: "tool without description",
+ messages: []api.Message{{Role: "user", Content: "go"}},
+ tools: []api.Tool{mkTool("ping", "", &api.ToolFunctionParameters{Type: "object", Required: []string{"host"}, Properties: strProp("host", api.ToolProperty{Type: api.PropertyType{"string"}, Description: "Host"})})},
+ },
+ {
+ // tool.parameters undefined (line 60)
+ name: "tool without parameters",
+ messages: []api.Message{{Role: "user", Content: "go"}},
+ tools: []api.Tool{mkTool("now", "Current time", nil)},
+ },
+ {
+ // param_fields.type undefined (line 64)
+ name: "tool param without type",
+ messages: []api.Message{{Role: "user", Content: "go"}},
+ tools: []api.Tool{mkTool("q", "Query", &api.ToolFunctionParameters{Type: "object", Properties: strProp("x", api.ToolProperty{Description: "no type"})})},
+ },
+ {
+ // unhandled keys fall through the render_json macro (lines 2-10)
+ name: "tool param with unhandled keys",
+ messages: []api.Message{{Role: "user", Content: "go"}},
+ tools: []api.Tool{mkTool("q", "Query", &api.ToolFunctionParameters{Type: "object", Properties: strProp("x", api.ToolProperty{Type: api.PropertyType{"string"}, Description: "X", Items: []any{"a", "b"}})})},
+ },
+ {
+ // tool.parameters.required undefined (line 80)
+ name: "tool without required list",
+ messages: []api.Message{{Role: "user", Content: "go"}},
+ tools: []api.Tool{mkTool("q", "Query", &api.ToolFunctionParameters{Type: "object", Properties: strProp("x", api.ToolProperty{Type: api.PropertyType{"string"}})})},
+ },
+ {
+ // a later system message takes the user/system branch (line 164)
+ name: "system message after first turn",
+ messages: []api.Message{
+ {Role: "system", Content: "First system"},
+ {Role: "user", Content: "Hi"},
+ {Role: "system", Content: "Second system"},
+ {Role: "user", Content: "Again"},
+ },
+ },
+ {
+ // tool message is the last message (loop.last, line 182)
+ name: "tool message last",
+ messages: []api.Message{
+ {Role: "user", Content: "go"},
+ {Role: "assistant", Content: "", ToolCalls: []api.ToolCall{{Function: api.ToolCallFunction{Name: "f"}}}},
+ {Role: "tool", Content: "result"},
+ },
+ },
+ {
+ // tool run followed by a non-tool message (loop.nextitem, line 180)
+ name: "tool run then assistant",
+ messages: []api.Message{
+ {Role: "user", Content: "go"},
+ {Role: "assistant", Content: "", ToolCalls: []api.ToolCall{{Function: api.ToolCallFunction{Name: "f"}}}},
+ {Role: "tool", Content: "one"},
+ {Role: "tool", Content: "two"},
+ {Role: "assistant", Content: "done"},
+ {Role: "user", Content: "next"},
+ },
+ },
+ {
+ // two user turns: last_user_idx drives history truncation (line 149)
+ name: "two user turns truncates earlier thinking",
+ messages: []api.Message{
+ {Role: "user", Content: "first"},
+ {Role: "assistant", Content: "answer one", Thinking: "early reasoning"},
+ {Role: "user", Content: "second"},
+ {Role: "assistant", Content: "answer two", Thinking: "late reasoning"},
+ },
+ },
+ {
+ // assistant with reasoning AND tool calls (lines 100 + 112)
+ name: "assistant reasoning with tool call",
+ messages: []api.Message{
+ {Role: "user", Content: "go"},
+ {Role: "assistant", Content: "calling", Thinking: "decide", ToolCalls: []api.ToolCall{{Function: api.ToolCallFunction{Name: "f"}}}},
+ },
+ },
+ {
+ // only a system message, no user turn
+ name: "system only no user",
+ messages: []api.Message{{Role: "system", Content: "Only system"}},
+ },
+ {
+ // assistant speaks first, no preceding user (last_user_idx = -1)
+ name: "assistant first no user",
+ messages: []api.Message{
+ {Role: "assistant", Content: "unprompted"},
+ {Role: "user", Content: "now ask"},
+ },
+ },
+ {
+ // tool message with no preceding assistant (previtem nil)
+ name: "tool message first",
+ messages: []api.Message{{Role: "tool", Content: "orphan result"}},
+ },
+ {
+ // several tools registered (for tool in tools, line 51)
+ name: "multiple tools",
+ messages: []api.Message{{Role: "user", Content: "go"}},
+ tools: []api.Tool{
+ mkTool("alpha", "First", &api.ToolFunctionParameters{Type: "object", Properties: strProp("a", api.ToolProperty{Type: api.PropertyType{"string"}})}),
+ mkTool("beta", "Second", nil),
+ },
+ },
+ {
+ // tool_call arguments with several keys (line 139)
+ name: "tool call multiple arguments",
+ messages: []api.Message{
+ {Role: "user", Content: "go"},
+ {Role: "assistant", ToolCalls: []api.ToolCall{{Function: api.ToolCallFunction{
+ Name: "f",
+ Arguments: testArgsOrdered([]orderedArg{{Key: "one", Value: "1"}, {Key: "two", Value: 2}, {Key: "three", Value: true}}),
+ }}}},
+ },
+ },
+ {
+ // assistant with no content, no thinking, no tool calls (line 159/161)
+ name: "assistant fully empty",
+ messages: []api.Message{
+ {Role: "user", Content: "go"},
+ {Role: "assistant", Content: ""},
+ {Role: "user", Content: "again"},
+ },
+ },
+ {
+ // deep multi-turn: several assistant turns before the last user
+ name: "deep multi turn truncation",
+ messages: []api.Message{
+ {Role: "user", Content: "u1"},
+ {Role: "assistant", Content: "a1", Thinking: "t1"},
+ {Role: "user", Content: "u2"},
+ {Role: "assistant", Content: "a2", Thinking: "t2"},
+ {Role: "user", Content: "u3"},
+ {Role: "assistant", Content: "a3", Thinking: "t3"},
+ },
+ },
+ {
+ // think tags inside content alongside a tool call (line 120/122)
+ name: "content think tags with tool call",
+ messages: []api.Message{
+ {Role: "user", Content: "go"},
+ {Role: "assistant", Content: "<think>inline</think>after", ToolCalls: []api.ToolCall{{Function: api.ToolCallFunction{Name: "f"}}}},
+ },
+ },
+ {
+ // tool response carrying JSON
+ name: "tool response json",
+ messages: []api.Message{
+ {Role: "user", Content: "go"},
+ {Role: "assistant", ToolCalls: []api.ToolCall{{Function: api.ToolCallFunction{Name: "f"}}}},
+ {Role: "tool", Content: `{"temp": 14, "unit": "c"}`},
+ {Role: "user", Content: "and?"},
+ },
+ },
+ {
+ // unopened closing tag only, in assistant content
+ name: "assistant closing tag only",
+ messages: []api.Message{
+ {Role: "user", Content: "go"},
+ {Role: "assistant", Content: "stray </think> tail"},
+ {Role: "user", Content: "again"},
+ },
+ },
+ {
+ // scalar types through the template's `| string` path
+ name: "tool call scalar arg types",
+ messages: []api.Message{
+ {Role: "user", Content: "go"},
+ {Role: "assistant", ToolCalls: []api.ToolCall{{Function: api.ToolCallFunction{
+ Name: "f",
+ Arguments: testArgsOrdered([]orderedArg{
+ {Key: "int", Value: 7},
+ {Key: "float", Value: 2.5},
+ {Key: "wholefloat", Value: 2.0},
+ {Key: "boolfalse", Value: false},
+ {Key: "empty", Value: ""},
+ {Key: "zero", Value: 0},
+ }),
+ }}}},
+ },
+ },
+ {
+ // nested container arg goes through `| tojson` instead
+ name: "tool call container arg",
+ messages: []api.Message{
+ {Role: "user", Content: "go"},
+ {Role: "assistant", ToolCalls: []api.ToolCall{{Function: api.ToolCallFunction{
+ Name: "f",
+ Arguments: testArgsOrdered([]orderedArg{
+ {Key: "obj", Value: map[string]any{"k": true}},
+ {Key: "arr", Value: []any{1, "two", false}},
+ }),
+ }}}},
+ },
+ },
+ {
+ // multiple tool calls in one assistant message
+ name: "assistant two tool calls",
+ messages: []api.Message{
+ {Role: "user", Content: "go"},
+ {Role: "assistant", ToolCalls: []api.ToolCall{
+ {Function: api.ToolCallFunction{Name: "first", Arguments: testArgs(map[string]any{"a": "1"})}},
+ {Function: api.ToolCallFunction{Name: "second"}},
+ }},
+ },
+ },
+ {
+ // tool call with no arguments at all (arguments undefined)
+ name: "tool call no arguments",
+ messages: []api.Message{
+ {Role: "user", Content: "go"},
+ {Role: "assistant", ToolCalls: []api.ToolCall{{Function: api.ToolCallFunction{Name: "bare"}}}},
+ },
+ },
+ {
+ // multiline content in user and assistant turns
+ name: "multiline content",
+ messages: []api.Message{
+ {Role: "user", Content: "line one\nline two\n"},
+ {Role: "assistant", Content: "reply one\nreply two"},
+ {Role: "user", Content: "again"},
+ },
+ },
+ {
+ // unicode and special characters survive verbatim
+ name: "unicode content",
+ messages: []api.Message{
+ {Role: "user", Content: "héllo <b>&amp;</b> 日本語 \u00e9"},
+ },
+ },
+ {
+ // empty user content
+ name: "empty user content",
+ messages: []api.Message{{Role: "user", Content: ""}},
+ },
+ {
+ // system message that itself contains tool-ish markup
+ name: "system with markup",
+ messages: []api.Message{
+ {Role: "system", Content: "<tool_call>not real</tool_call>"},
+ {Role: "user", Content: "go"},
+ },
+ },
+ {
+ // tools registered AND an assistant tool call in history
+ name: "tools registered with history call",
+ messages: []api.Message{
+ {Role: "user", Content: "go"},
+ {Role: "assistant", ToolCalls: []api.ToolCall{{Function: api.ToolCallFunction{Name: "search_docs", Arguments: testArgs(map[string]any{"query": "api"})}}}},
+ {Role: "tool", Content: "found"},
+ {Role: "user", Content: "thanks"},
+ },
+ tools: nemotron3NanoReferenceTools(),
+ },
+ {
+ // thinking explicitly omitted (think == nil) with history
+ name: "think unset with history",
+ messages: []api.Message{
+ {Role: "user", Content: "u1"},
+ {Role: "assistant", Content: "a1", Thinking: "t1"},
+ {Role: "user", Content: "u2"},
+ },
+ },
+ {
+ // two assistant turns in a row
+ name: "consecutive assistant messages",
+ messages: []api.Message{
+ {Role: "user", Content: "go"},
+ {Role: "assistant", Content: "first"},
+ {Role: "assistant", Content: "second"},
+ {Role: "user", Content: "again"},
+ },
+ },
+ {
+ // user turn directly after a tool response
+ name: "user directly after tool",
+ messages: []api.Message{
+ {Role: "user", Content: "go"},
+ {Role: "assistant", ToolCalls: []api.ToolCall{{Function: api.ToolCallFunction{Name: "f"}}}},
+ {Role: "tool", Content: "res"},
+ {Role: "user", Content: "next"},
+ },
+ },
+ {
+ // thinking present but content empty
+ name: "assistant thinking empty content",
+ messages: []api.Message{
+ {Role: "user", Content: "go"},
+ {Role: "assistant", Content: "", Thinking: "only reasoning"},
+ {Role: "user", Content: "again"},
+ },
+ },
+ {
+ // tool response with empty content
+ name: "tool response empty",
+ messages: []api.Message{
+ {Role: "user", Content: "go"},
+ {Role: "assistant", ToolCalls: []api.ToolCall{{Function: api.ToolCallFunction{Name: "f"}}}},
+ {Role: "tool", Content: ""},
+ },
+ },
+ {
+ // whitespace-only assistant content
+ name: "assistant whitespace content",
+ messages: []api.Message{
+ {Role: "user", Content: "go"},
+ {Role: "assistant", Content: " "},
+ {Role: "user", Content: "again"},
+ },
+ },
+ {
+ // empty system message string
+ name: "empty system message",
+ messages: []api.Message{
+ {Role: "system", Content: ""},
+ {Role: "user", Content: "go"},
+ },
+ },
+ {
+ // a full agentic loop: two rounds of call/response then an answer
+ name: "agentic multi round tool loop",
+ messages: []api.Message{
+ {Role: "user", Content: "plan it"},
+ {Role: "assistant", Content: "checking", Thinking: "r1", ToolCalls: []api.ToolCall{{Function: api.ToolCallFunction{Name: "lookup", Arguments: testArgs(map[string]any{"q": "a"})}}}},
+ {Role: "tool", Content: "res one"},
+ {Role: "assistant", Content: "again", Thinking: "r2", ToolCalls: []api.ToolCall{{Function: api.ToolCallFunction{Name: "lookup", Arguments: testArgs(map[string]any{"q": "b"})}}}},
+ {Role: "tool", Content: "res two"},
+ {Role: "assistant", Content: "final answer"},
+ {Role: "user", Content: "thanks"},
+ },
+ tools: nemotron3NanoReferenceTools(),
+ },
+ {
+ // tool call name with punctuation
+ name: "tool call punctuated name",
+ messages: []api.Message{
+ {Role: "user", Content: "go"},
+ {Role: "assistant", ToolCalls: []api.ToolCall{{Function: api.ToolCallFunction{Name: "ns.sub_tool-v2"}}}},
+ },
+ },
+ {
+ // nested empty containers as arguments
+ name: "tool call empty containers",
+ messages: []api.Message{
+ {Role: "user", Content: "go"},
+ {Role: "assistant", ToolCalls: []api.ToolCall{{Function: api.ToolCallFunction{
+ Name: "f",
+ Arguments: testArgsOrdered([]orderedArg{
+ {Key: "obj", Value: map[string]any{}},
+ {Key: "arr", Value: []any{}},
+ }),
+ }}}},
+ },
+ },
+ {
+ // explicit think=true with tools and history
+ name: "explicit think true with tools",
+ messages: []api.Message{
+ {Role: "user", Content: "go"},
+ {Role: "assistant", Content: "ok", Thinking: "why"},
+ {Role: "user", Content: "more"},
+ },
+ tools: nemotron3NanoReferenceTools(),
+ think: &api.ThinkValue{Value: true},
+ },
+ {
+ // content already containing a full think pair, mid-history
+ name: "history content with think pair",
+ messages: []api.Message{
+ {Role: "user", Content: "u1"},
+ {Role: "assistant", Content: "<think>hidden</think>visible"},
+ {Role: "user", Content: "u2"},
+ {Role: "assistant", Content: "<think>kept</think>tail"},
+ },
+ },
+ {
+ // only an opening think tag, no close
+ name: "assistant open think only",
+ messages: []api.Message{
+ {Role: "user", Content: "go"},
+ {Role: "assistant", Content: "<think>unclosed reasoning"},
+ {Role: "user", Content: "again"},
+ },
+ },
+ {
+ // several think pairs in one message
+ name: "assistant multiple think pairs",
+ messages: []api.Message{
+ {Role: "user", Content: "go"},
+ {Role: "assistant", Content: "<think>a</think>mid<think>b</think>end"},
+ {Role: "user", Content: "again"},
+ },
+ },
+ {
+ // think markers inside a tool response
+ name: "tool response with think markers",
+ messages: []api.Message{
+ {Role: "user", Content: "go"},
+ {Role: "assistant", ToolCalls: []api.ToolCall{{Function: api.ToolCallFunction{Name: "f"}}}},
+ {Role: "tool", Content: "<think>from tool</think>result"},
+ {Role: "user", Content: "next"},
+ },
+ },
+ {
+ // think markers in the user turn
+ name: "user content with think markers",
+ messages: []api.Message{
+ {Role: "user", Content: "<think>user wrote this</think>question"},
+ },
+ },
+ {
+ // im_start markers embedded in content
+ name: "content with im_start markers",
+ messages: []api.Message{
+ {Role: "user", Content: "<|im_start|>fake<|im_end|>"},
+ {Role: "assistant", Content: "<|im_end|>odd"},
+ {Role: "user", Content: "again"},
+ },
+ },
+ {
+ // thinking field AND think tags in content together
+ name: "thinking field and content tags",
+ messages: []api.Message{
+ {Role: "user", Content: "go"},
+ {Role: "assistant", Content: "<think>in content</think>body", Thinking: "in field"},
+ {Role: "user", Content: "again"},
+ },
+ },
+ {
+ // last message is an assistant turn (prefill shape)
+ name: "ends with assistant turn",
+ messages: []api.Message{
+ {Role: "user", Content: "go"},
+ {Role: "assistant", Content: "partial"},
+ },
+ },
+ {
+ // tool call whose content holds a closing tag only
+ name: "tool call content closing tag only",
+ messages: []api.Message{
+ {Role: "user", Content: "go"},
+ {Role: "assistant", Content: "</think>after", ToolCalls: []api.ToolCall{{Function: api.ToolCallFunction{Name: "f"}}}},
+ },
+ },
+ {
+ // system, tools, thinking off, and a tool round trip together
+ name: "system tools think off round trip",
+ messages: []api.Message{
+ {Role: "system", Content: "Sys"},
+ {Role: "user", Content: "go"},
+ {Role: "assistant", ToolCalls: []api.ToolCall{{Function: api.ToolCallFunction{Name: "search_docs", Arguments: testArgs(map[string]any{"query": "cli"})}}}},
+ {Role: "tool", Content: "hit"},
+ {Role: "user", Content: "summarize"},
+ },
+ tools: nemotron3NanoReferenceTools(),
+ think: &api.ThinkValue{Value: false},
+ },
+ {
+ // null and numeric scalars through `| string`
+ name: "tool call null and numeric args",
+ messages: []api.Message{
+ {Role: "user", Content: "go"},
+ {Role: "assistant", ToolCalls: []api.ToolCall{{Function: api.ToolCallFunction{
+ Name: "f",
+ Arguments: testArgsOrdered([]orderedArg{
+ {Key: "nothing", Value: nil},
+ {Key: "negative", Value: -12},
+ {Key: "big", Value: 9007199254740993},
+ {Key: "fraction", Value: 0.125},
+ }),
+ }}}},
+ },
+ },
+ {
+ // nested containers exercising pythonJSON's numeric and null arms
+ name: "tool call nested mixed container",
+ messages: []api.Message{
+ {Role: "user", Content: "go"},
+ {Role: "assistant", ToolCalls: []api.ToolCall{{Function: api.ToolCallFunction{
+ Name: "f",
+ Arguments: testArgsOrdered([]orderedArg{
+ {Key: "deep", Value: map[string]any{
+ "n": nil, "i": 3, "f": 1.5, "b": false, "s": "q\"uote",
+ "inner": []any{1, map[string]any{"z": true}},
+ }},
+ }),
+ }}}},
+ },
+ },
+ {
+ // tool schema whose property carries several unhandled keys
+ name: "tool param many unhandled keys",
+ messages: []api.Message{{Role: "user", Content: "go"}},
+ tools: []api.Tool{mkTool("q", "Query", &api.ToolFunctionParameters{
+ Type: "object",
+ Properties: strProp("x", api.ToolProperty{
+ Type: api.PropertyType{"string"},
+ Description: "X",
+ Items: map[string]any{"type": "number", "minimum": 0},
+ AnyOf: []api.ToolProperty{{Type: api.PropertyType{"null"}}},
+ }),
+ })},
+ },
+ {
+ // tool call whose content is only a think pair, forcing the
+ // truncation arm of formatToolCallContent
+ name: "tool call content think pair only",
+ messages: []api.Message{
+ {Role: "user", Content: "u1"},
+ {Role: "assistant", Content: "<think>x</think>", ToolCalls: []api.ToolCall{{Function: api.ToolCallFunction{Name: "f"}}}},
+ {Role: "user", Content: "u2"},
+ {Role: "assistant", Content: "<think>y</think>z", ToolCalls: []api.ToolCall{{Function: api.ToolCallFunction{Name: "g"}}}},
+ },
+ },
+ {
+ // string argument containing characters that need quoting
+ name: "tool call quoted string arg",
+ messages: []api.Message{
+ {Role: "user", Content: "go"},
+ {Role: "assistant", ToolCalls: []api.ToolCall{{Function: api.ToolCallFunction{
+ Name: "f",
+ Arguments: testArgsOrdered([]orderedArg{{Key: "s", Value: "line\nbreak \"quoted\""}}),
+ }}}},
+ },
+ },
+ {
+ // params-level Items plus a deeply nested property schema:
+ // exercises renderToolParameterExtraKeys' items arm and
+ // pythonJSON's ToolPropertiesMap / ToolProperty recursion.
+ name: "tool schema nested and items",
+ messages: []api.Message{{Role: "user", Content: "go"}},
+ tools: []api.Tool{{
+ Type: "function",
+ Function: api.ToolFunction{
+ Name: "deep",
+ Description: "Nested schema",
+ Parameters: api.ToolFunctionParameters{
+ Type: "object",
+ Items: map[string]any{"type": "string"},
+ Required: []string{"outer"},
+ Properties: testPropsOrdered([]orderedProp{
+ {
+ Key: "outer",
+ Value: api.ToolProperty{
+ Type: api.PropertyType{"object"},
+ Description: "Outer object",
+ Enum: []any{"a", "b"},
+ Items: map[string]any{"type": "integer"},
+ Required: []string{"inner"},
+ Properties: testPropsOrdered([]orderedProp{
+ {Key: "inner", Value: api.ToolProperty{Type: api.PropertyType{"string"}, Description: "Inner"}},
+ {Key: "flag", Value: api.ToolProperty{Type: api.PropertyType{"boolean", "null"}}},
+ }),
+ },
+ },
+ }),
+ },
+ },
+ }},
+ },
+ {
+ // unsigned and mixed numeric values inside a container argument,
+ // hitting pythonJSON's uint arm
+ name: "tool call unsigned numeric container",
+ messages: []api.Message{
+ {Role: "user", Content: "go"},
+ {Role: "assistant", ToolCalls: []api.ToolCall{{Function: api.ToolCallFunction{
+ Name: "f",
+ Arguments: testArgsOrdered([]orderedArg{
+ {Key: "nums", Value: map[string]any{"u": uint(7), "u8": uint8(255), "i64": int64(-9), "f32": float32(1.5)}},
+ }),
+ }}}},
+ },
+ },
+ {
+ // assistant tool call whose content is whitespace only, hitting
+ // formatToolCallContent's empty guard
+ name: "tool call whitespace content",
+ messages: []api.Message{
+ {Role: "user", Content: "go"},
+ {Role: "assistant", Content: " \n ", ToolCalls: []api.ToolCall{{Function: api.ToolCallFunction{Name: "f"}}}},
+ },
+ },
+ {
+ // $defs carrying a property map rather than a plain map
+ name: "tool schema defs property map",
+ messages: []api.Message{{Role: "user", Content: "go"}},
+ tools: []api.Tool{{
+ Type: "function",
+ Function: api.ToolFunction{
+ Name: "defs",
+ Parameters: api.ToolFunctionParameters{
+ Type: "object",
+ Defs: testPropsOrdered([]orderedProp{
+ {Key: "shared", Value: api.ToolProperty{Type: api.PropertyType{"string"}, Description: "Shared"}},
+ }),
+ Properties: testPropsOrdered([]orderedProp{
+ {Key: "x", Value: api.ToolProperty{Type: api.PropertyType{"string"}}},
+ }),
+ },
+ },
+ }},
+ },
+ {
+ // a rich property nested inside $defs: reaches pythonJSON's
+ // ToolProperty arms for anyOf, items, enum, properties, required
+ name: "tool schema defs rich property",
+ messages: []api.Message{{Role: "user", Content: "go"}},
+ tools: []api.Tool{{
+ Type: "function",
+ Function: api.ToolFunction{
+ Name: "rich",
+ Parameters: api.ToolFunctionParameters{
+ Type: "object",
+ Defs: testPropsOrdered([]orderedProp{
+ {Key: "node", Value: api.ToolProperty{
+ AnyOf: []api.ToolProperty{{Type: api.PropertyType{"string"}}, {Type: api.PropertyType{"null"}}},
+ Type: api.PropertyType{"object"},
+ Items: map[string]any{"type": "integer"},
+ Description: "Node",
+ Enum: []any{"x", "y"},
+ Required: []string{"child"},
+ Properties: testPropsOrdered([]orderedProp{
+ {Key: "child", Value: api.ToolProperty{Type: api.PropertyType{"string"}}},
+ }),
+ }},
+ }),
+ Properties: testPropsOrdered([]orderedProp{
+ {Key: "p", Value: api.ToolProperty{Type: api.PropertyType{"string"}}},
+ }),
+ },
+ },
+ }},
+ },
+ {
+ // params Items carrying a PropertyType directly
+ name: "tool schema items property type",
+ messages: []api.Message{{Role: "user", Content: "go"}},
+ tools: []api.Tool{{
+ Type: "function",
+ Function: api.ToolFunction{
+ Name: "pt",
+ Parameters: api.ToolFunctionParameters{
+ Type: "object",
+ Items: api.PropertyType{"string", "null"},
+ Properties: testPropsOrdered([]orderedProp{
+ {Key: "p", Value: api.ToolProperty{Type: api.PropertyType{"string"}}},
+ }),
+ },
+ },
+ }},
+ },
+ {
+ // a typed-nil property map in $defs
+ name: "tool schema nil defs map",
+ messages: []api.Message{{Role: "user", Content: "go"}},
+ tools: []api.Tool{{
+ Type: "function",
+ Function: api.ToolFunction{
+ Name: "niltest",
+ Parameters: api.ToolFunctionParameters{
+ Type: "object",
+ Defs: (*api.ToolPropertiesMap)(nil),
+ Properties: testPropsOrdered([]orderedProp{
+ {Key: "p", Value: api.ToolProperty{Type: api.PropertyType{"string"}}},
+ }),
+ },
+ },
+ }},
+ },
+ {
+ // an argument value of a type pythonJSON has no case for, so it
+ // falls to the default arm and round-trips through JSON
+ name: "tool call struct argument",
+ messages: []api.Message{
+ {Role: "user", Content: "go"},
+ {Role: "assistant", ToolCalls: []api.ToolCall{{Function: api.ToolCallFunction{
+ Name: "f",
+ Arguments: testArgsOrdered([]orderedArg{
+ {Key: "custom", Value: struct {
+ A string `json:"a"`
+ B int `json:"b"`
+ }{A: "x", B: 2}},
+ {Key: "list", Value: []int{1, 2, 3}},
+ }),
+ }}}},
+ },
+ },
+ {
+ // a nested property whose own Properties map is nil, reaching
+ // pythonJSON's nil-map guard through a container
+ name: "tool schema nested nil properties",
+ messages: []api.Message{{Role: "user", Content: "go"}},
+ tools: []api.Tool{{
+ Type: "function",
+ Function: api.ToolFunction{
+ Name: "nested",
+ Parameters: api.ToolFunctionParameters{
+ Type: "object",
+ Defs: testPropsOrdered([]orderedProp{
+ {Key: "node", Value: api.ToolProperty{
+ Type: api.PropertyType{"object"},
+ Properties: (*api.ToolPropertiesMap)(nil),
+ Required: []string{"q"},
+ }},
+ }),
+ Properties: testPropsOrdered([]orderedProp{
+ {Key: "p", Value: api.ToolProperty{Type: api.PropertyType{"string"}}},
+ }),
+ },
+ },
+ }},
+ },
+ }
+}
diff --git a/model/renderers/nemotron_extra_reference_test.go b/model/renderers/nemotron_extra_reference_test.go
new file mode 100644
index 000000000..2f7bb0f4d
--- /dev/null
+++ b/model/renderers/nemotron_extra_reference_test.go
@@ -0,0 +1,108 @@
+package renderers
+
+import (
+ "os"
+ "testing"
+
+ "github.com/google/go-cmp/cmp"
+)
+
+// Expectations for the extra cases, captured from
+// testdata/nemotron3nano_chat_template.jinja2 itself, so they are the
+// template's output and not the renderer's. The default run compares the
+// renderer against them; VERIFY_JINJA2=1 re-checks them against the template.
+var nemotronExtraExpected = map[string]string{
+ "tool without description": "<|im_start|>system\n# Tools\n\nYou have access to the following functions:\n\n<tools>\n<function>\n<name>ping</name>\n<parameters>\n<parameter>\n<name>host</name>\n<type>string</type>\n<description>Host</description>\n</parameter>\n<required>[\"host\"]</required>\n</parameters>\n</function>\n</tools>\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n<tool_call>\n<function=example_function_name>\n<parameter=example_parameter_1>\nvalue_1\n</parameter>\n<parameter=example_parameter_2>\nThis is the value for the second parameter\nthat can span\nmultiple lines\n</parameter>\n</function>\n</tool_call>\n\n<IMPORTANT>\nReminder:\n- Function calls MUST follow the specified format: an inner <function=...></function> block must be nested within <tool_call></tool_call> XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n</IMPORTANT><|im_end|>\n<|im_start|>user\ngo<|im_end|>\n<|im_start|>assistant\n<think>\n",
+ "tool without parameters": "<|im_start|>system\n# Tools\n\nYou have access to the following functions:\n\n<tools>\n<function>\n<name>now</name>\n<description>Current time</description>\n<parameters>\n</parameters>\n</function>\n</tools>\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n<tool_call>\n<function=example_function_name>\n<parameter=example_parameter_1>\nvalue_1\n</parameter>\n<parameter=example_parameter_2>\nThis is the value for the second parameter\nthat can span\nmultiple lines\n</parameter>\n</function>\n</tool_call>\n\n<IMPORTANT>\nReminder:\n- Function calls MUST follow the specified format: an inner <function=...></function> block must be nested within <tool_call></tool_call> XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n</IMPORTANT><|im_end|>\n<|im_start|>user\ngo<|im_end|>\n<|im_start|>assistant\n<think>\n",
+ "tool param without type": "<|im_start|>system\n# Tools\n\nYou have access to the following functions:\n\n<tools>\n<function>\n<name>q</name>\n<description>Query</description>\n<parameters>\n<parameter>\n<name>x</name>\n<description>no type</description>\n</parameter>\n</parameters>\n</function>\n</tools>\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n<tool_call>\n<function=example_function_name>\n<parameter=example_parameter_1>\nvalue_1\n</parameter>\n<parameter=example_parameter_2>\nThis is the value for the second parameter\nthat can span\nmultiple lines\n</parameter>\n</function>\n</tool_call>\n\n<IMPORTANT>\nReminder:\n- Function calls MUST follow the specified format: an inner <function=...></function> block must be nested within <tool_call></tool_call> XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n</IMPORTANT><|im_end|>\n<|im_start|>user\ngo<|im_end|>\n<|im_start|>assistant\n<think>\n",
+ "tool param with unhandled keys": "<|im_start|>system\n# Tools\n\nYou have access to the following functions:\n\n<tools>\n<function>\n<name>q</name>\n<description>Query</description>\n<parameters>\n<parameter>\n<name>x</name>\n<type>string</type>\n<description>X</description>\n<items>[\"a\", \"b\"]</items>\n</parameter>\n</parameters>\n</function>\n</tools>\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n<tool_call>\n<function=example_function_name>\n<parameter=example_parameter_1>\nvalue_1\n</parameter>\n<parameter=example_parameter_2>\nThis is the value for the second parameter\nthat can span\nmultiple lines\n</parameter>\n</function>\n</tool_call>\n\n<IMPORTANT>\nReminder:\n- Function calls MUST follow the specified format: an inner <function=...></function> block must be nested within <tool_call></tool_call> XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n</IMPORTANT><|im_end|>\n<|im_start|>user\ngo<|im_end|>\n<|im_start|>assistant\n<think>\n",
+ "tool without required list": "<|im_start|>system\n# Tools\n\nYou have access to the following functions:\n\n<tools>\n<function>\n<name>q</name>\n<description>Query</description>\n<parameters>\n<parameter>\n<name>x</name>\n<type>string</type>\n</parameter>\n</parameters>\n</function>\n</tools>\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n<tool_call>\n<function=example_function_name>\n<parameter=example_parameter_1>\nvalue_1\n</parameter>\n<parameter=example_parameter_2>\nThis is the value for the second parameter\nthat can span\nmultiple lines\n</parameter>\n</function>\n</tool_call>\n\n<IMPORTANT>\nReminder:\n- Function calls MUST follow the specified format: an inner <function=...></function> block must be nested within <tool_call></tool_call> XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n</IMPORTANT><|im_end|>\n<|im_start|>user\ngo<|im_end|>\n<|im_start|>assistant\n<think>\n",
+ "system message after first turn": "<|im_start|>system\nFirst system<|im_end|>\n<|im_start|>user\nHi<|im_end|>\n<|im_start|>system\nSecond system<|im_end|>\n<|im_start|>user\nAgain<|im_end|>\n<|im_start|>assistant\n<think>\n",
+ "tool message last": "<|im_start|>system\n<|im_end|>\n<|im_start|>user\ngo<|im_end|>\n<|im_start|>assistant\n<think></think>\n<tool_call>\n<function=f>\n</function>\n</tool_call>\n<|im_end|>\n<|im_start|>user\n<tool_response>\nresult\n</tool_response>\n<|im_end|>\n<|im_start|>assistant\n<think>\n",
+ "tool run then assistant": "<|im_start|>system\n<|im_end|>\n<|im_start|>user\ngo<|im_end|>\n<|im_start|>assistant\n<think></think>\n<tool_call>\n<function=f>\n</function>\n</tool_call>\n<|im_end|>\n<|im_start|>user\n<tool_response>\none\n</tool_response>\n<tool_response>\ntwo\n</tool_response>\n<|im_end|>\n<|im_start|>assistant\n<think></think>done<|im_end|>\n<|im_start|>user\nnext<|im_end|>\n<|im_start|>assistant\n<think>\n",
+ "two user turns truncates earlier thinking": "<|im_start|>system\n<|im_end|>\n<|im_start|>user\nfirst<|im_end|>\n<|im_start|>assistant\n<think></think>\nanswer one<|im_end|>\n<|im_start|>user\nsecond<|im_end|>\n<|im_start|>assistant\n<think>\nlate reasoning\n</think>\nanswer two<|im_end|>\n<|im_start|>assistant\n<think>\n",
+ "assistant reasoning with tool call": "<|im_start|>system\n<|im_end|>\n<|im_start|>user\ngo<|im_end|>\n<|im_start|>assistant\n<think>\ndecide\n</think>\ncalling\n<tool_call>\n<function=f>\n</function>\n</tool_call>\n<|im_end|>\n<|im_start|>assistant\n<think>\n",
+ "system only no user": "<|im_start|>system\nOnly system<|im_end|>\n<|im_start|>assistant\n<think>\n",
+ "assistant first no user": "<|im_start|>system\n<|im_end|>\n<|im_start|>assistant\n<think></think>unprompted<|im_end|>\n<|im_start|>user\nnow ask<|im_end|>\n<|im_start|>assistant\n<think>\n",
+ "tool message first": "<|im_start|>system\n<|im_end|>\n<tool_response>\norphan result\n</tool_response>\n<|im_end|>\n<|im_start|>assistant\n<think>\n",
+ "multiple tools": "<|im_start|>system\n# Tools\n\nYou have access to the following functions:\n\n<tools>\n<function>\n<name>alpha</name>\n<description>First</description>\n<parameters>\n<parameter>\n<name>a</name>\n<type>string</type>\n</parameter>\n</parameters>\n</function>\n<function>\n<name>beta</name>\n<description>Second</description>\n<parameters>\n</parameters>\n</function>\n</tools>\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n<tool_call>\n<function=example_function_name>\n<parameter=example_parameter_1>\nvalue_1\n</parameter>\n<parameter=example_parameter_2>\nThis is the value for the second parameter\nthat can span\nmultiple lines\n</parameter>\n</function>\n</tool_call>\n\n<IMPORTANT>\nReminder:\n- Function calls MUST follow the specified format: an inner <function=...></function> block must be nested within <tool_call></tool_call> XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n</IMPORTANT><|im_end|>\n<|im_start|>user\ngo<|im_end|>\n<|im_start|>assistant\n<think>\n",
+ "tool call multiple arguments": "<|im_start|>system\n<|im_end|>\n<|im_start|>user\ngo<|im_end|>\n<|im_start|>assistant\n<think></think>\n<tool_call>\n<function=f>\n<parameter=one>\n1\n</parameter>\n<parameter=two>\n2\n</parameter>\n<parameter=three>\nTrue\n</parameter>\n</function>\n</tool_call>\n<|im_end|>\n<|im_start|>assistant\n<think>\n",
+ "assistant fully empty": "<|im_start|>system\n<|im_end|>\n<|im_start|>user\ngo<|im_end|>\n<|im_start|>assistant\n<think></think><|im_end|>\n<|im_start|>user\nagain<|im_end|>\n<|im_start|>assistant\n<think>\n",
+ "deep multi turn truncation": "<|im_start|>system\n<|im_end|>\n<|im_start|>user\nu1<|im_end|>\n<|im_start|>assistant\n<think></think>\na1<|im_end|>\n<|im_start|>user\nu2<|im_end|>\n<|im_start|>assistant\n<think></think>\na2<|im_end|>\n<|im_start|>user\nu3<|im_end|>\n<|im_start|>assistant\n<think>\nt3\n</think>\na3<|im_end|>\n<|im_start|>assistant\n<think>\n",
+ "content think tags with tool call": "<|im_start|>system\n<|im_end|>\n<|im_start|>user\ngo<|im_end|>\n<|im_start|>assistant\n<think>inline</think>after\n<tool_call>\n<function=f>\n</function>\n</tool_call>\n<|im_end|>\n<|im_start|>assistant\n<think>\n",
+ "tool response json": "<|im_start|>system\n<|im_end|>\n<|im_start|>user\ngo<|im_end|>\n<|im_start|>assistant\n<think></think>\n<tool_call>\n<function=f>\n</function>\n</tool_call>\n<|im_end|>\n<|im_start|>user\n<tool_response>\n{\"temp\": 14, \"unit\": \"c\"}\n</tool_response>\n<|im_end|>\n<|im_start|>user\nand?<|im_end|>\n<|im_start|>assistant\n<think>\n",
+ "assistant closing tag only": "<|im_start|>system\n<|im_end|>\n<|im_start|>user\ngo<|im_end|>\n<|im_start|>assistant\nstray </think> tail<|im_end|>\n<|im_start|>user\nagain<|im_end|>\n<|im_start|>assistant\n<think>\n",
+ "tool call scalar arg types": "<|im_start|>system\n<|im_end|>\n<|im_start|>user\ngo<|im_end|>\n<|im_start|>assistant\n<think></think>\n<tool_call>\n<function=f>\n<parameter=int>\n7\n</parameter>\n<parameter=float>\n2.5\n</parameter>\n<parameter=wholefloat>\n2\n</parameter>\n<parameter=boolfalse>\nFalse\n</parameter>\n<parameter=empty>\n\n</parameter>\n<parameter=zero>\n0\n</parameter>\n</function>\n</tool_call>\n<|im_end|>\n<|im_start|>assistant\n<think>\n",
+ "tool call container arg": "<|im_start|>system\n<|im_end|>\n<|im_start|>user\ngo<|im_end|>\n<|im_start|>assistant\n<think></think>\n<tool_call>\n<function=f>\n<parameter=obj>\n{\"k\": true}\n</parameter>\n<parameter=arr>\n[1, \"two\", false]\n</parameter>\n</function>\n</tool_call>\n<|im_end|>\n<|im_start|>assistant\n<think>\n",
+ "assistant two tool calls": "<|im_start|>system\n<|im_end|>\n<|im_start|>user\ngo<|im_end|>\n<|im_start|>assistant\n<think></think>\n<tool_call>\n<function=first>\n<parameter=a>\n1\n</parameter>\n</function>\n</tool_call>\n<tool_call>\n<function=second>\n</function>\n</tool_call>\n<|im_end|>\n<|im_start|>assistant\n<think>\n",
+ "tool call no arguments": "<|im_start|>system\n<|im_end|>\n<|im_start|>user\ngo<|im_end|>\n<|im_start|>assistant\n<think></think>\n<tool_call>\n<function=bare>\n</function>\n</tool_call>\n<|im_end|>\n<|im_start|>assistant\n<think>\n",
+ "multiline content": "<|im_start|>system\n<|im_end|>\n<|im_start|>user\nline one\nline two<|im_end|>\n<|im_start|>assistant\n<think></think>reply one\nreply two<|im_end|>\n<|im_start|>user\nagain<|im_end|>\n<|im_start|>assistant\n<think>\n",
+ "unicode content": "<|im_start|>system\n<|im_end|>\n<|im_start|>user\nhéllo <b>&amp;</b> 日本語 é<|im_end|>\n<|im_start|>assistant\n<think>\n",
+ "empty user content": "<|im_start|>system\n<|im_end|>\n<|im_start|>user\n<|im_end|>\n<|im_start|>assistant\n<think>\n",
+ "system with markup": "<|im_start|>system\n<tool_call>not real</tool_call><|im_end|>\n<|im_start|>user\ngo<|im_end|>\n<|im_start|>assistant\n<think>\n",
+ "tools registered with history call": "<|im_start|>system\n# Tools\n\nYou have access to the following functions:\n\n<tools>\n<function>\n<name>search_docs</name>\n<description>Search docs</description>\n<parameters>\n<parameter>\n<name>query</name>\n<type>string</type>\n<description>Search query</description>\n<enum>[\"api\", \"cli\"]</enum>\n</parameter>\n<parameter>\n<name>mode</name>\n<type>['string', 'null']</type>\n<description>Mode</description>\n<anyOf>[{\"type\": \"string\"}, {\"type\": \"number\"}]</anyOf>\n</parameter>\n<parameter>\n<name>payload</name>\n<type>object</type>\n<description>Payload</description>\n<properties>{\"enabled\": {\"type\": \"boolean\"}}</properties>\n<required>[\"enabled\"]</required>\n</parameter>\n<parameter>\n<name>tags</name>\n<type>array</type>\n<description>Tags</description>\n<items>{\"type\": \"string\"}</items>\n</parameter>\n<$defs>{\"shared\": {\"type\": \"string\"}}</$defs>\n<required>[\"query\"]</required>\n</parameters>\n</function>\n</tools>\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n<tool_call>\n<function=example_function_name>\n<parameter=example_parameter_1>\nvalue_1\n</parameter>\n<parameter=example_parameter_2>\nThis is the value for the second parameter\nthat can span\nmultiple lines\n</parameter>\n</function>\n</tool_call>\n\n<IMPORTANT>\nReminder:\n- Function calls MUST follow the specified format: an inner <function=...></function> block must be nested within <tool_call></tool_call> XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n</IMPORTANT><|im_end|>\n<|im_start|>user\ngo<|im_end|>\n<|im_start|>assistant\n<think></think>\n<tool_call>\n<function=search_docs>\n<parameter=query>\napi\n</parameter>\n</function>\n</tool_call>\n<|im_end|>\n<|im_start|>user\n<tool_response>\nfound\n</tool_response>\n<|im_end|>\n<|im_start|>user\nthanks<|im_end|>\n<|im_start|>assistant\n<think>\n",
+ "think unset with history": "<|im_start|>system\n<|im_end|>\n<|im_start|>user\nu1<|im_end|>\n<|im_start|>assistant\n<think></think>\na1<|im_end|>\n<|im_start|>user\nu2<|im_end|>\n<|im_start|>assistant\n<think>\n",
+ "consecutive assistant messages": "<|im_start|>system\n<|im_end|>\n<|im_start|>user\ngo<|im_end|>\n<|im_start|>assistant\n<think></think>first<|im_end|>\n<|im_start|>assistant\n<think></think>second<|im_end|>\n<|im_start|>user\nagain<|im_end|>\n<|im_start|>assistant\n<think>\n",
+ "user directly after tool": "<|im_start|>system\n<|im_end|>\n<|im_start|>user\ngo<|im_end|>\n<|im_start|>assistant\n<think></think>\n<tool_call>\n<function=f>\n</function>\n</tool_call>\n<|im_end|>\n<|im_start|>user\n<tool_response>\nres\n</tool_response>\n<|im_end|>\n<|im_start|>user\nnext<|im_end|>\n<|im_start|>assistant\n<think>\n",
+ "assistant thinking empty content": "<|im_start|>system\n<|im_end|>\n<|im_start|>user\ngo<|im_end|>\n<|im_start|>assistant\n<think></think><|im_end|>\n<|im_start|>user\nagain<|im_end|>\n<|im_start|>assistant\n<think>\n",
+ "tool response empty": "<|im_start|>system\n<|im_end|>\n<|im_start|>user\ngo<|im_end|>\n<|im_start|>assistant\n<think></think>\n<tool_call>\n<function=f>\n</function>\n</tool_call>\n<|im_end|>\n<|im_start|>user\n<tool_response>\n\n</tool_response>\n<|im_end|>\n<|im_start|>assistant\n<think>\n",
+ "assistant whitespace content": "<|im_start|>system\n<|im_end|>\n<|im_start|>user\ngo<|im_end|>\n<|im_start|>assistant\n<think></think><|im_end|>\n<|im_start|>user\nagain<|im_end|>\n<|im_start|>assistant\n<think>\n",
+ "empty system message": "<|im_start|>system\n<|im_end|>\n<|im_start|>user\ngo<|im_end|>\n<|im_start|>assistant\n<think>\n",
+ "agentic multi round tool loop": "<|im_start|>system\n# Tools\n\nYou have access to the following functions:\n\n<tools>\n<function>\n<name>search_docs</name>\n<description>Search docs</description>\n<parameters>\n<parameter>\n<name>query</name>\n<type>string</type>\n<description>Search query</description>\n<enum>[\"api\", \"cli\"]</enum>\n</parameter>\n<parameter>\n<name>mode</name>\n<type>['string', 'null']</type>\n<description>Mode</description>\n<anyOf>[{\"type\": \"string\"}, {\"type\": \"number\"}]</anyOf>\n</parameter>\n<parameter>\n<name>payload</name>\n<type>object</type>\n<description>Payload</description>\n<properties>{\"enabled\": {\"type\": \"boolean\"}}</properties>\n<required>[\"enabled\"]</required>\n</parameter>\n<parameter>\n<name>tags</name>\n<type>array</type>\n<description>Tags</description>\n<items>{\"type\": \"string\"}</items>\n</parameter>\n<$defs>{\"shared\": {\"type\": \"string\"}}</$defs>\n<required>[\"query\"]</required>\n</parameters>\n</function>\n</tools>\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n<tool_call>\n<function=example_function_name>\n<parameter=example_parameter_1>\nvalue_1\n</parameter>\n<parameter=example_parameter_2>\nThis is the value for the second parameter\nthat can span\nmultiple lines\n</parameter>\n</function>\n</tool_call>\n\n<IMPORTANT>\nReminder:\n- Function calls MUST follow the specified format: an inner <function=...></function> block must be nested within <tool_call></tool_call> XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n</IMPORTANT><|im_end|>\n<|im_start|>user\nplan it<|im_end|>\n<|im_start|>assistant\n<think></think>checking\n<tool_call>\n<function=lookup>\n<parameter=q>\na\n</parameter>\n</function>\n</tool_call>\n<|im_end|>\n<|im_start|>user\n<tool_response>\nres one\n</tool_response>\n<|im_end|>\n<|im_start|>assistant\n<think></think>again\n<tool_call>\n<function=lookup>\n<parameter=q>\nb\n</parameter>\n</function>\n</tool_call>\n<|im_end|>\n<|im_start|>user\n<tool_response>\nres two\n</tool_response>\n<|im_end|>\n<|im_start|>assistant\n<think></think>final answer<|im_end|>\n<|im_start|>user\nthanks<|im_end|>\n<|im_start|>assistant\n<think>\n",
+ "tool call punctuated name": "<|im_start|>system\n<|im_end|>\n<|im_start|>user\ngo<|im_end|>\n<|im_start|>assistant\n<think></think>\n<tool_call>\n<function=ns.sub_tool-v2>\n</function>\n</tool_call>\n<|im_end|>\n<|im_start|>assistant\n<think>\n",
+ "tool call empty containers": "<|im_start|>system\n<|im_end|>\n<|im_start|>user\ngo<|im_end|>\n<|im_start|>assistant\n<think></think>\n<tool_call>\n<function=f>\n<parameter=obj>\n{}\n</parameter>\n<parameter=arr>\n[]\n</parameter>\n</function>\n</tool_call>\n<|im_end|>\n<|im_start|>assistant\n<think>\n",
+ "explicit think true with tools": "<|im_start|>system\n# Tools\n\nYou have access to the following functions:\n\n<tools>\n<function>\n<name>search_docs</name>\n<description>Search docs</description>\n<parameters>\n<parameter>\n<name>query</name>\n<type>string</type>\n<description>Search query</description>\n<enum>[\"api\", \"cli\"]</enum>\n</parameter>\n<parameter>\n<name>mode</name>\n<type>['string', 'null']</type>\n<description>Mode</description>\n<anyOf>[{\"type\": \"string\"}, {\"type\": \"number\"}]</anyOf>\n</parameter>\n<parameter>\n<name>payload</name>\n<type>object</type>\n<description>Payload</description>\n<properties>{\"enabled\": {\"type\": \"boolean\"}}</properties>\n<required>[\"enabled\"]</required>\n</parameter>\n<parameter>\n<name>tags</name>\n<type>array</type>\n<description>Tags</description>\n<items>{\"type\": \"string\"}</items>\n</parameter>\n<$defs>{\"shared\": {\"type\": \"string\"}}</$defs>\n<required>[\"query\"]</required>\n</parameters>\n</function>\n</tools>\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n<tool_call>\n<function=example_function_name>\n<parameter=example_parameter_1>\nvalue_1\n</parameter>\n<parameter=example_parameter_2>\nThis is the value for the second parameter\nthat can span\nmultiple lines\n</parameter>\n</function>\n</tool_call>\n\n<IMPORTANT>\nReminder:\n- Function calls MUST follow the specified format: an inner <function=...></function> block must be nested within <tool_call></tool_call> XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n</IMPORTANT><|im_end|>\n<|im_start|>user\ngo<|im_end|>\n<|im_start|>assistant\n<think></think>\nok<|im_end|>\n<|im_start|>user\nmore<|im_end|>\n<|im_start|>assistant\n<think>\n",
+ "history content with think pair": "<|im_start|>system\n<|im_end|>\n<|im_start|>user\nu1<|im_end|>\n<|im_start|>assistant\n<think></think>visible<|im_end|>\n<|im_start|>user\nu2<|im_end|>\n<|im_start|>assistant\n<think>kept</think>tail<|im_end|>\n<|im_start|>assistant\n<think>\n",
+ "assistant open think only": "<|im_start|>system\n<|im_end|>\n<|im_start|>user\ngo<|im_end|>\n<|im_start|>assistant\n<think>unclosed reasoning<|im_end|>\n<|im_start|>user\nagain<|im_end|>\n<|im_start|>assistant\n<think>\n",
+ "assistant multiple think pairs": "<|im_start|>system\n<|im_end|>\n<|im_start|>user\ngo<|im_end|>\n<|im_start|>assistant\n<think></think>end<|im_end|>\n<|im_start|>user\nagain<|im_end|>\n<|im_start|>assistant\n<think>\n",
+ "tool response with think markers": "<|im_start|>system\n<|im_end|>\n<|im_start|>user\ngo<|im_end|>\n<|im_start|>assistant\n<think></think>\n<tool_call>\n<function=f>\n</function>\n</tool_call>\n<|im_end|>\n<|im_start|>user\n<tool_response>\n<think>from tool</think>result\n</tool_response>\n<|im_end|>\n<|im_start|>user\nnext<|im_end|>\n<|im_start|>assistant\n<think>\n",
+ "user content with think markers": "<|im_start|>system\n<|im_end|>\n<|im_start|>user\n<think>user wrote this</think>question<|im_end|>\n<|im_start|>assistant\n<think>\n",
+ "content with im_start markers": "<|im_start|>system\n<|im_end|>\n<|im_start|>user\n<|im_start|>fake<|im_end|><|im_end|>\n<|im_start|>assistant\n<think></think><|im_end|>odd<|im_end|>\n<|im_start|>user\nagain<|im_end|>\n<|im_start|>assistant\n<think>\n",
+ "thinking field and content tags": "<|im_start|>system\n<|im_end|>\n<|im_start|>user\ngo<|im_end|>\n<|im_start|>assistant\n<think></think>body<|im_end|>\n<|im_start|>user\nagain<|im_end|>\n<|im_start|>assistant\n<think>\n",
+ "ends with assistant turn": "<|im_start|>system\n<|im_end|>\n<|im_start|>user\ngo<|im_end|>\n<|im_start|>assistant\n<think></think>partial<|im_end|>\n<|im_start|>assistant\n<think>\n",
+ "tool call content closing tag only": "<|im_start|>system\n<|im_end|>\n<|im_start|>user\ngo<|im_end|>\n<|im_start|>assistant\n</think>after\n<tool_call>\n<function=f>\n</function>\n</tool_call>\n<|im_end|>\n<|im_start|>assistant\n<think>\n",
+ "system tools think off round trip": "<|im_start|>system\nSys\n\n# Tools\n\nYou have access to the following functions:\n\n<tools>\n<function>\n<name>search_docs</name>\n<description>Search docs</description>\n<parameters>\n<parameter>\n<name>query</name>\n<type>string</type>\n<description>Search query</description>\n<enum>[\"api\", \"cli\"]</enum>\n</parameter>\n<parameter>\n<name>mode</name>\n<type>['string', 'null']</type>\n<description>Mode</description>\n<anyOf>[{\"type\": \"string\"}, {\"type\": \"number\"}]</anyOf>\n</parameter>\n<parameter>\n<name>payload</name>\n<type>object</type>\n<description>Payload</description>\n<properties>{\"enabled\": {\"type\": \"boolean\"}}</properties>\n<required>[\"enabled\"]</required>\n</parameter>\n<parameter>\n<name>tags</name>\n<type>array</type>\n<description>Tags</description>\n<items>{\"type\": \"string\"}</items>\n</parameter>\n<$defs>{\"shared\": {\"type\": \"string\"}}</$defs>\n<required>[\"query\"]</required>\n</parameters>\n</function>\n</tools>\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n<tool_call>\n<function=example_function_name>\n<parameter=example_parameter_1>\nvalue_1\n</parameter>\n<parameter=example_parameter_2>\nThis is the value for the second parameter\nthat can span\nmultiple lines\n</parameter>\n</function>\n</tool_call>\n\n<IMPORTANT>\nReminder:\n- Function calls MUST follow the specified format: an inner <function=...></function> block must be nested within <tool_call></tool_call> XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n</IMPORTANT><|im_end|>\n<|im_start|>user\ngo<|im_end|>\n<|im_start|>assistant\n<think></think>\n<tool_call>\n<function=search_docs>\n<parameter=query>\ncli\n</parameter>\n</function>\n</tool_call>\n<|im_end|>\n<|im_start|>user\n<tool_response>\nhit\n</tool_response>\n<|im_end|>\n<|im_start|>user\nsummarize<|im_end|>\n<|im_start|>assistant\n<think></think>",
+ "tool call null and numeric args": "<|im_start|>system\n<|im_end|>\n<|im_start|>user\ngo<|im_end|>\n<|im_start|>assistant\n<think></think>\n<tool_call>\n<function=f>\n<parameter=nothing>\nNone\n</parameter>\n<parameter=negative>\n-12\n</parameter>\n<parameter=big>\n9007199254740993\n</parameter>\n<parameter=fraction>\n0.125\n</parameter>\n</function>\n</tool_call>\n<|im_end|>\n<|im_start|>assistant\n<think>\n",
+ "tool call nested mixed container": "<|im_start|>system\n<|im_end|>\n<|im_start|>user\ngo<|im_end|>\n<|im_start|>assistant\n<think></think>\n<tool_call>\n<function=f>\n<parameter=deep>\n{\"b\": false, \"f\": 1.5, \"i\": 3, \"inner\": [1, {\"z\": true}], \"n\": null, \"s\": \"q\\\"uote\"}\n</parameter>\n</function>\n</tool_call>\n<|im_end|>\n<|im_start|>assistant\n<think>\n",
+ "tool param many unhandled keys": "<|im_start|>system\n# Tools\n\nYou have access to the following functions:\n\n<tools>\n<function>\n<name>q</name>\n<description>Query</description>\n<parameters>\n<parameter>\n<name>x</name>\n<type>string</type>\n<description>X</description>\n<anyOf>[{\"type\": \"null\"}]</anyOf>\n<items>{\"minimum\": 0, \"type\": \"number\"}</items>\n</parameter>\n</parameters>\n</function>\n</tools>\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n<tool_call>\n<function=example_function_name>\n<parameter=example_parameter_1>\nvalue_1\n</parameter>\n<parameter=example_parameter_2>\nThis is the value for the second parameter\nthat can span\nmultiple lines\n</parameter>\n</function>\n</tool_call>\n\n<IMPORTANT>\nReminder:\n- Function calls MUST follow the specified format: an inner <function=...></function> block must be nested within <tool_call></tool_call> XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n</IMPORTANT><|im_end|>\n<|im_start|>user\ngo<|im_end|>\n<|im_start|>assistant\n<think>\n",
+ "tool call content think pair only": "<|im_start|>system\n<|im_end|>\n<|im_start|>user\nu1<|im_end|>\n<|im_start|>assistant\n<think></think>\n<tool_call>\n<function=f>\n</function>\n</tool_call>\n<|im_end|>\n<|im_start|>user\nu2<|im_end|>\n<|im_start|>assistant\n<think>y</think>z\n<tool_call>\n<function=g>\n</function>\n</tool_call>\n<|im_end|>\n<|im_start|>assistant\n<think>\n",
+ "tool call quoted string arg": "<|im_start|>system\n<|im_end|>\n<|im_start|>user\ngo<|im_end|>\n<|im_start|>assistant\n<think></think>\n<tool_call>\n<function=f>\n<parameter=s>\nline\nbreak \"quoted\"\n</parameter>\n</function>\n</tool_call>\n<|im_end|>\n<|im_start|>assistant\n<think>\n",
+ "tool schema nested and items": "<|im_start|>system\n# Tools\n\nYou have access to the following functions:\n\n<tools>\n<function>\n<name>deep</name>\n<description>Nested schema</description>\n<parameters>\n<parameter>\n<name>outer</name>\n<type>object</type>\n<description>Outer object</description>\n<enum>[\"a\", \"b\"]</enum>\n<items>{\"type\": \"integer\"}</items>\n<properties>{\"inner\": {\"type\": \"string\", \"description\": \"Inner\"}, \"flag\": {\"type\": [\"boolean\", \"null\"]}}</properties>\n<required>[\"inner\"]</required>\n</parameter>\n<items>{\"type\": \"string\"}</items>\n<required>[\"outer\"]</required>\n</parameters>\n</function>\n</tools>\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n<tool_call>\n<function=example_function_name>\n<parameter=example_parameter_1>\nvalue_1\n</parameter>\n<parameter=example_parameter_2>\nThis is the value for the second parameter\nthat can span\nmultiple lines\n</parameter>\n</function>\n</tool_call>\n\n<IMPORTANT>\nReminder:\n- Function calls MUST follow the specified format: an inner <function=...></function> block must be nested within <tool_call></tool_call> XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n</IMPORTANT><|im_end|>\n<|im_start|>user\ngo<|im_end|>\n<|im_start|>assistant\n<think>\n",
+ "tool call unsigned numeric container": "<|im_start|>system\n<|im_end|>\n<|im_start|>user\ngo<|im_end|>\n<|im_start|>assistant\n<think></think>\n<tool_call>\n<function=f>\n<parameter=nums>\n{\"f32\": 1.5, \"i64\": -9, \"u\": 7, \"u8\": 255}\n</parameter>\n</function>\n</tool_call>\n<|im_end|>\n<|im_start|>assistant\n<think>\n",
+ "tool call whitespace content": "<|im_start|>system\n<|im_end|>\n<|im_start|>user\ngo<|im_end|>\n<|im_start|>assistant\n<think></think>\n<tool_call>\n<function=f>\n</function>\n</tool_call>\n<|im_end|>\n<|im_start|>assistant\n<think>\n",
+ "tool schema defs property map": "<|im_start|>system\n# Tools\n\nYou have access to the following functions:\n\n<tools>\n<function>\n<name>defs</name>\n<parameters>\n<parameter>\n<name>x</name>\n<type>string</type>\n</parameter>\n<$defs>{\"shared\": {\"type\": \"string\", \"description\": \"Shared\"}}</$defs>\n</parameters>\n</function>\n</tools>\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n<tool_call>\n<function=example_function_name>\n<parameter=example_parameter_1>\nvalue_1\n</parameter>\n<parameter=example_parameter_2>\nThis is the value for the second parameter\nthat can span\nmultiple lines\n</parameter>\n</function>\n</tool_call>\n\n<IMPORTANT>\nReminder:\n- Function calls MUST follow the specified format: an inner <function=...></function> block must be nested within <tool_call></tool_call> XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n</IMPORTANT><|im_end|>\n<|im_start|>user\ngo<|im_end|>\n<|im_start|>assistant\n<think>\n",
+ "tool schema defs rich property": "<|im_start|>system\n# Tools\n\nYou have access to the following functions:\n\n<tools>\n<function>\n<name>rich</name>\n<parameters>\n<parameter>\n<name>p</name>\n<type>string</type>\n</parameter>\n<$defs>{\"node\": {\"anyOf\": [{\"type\": \"string\"}, {\"type\": \"null\"}], \"type\": \"object\", \"items\": {\"type\": \"integer\"}, \"description\": \"Node\", \"enum\": [\"x\", \"y\"], \"properties\": {\"child\": {\"type\": \"string\"}}, \"required\": [\"child\"]}}</$defs>\n</parameters>\n</function>\n</tools>\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n<tool_call>\n<function=example_function_name>\n<parameter=example_parameter_1>\nvalue_1\n</parameter>\n<parameter=example_parameter_2>\nThis is the value for the second parameter\nthat can span\nmultiple lines\n</parameter>\n</function>\n</tool_call>\n\n<IMPORTANT>\nReminder:\n- Function calls MUST follow the specified format: an inner <function=...></function> block must be nested within <tool_call></tool_call> XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n</IMPORTANT><|im_end|>\n<|im_start|>user\ngo<|im_end|>\n<|im_start|>assistant\n<think>\n",
+ "tool schema items property type": "<|im_start|>system\n# Tools\n\nYou have access to the following functions:\n\n<tools>\n<function>\n<name>pt</name>\n<parameters>\n<parameter>\n<name>p</name>\n<type>string</type>\n</parameter>\n<items>[\"string\", \"null\"]</items>\n</parameters>\n</function>\n</tools>\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n<tool_call>\n<function=example_function_name>\n<parameter=example_parameter_1>\nvalue_1\n</parameter>\n<parameter=example_parameter_2>\nThis is the value for the second parameter\nthat can span\nmultiple lines\n</parameter>\n</function>\n</tool_call>\n\n<IMPORTANT>\nReminder:\n- Function calls MUST follow the specified format: an inner <function=...></function> block must be nested within <tool_call></tool_call> XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n</IMPORTANT><|im_end|>\n<|im_start|>user\ngo<|im_end|>\n<|im_start|>assistant\n<think>\n",
+ "tool schema nil defs map": "<|im_start|>system\n# Tools\n\nYou have access to the following functions:\n\n<tools>\n<function>\n<name>niltest</name>\n<parameters>\n<parameter>\n<name>p</name>\n<type>string</type>\n</parameter>\n<$defs>None</$defs>\n</parameters>\n</function>\n</tools>\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n<tool_call>\n<function=example_function_name>\n<parameter=example_parameter_1>\nvalue_1\n</parameter>\n<parameter=example_parameter_2>\nThis is the value for the second parameter\nthat can span\nmultiple lines\n</parameter>\n</function>\n</tool_call>\n\n<IMPORTANT>\nReminder:\n- Function calls MUST follow the specified format: an inner <function=...></function> block must be nested within <tool_call></tool_call> XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n</IMPORTANT><|im_end|>\n<|im_start|>user\ngo<|im_end|>\n<|im_start|>assistant\n<think>\n",
+ "tool call struct argument": "<|im_start|>system\n<|im_end|>\n<|im_start|>user\ngo<|im_end|>\n<|im_start|>assistant\n<think></think>\n<tool_call>\n<function=f>\n<parameter=custom>\n{\"a\": \"x\", \"b\": 2}\n</parameter>\n<parameter=list>\n[1, 2, 3]\n</parameter>\n</function>\n</tool_call>\n<|im_end|>\n<|im_start|>assistant\n<think>\n",
+ "tool schema nested nil properties": "<|im_start|>system\n# Tools\n\nYou have access to the following functions:\n\n<tools>\n<function>\n<name>nested</name>\n<parameters>\n<parameter>\n<name>p</name>\n<type>string</type>\n</parameter>\n<$defs>{\"node\": {\"type\": \"object\", \"required\": [\"q\"]}}</$defs>\n</parameters>\n</function>\n</tools>\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n<tool_call>\n<function=example_function_name>\n<parameter=example_parameter_1>\nvalue_1\n</parameter>\n<parameter=example_parameter_2>\nThis is the value for the second parameter\nthat can span\nmultiple lines\n</parameter>\n</function>\n</tool_call>\n\n<IMPORTANT>\nReminder:\n- Function calls MUST follow the specified format: an inner <function=...></function> block must be nested within <tool_call></tool_call> XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n</IMPORTANT><|im_end|>\n<|im_start|>user\ngo<|im_end|>\n<|im_start|>assistant\n<think>\n",
+}
+
+func TestNemotron3NanoRendererMatchesReferenceExtra(t *testing.T) {
+ verifyJinja2 := os.Getenv("VERIFY_JINJA2") != ""
+
+ renderer := &Nemotron3NanoRenderer{}
+ for _, tc := range nemotronExtraCases() {
+ t.Run(tc.name, func(t *testing.T) {
+ want, ok := nemotronExtraExpected[tc.name]
+ if !ok {
+ t.Fatalf("no expectation for %q: every case must be covered", tc.name)
+ }
+
+ got, err := renderer.Render(tc.messages, tc.tools, tc.think)
+ if err != nil {
+ t.Fatalf("Render() error = %v", err)
+ }
+ if diff := cmp.Diff(want, got); diff != "" {
+ t.Fatalf("renderer mismatch (-want +got):\n%s", diff)
+ }
+
+ if verifyJinja2 {
+ jinja2Output := renderNemotronWithJinja2(t, nemotron3NanoTemplate, tc.messages, tc.tools, tc.think)
+ if diff := cmp.Diff(want, jinja2Output); diff != "" {
+ t.Fatalf("template mismatch (-want +got):\n%s", diff)
+ }
+ }
+ })
+ }
+}
diff --git a/model/renderers/testdata/nemotron3nano_chat_template.jinja2 b/model/renderers/testdata/nemotron3nano_chat_template.jinja2
index 0f45006a8..6381c9df8 100644
--- a/model/renderers/testdata/nemotron3nano_chat_template.jinja2
+++ b/model/renderers/testdata/nemotron3nano_chat_template.jinja2
@@ -8,13 +8,12 @@
{%- endif %}
{%- endfor %}
{%- endif %}
-{% endmacro %}
+{%- endmacro -%}
{%- set enable_thinking = enable_thinking if enable_thinking is defined else True %}
{%- set reasoning_budget = reasoning_budget if reasoning_budget is defined else None %}
{%- set truncate_history_thinking = truncate_history_thinking if truncate_history_thinking is defined else True %}
-{%- set response_format = response_format if response_format is defined else None %}
-{# Scan messages for VLM thinking toggles to override enable_thinking #}
+{#- Scan messages for VLM thinking toggles to override enable_thinking -#}
{%- set toggle = namespace(enable=enable_thinking) %}
{%- for m in messages %}
{%- if m['role'] == 'user' or m['role'] == 'system' -%}
@@ -25,18 +24,28 @@
{%- elif '/no_think' in c -%}
{%- set toggle.enable = false -%}
{%- endif -%}
+ {%- else -%}
+ {%- for part in m['content'] -%}
+ {%- if part['type'] == 'text' -%}
+ {%- set c = part['text'] %}
+ {%- if '/think' in c.replace('</think>', '') -%}
+ {%- set toggle.enable = true -%}
+ {%- elif '/no_think' in c -%}
+ {%- set toggle.enable = false -%}
+ {%- endif -%}
+ {%- endif -%}
+ {%- endfor -%}
{%- endif -%}
{%- endif -%}
-{%- endfor %}
-
-{# Prepare message iteration similar to LM template #}
+{%- endfor -%}
+{#- Prepare message iteration similar to LM template -#}
{%- set ns = namespace(last_user_idx = -1) %}
{%- set loop_messages = messages %}
{%- for m in loop_messages %}
{%- if m["role"] == "user" %}
{%- set ns.last_user_idx = loop.index0 %}
{%- endif %}
-{%- endfor %}
+{%- endfor -%}
{%- if messages[0]["role"] == "system" %}
{%- set system_message = messages[0]["content"] %}
@@ -48,15 +57,14 @@
{%- if not tools is defined %}
{%- set tools = [] %}
{%- endif %}
-{# Recompute last_user_idx relative to loop_messages after handling system #}
+{#- Recompute last_user_idx relative to loop_messages after handling system -#}
{%- set ns = namespace(last_user_idx = -1) %}
{%- for m in loop_messages %}
{%- if m["role"] == "user" %}
{%- set ns.last_user_idx = loop.index0 %}
{%- endif %}
-{%- endfor %}
-
-{# System preamble with LM formatting, sanitize thinking toggles #}
+{%- endfor -%}
+{#- System preamble with LM formatting, sanitize thinking toggles -#}
{%- if system_message is defined %}
{%- set sys_content = system_message | string %}
{%- set sys_content = sys_content.replace('</think>', '<_end_think>').replace('/think', '').replace('/no_think', '').replace('<_end_think>', '</think>') %}
@@ -99,7 +107,7 @@
{{- '\n</parameter>' }}
{%- endfor %}
{%- endif %}
- {% set handled_keys = ['type', 'properties', 'required'] %}
+ {%- set handled_keys = ['type', 'properties', 'required'] %}
{{- render_extra_keys(tool.parameters, handled_keys) }}
{%- if tool.parameters is defined and tool.parameters.required is defined %}
{{- '\n<required>' ~ (tool.parameters.required | tojson | safe) ~ '</required>' }}
@@ -112,20 +120,18 @@
{{- "\n</tools>" }}
{{- '\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n<tool_call>\n<function=example_function_name>\n<parameter=example_parameter_1>\nvalue_1\n</parameter>\n<parameter=example_parameter_2>\nThis is the value for the second parameter\nthat can span\nmultiple lines\n</parameter>\n</function>\n</tool_call>\n\n<IMPORTANT>\nReminder:\n- Function calls MUST follow the specified format: an inner <function=...></function> block must be nested within <tool_call></tool_call> XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n</IMPORTANT>' }}
-{%- endif %}
-
+{%- endif -%}
{%- if system_message is defined %}
{{- '<|im_end|>\n' }}
{%- else %}
{%- if tools is iterable and tools | length > 0 %}
{{- '<|im_end|>\n' }}
{%- endif %}
-{%- endif %}
-
-{# Iterate conversation #}
+{%- endif -%}
+{#- Iterate conversation -#}
{%- for message in loop_messages %}
{%- if message.role == "assistant" %}
- {# Use LM assistant handling #}
+ {#- Use LM assistant handling -#}
{%- if message.reasoning_content is defined and message.reasoning_content is string and message.reasoning_content | trim | length > 0 %}
{%- set content = "<think>\n" ~ message.reasoning_content ~ "\n</think>\n" ~ (message.content | default('', true)) %}
{%- else %}
@@ -192,8 +198,54 @@
{%- endif %}
{%- elif message.role == "user" or message.role == "system" %}
{{- '<|im_start|>' + message.role + '\n' }}
- {%- set content = message.content | string %}
- {{- content }}
+ {#- Build VLM multimodal content when content is a sequence -#}
+ {%- if message.content is string -%}
+ {%- set content = (message.content | string) %}
+ {%- else -%}
+ {%- set text_ns = namespace(val='') -%}
+ {%- set mm_content = '' -%}
+ {%- set counters = namespace(images=0, videos=0, audios=0) -%}
+ {%- for part in message['content'] -%}
+ {%- if part['type'] == 'image' or part['type'] == 'image_url' -%}
+ {%- set counters.images = counters.images + 1 -%}
+ {%- elif part['type'] == 'video' or part['type'] == 'video_url' -%}
+ {%- set counters.videos = counters.videos + 1 -%}
+ {%- elif part['type'] == 'audio' or part['type'] == 'audio_url' -%}
+ {%- set counters.audios = counters.audios + 1 -%}
+ {%- elif part['type'] == 'text' -%}
+ {%- set text_ns.val = text_ns.val + part['text'] -%}
+ {%- endif -%}
+ {%- endfor -%}
+ {%- if '<image>' in text_ns.val -%}
+ {%- set counters.images = 0 -%}
+ {%- endif -%}
+ {%- if '<video>' in text_ns.val -%}
+ {%- set counters.videos = 0 -%}
+ {%- endif -%}
+ {%- if '<so_embedding>' in text_ns.val -%}
+ {%- set counters.audios = 0 -%}
+ {%- endif -%}
+ {%- if counters.images > 1 -%}
+ {%- set image_tags = namespace(tags=[]) -%}
+ {%- for i in range(counters.images) -%}
+ {%- set image_tags.tags = image_tags.tags + ['<image ' + (i + 1)|string + '><image>'] -%}
+ {%- endfor -%}
+ {%- set mm_content = ' '.join(image_tags.tags) + '\n' -%}
+ {%- elif counters.images == 1 -%}
+ {%- set mm_content = '<image>\n' -%}
+ {%- endif -%}
+ {%- set mm_content = mm_content + '<video>\n' * counters.videos -%}
+ {%- set mm_content = mm_content + '<so_embedding>\n' * counters.audios -%}
+ {%- set content = mm_content + text_ns.val.lstrip('\n') -%}
+ {%- endif -%}
+ {#- Sanitize thinking toggle directives from user/system content -#}
+ {%- set content = content.replace('</think>', '<_end_think>').replace('/think', '').replace('/no_think', '').replace('<_end_think>', '</think>') -%}
+ {%- set content = content | trim -%}
+ {%- if message.role == "user" and loop.index0 == ns.last_user_idx and reasoning_budget is not none -%}
+ {{- content + '\n\n{thinking token budget: ' + (reasoning_budget | string) + '}' -}}
+ {%- else -%}
+ {{- content -}}
+ {%- endif -%}
{{- '<|im_end|>\n' }}
{%- elif message.role == "tool" %}
{%- if loop.previtem and loop.previtem.role != "tool" %}
@@ -210,13 +262,12 @@
{%- else %}
{{- '<|im_start|>' + message.role + '\n' + message.content + '<|im_end|>\n' }}
{%- endif %}
-{%- endfor %}
-
-{# Generation prompt using computed thinking toggle #}
+{%- endfor -%}
+{#- Generation prompt using computed thinking toggle -#}
{%- if add_generation_prompt %}
{%- if toggle.enable %}
{{- '<|im_start|>assistant\n<think>\n' }}
{%- else %}
{{- '<|im_start|>assistant\n<think></think>' }}
{%- endif %}
-{%- endif %}
+{%- endif %}
\ No newline at end of file
diff --git a/server/images.go b/server/images.go
index e8493b14a..c5ff13380 100644
--- a/server/images.go
+++ b/server/images.go
@@ -455,7 +455,7 @@ func (m *Model) filterUnsupportedCapabilities(capabilities []model.Capability, m
return c == model.CapabilityAudio
})
}
- if isGemma4Renderer(m.Config.Renderer) && m.Config.ModelFormat == "safetensors" {
+ if suppressVisionCapability(m) {
capabilities = slices.DeleteFunc(capabilities, func(c model.Capability) bool {
return c == model.CapabilityVision
})
@@ -464,6 +464,16 @@ func (m *Model) filterUnsupportedCapabilities(capabilities []model.Capability, m
return capabilities
}
+func suppressVisionCapability(m *Model) bool {
+ if isGemma4Renderer(m.Config.Renderer) && m.Config.ModelFormat == "safetensors" {
+ return true
+ }
+
+ // The current MLX Nemotron path is text-only. Do not advertise vision for
+ // safetensors manifests until the runner can load and serve that modality.
+ return isNemotron3NanoSafetensors(m)
+}
+
func suppressAudioCapability(m *Model, arch string) bool {
if isGemma4Renderer(m.Config.Renderer) && m.Config.ModelFormat == "safetensors" {
return true
@@ -471,6 +481,9 @@ func suppressAudioCapability(m *Model, arch string) bool {
if m.Config.ModelFormat == "safetensors" && m.Config.Renderer == "glimmer" {
return true
}
+ if isNemotron3NanoSafetensors(m) {
+ return true
+ }
if arch == "nemotron_h_omni" ||
m.Config.ModelFamily == "nemotron_h_omni" ||
@@ -482,6 +495,18 @@ func suppressAudioCapability(m *Model, arch string) bool {
return false
}
+func isNemotron3NanoSafetensors(m *Model) bool {
+ return isNemotron3NanoSafetensorsConfig(m.Config)
+}
+
+func isNemotron3NanoSafetensorsConfig(cfg model.ConfigV2) bool {
+ return cfg.ModelFormat == "safetensors" &&
+ (cfg.Parser == "nemotron-3-nano" ||
+ cfg.Renderer == "nemotron-3-nano" ||
+ cfg.ModelFamily == "nemotron_h_omni" ||
+ slices.Contains(cfg.ModelFamilies, "nemotron_h_omni"))
+}
+
func projectorHasAudio(f *gguf.File) bool {
if f.KeyValue("has_audio_encoder").Bool() {
return true
diff --git a/server/images_test.go b/server/images_test.go
index 269098d21..ea10106d0 100644
--- a/server/images_test.go
+++ b/server/images_test.go
@@ -515,6 +515,19 @@ func TestModelCapabilities(t *testing.T) {
},
expectedCaps: []model.Capability{model.CapabilityCompletion, model.CapabilityVision},
},
+ {
+ name: "nemotron3 safetensors suppresses vision and audio but keeps thinking",
+ model: Model{
+ Config: model.ConfigV2{
+ ModelFormat: "safetensors",
+ Parser: "nemotron-3-nano",
+ Renderer: "nemotron-3-nano",
+ Capabilities: []string{"completion", "vision", "audio"},
+ },
+ Template: chatTemplate,
+ },
+ expectedCaps: []model.Capability{model.CapabilityCompletion, model.CapabilityTools, model.CapabilityThinking},
+ },
{
name: "gemma4 small safetensors suppresses vision and audio",
model: Model{
diff --git a/server/model_list_cache.go b/server/model_list_cache.go
index 6775382aa..9443a1576 100644
--- a/server/model_list_cache.go
+++ b/server/model_list_cache.go
@@ -391,21 +391,26 @@ func buildModelListSummary(name model.Name, mf *manifest.Manifest) (modelListSum
summary.Capabilities = appendModelListCapability(summary.Capabilities, model.CapabilityVision)
}
- if cfg.ModelFormat == "safetensors" && isGemma4Renderer(cfg.Renderer) {
- summary.Capabilities = slices.DeleteFunc(summary.Capabilities, func(c model.Capability) bool {
+ summary.Capabilities = filterUnsupportedModelListCapabilities(summary.Capabilities, cfg)
+
+ return summary, nil
+}
+
+func filterUnsupportedModelListCapabilities(capabilities []model.Capability, cfg model.ConfigV2) []model.Capability {
+ if cfg.ModelFormat == "safetensors" && (isGemma4Renderer(cfg.Renderer) || isNemotron3NanoSafetensorsConfig(cfg)) {
+ capabilities = slices.DeleteFunc(capabilities, func(c model.Capability) bool {
return c == model.CapabilityVision || c == model.CapabilityAudio
})
}
-
// Mirrors suppressAudioCapability in images.go so /api/tags and /api/show
// agree for safetensors models whose MLX runner serves vision but not audio.
if cfg.ModelFormat == "safetensors" && cfg.Renderer == "glimmer" {
- summary.Capabilities = slices.DeleteFunc(summary.Capabilities, func(c model.Capability) bool {
+ capabilities = slices.DeleteFunc(capabilities, func(c model.Capability) bool {
return c == model.CapabilityAudio
})
}
- return summary, nil
+ return capabilities
}
func readModelListConfig(mf *manifest.Manifest) (model.ConfigV2, error) {
diff --git a/server/model_list_cache_test.go b/server/model_list_cache_test.go
index 047ecd813..f9fb960cd 100644
--- a/server/model_list_cache_test.go
+++ b/server/model_list_cache_test.go
@@ -70,6 +70,36 @@ func TestModelListCacheHydratesSummary(t *testing.T) {
}
}
+func TestModelListCacheSuppressesNemotronSafetensorsMedia(t *testing.T) {
+ caps := []model.Capability{
+ model.CapabilityCompletion,
+ model.CapabilityTools,
+ model.CapabilityThinking,
+ model.CapabilityVision,
+ model.CapabilityAudio,
+ }
+ got := filterUnsupportedModelListCapabilities(caps, model.ConfigV2{
+ ModelFormat: "safetensors",
+ Renderer: "nemotron-3-nano",
+ Parser: "nemotron-3-nano",
+ })
+
+ for _, capability := range []model.Capability{
+ model.CapabilityCompletion,
+ model.CapabilityTools,
+ model.CapabilityThinking,
+ } {
+ if !slices.Contains(got, capability) {
+ t.Fatalf("capabilities = %v, want %s", got, capability)
+ }
+ }
+ for _, capability := range []model.Capability{model.CapabilityVision, model.CapabilityAudio} {
+ if slices.Contains(got, capability) {
+ t.Fatalf("capabilities = %v, did not expect %s", got, capability)
+ }
+ }
+}
+
func TestModelListCacheRefreshUpdatesEntry(t *testing.T) {
gin.SetMode(gin.TestMode)
setTestHome(t, t.TempDir())
diff --git a/x/create/client/create.go b/x/create/client/create.go
index c391fdeb0..8463766d9 100644
--- a/x/create/client/create.go
+++ b/x/create/client/create.go
@@ -186,6 +186,7 @@ func CreateModel(opts CreateOptions, p *progress.Progress) error {
var draftLayers []create.LayerInfo
var err error
+
if hasDraft {
draftLayers, err = create.CreateDraftLayers(
opts.Modelfile.Draft,
@@ -517,6 +518,7 @@ func detectCapabilities(modelDir string) modelCapabilities {
VisionConfig *map[string]any `json:"vision_config"`
AudioConfig *map[string]any `json:"audio_config"`
HasVision bool `json:"has_vision"`
+ SoundConfig *map[string]any `json:"sound_config"`
}
if data, err := os.ReadFile(filepath.Join(modelDir, "config.json")); err == nil {
_ = json.Unmarshal(data, &cfg)
@@ -524,7 +526,7 @@ func detectCapabilities(modelDir string) modelCapabilities {
return modelCapabilities{
vision: cfg.VisionConfig != nil || cfg.HasVision,
- audio: cfg.AudioConfig != nil,
+ audio: cfg.AudioConfig != nil || cfg.SoundConfig != nil,
thinking: chatTemplateHasThinkingSupport(readChatTemplate(modelDir)) ||
alwaysSupportsThinking(cfg.Architectures, cfg.ModelType),
}
@@ -610,72 +612,57 @@ func getParserName(modelDir string) string {
var cfg struct {
Architectures []string `json:"architectures"`
ModelType string `json:"model_type"`
+ LLMConfig struct {
+ ModelType string `json:"model_type"`
+ } `json:"llm_config"`
}
if err := json.Unmarshal(data, &cfg); err != nil {
return ""
}
- // Check architectures for known parsers
for _, arch := range cfg.Architectures {
- archLower := strings.ToLower(arch)
- if strings.HasPrefix(arch, "MuseGlimmer") {
- return "glimmer"
- }
- if strings.Contains(archLower, "laguna") {
- return lagunaRendererParserName(modelDir)
- }
- if strings.Contains(archLower, "cohere2moe") || strings.Contains(archLower, "cohere2_moe") {
- return "cohere"
- }
- if strings.Contains(archLower, "glm4") || strings.Contains(archLower, "glm-4") {
- return "glm-4.7"
- }
- if strings.Contains(archLower, "deepseek") {
- return "deepseek3"
- }
- if strings.Contains(archLower, "gemma4") {
- return "gemma4"
- }
- if isQwen35Family(archLower) {
- return "qwen3.5"
- }
- if strings.Contains(archLower, "qwen3") {
- return "qwen3"
+ if name := parserNameForIdentifier(modelDir, arch); name != "" {
+ return name
}
}
-
- // Also check model_type
- if cfg.ModelType != "" {
- typeLower := strings.ToLower(cfg.ModelType)
- if typeLower == "muse_glimmer" {
- return "glimmer"
- }
- if strings.Contains(typeLower, "laguna") {
- return lagunaRendererParserName(modelDir)
- }
- if strings.Contains(typeLower, "cohere2_moe") {
- return "cohere"
- }
- if strings.Contains(typeLower, "glm4") || strings.Contains(typeLower, "glm-4") {
- return "glm-4.7"
- }
- if strings.Contains(typeLower, "deepseek") {
- return "deepseek3"
- }
- if strings.Contains(typeLower, "gemma4") {
- return "gemma4"
- }
- if isQwen35Family(typeLower) {
- return "qwen3.5"
- }
- if strings.Contains(typeLower, "qwen3") {
- return "qwen3"
+ for _, modelType := range []string{cfg.ModelType, cfg.LLMConfig.ModelType} {
+ if name := parserNameForIdentifier(modelDir, modelType); name != "" {
+ return name
}
}
return ""
}
+func parserNameForIdentifier(modelDir, s string) string {
+ s = strings.ToLower(s)
+ switch {
+ case strings.HasPrefix(s, "museglimmer") || s == "muse_glimmer":
+ return "glimmer"
+ case strings.Contains(s, "laguna"):
+ return lagunaRendererParserName(modelDir)
+ case strings.Contains(s, "cohere2moe") || strings.Contains(s, "cohere2_moe"):
+ return "cohere"
+ case strings.Contains(s, "glm4") || strings.Contains(s, "glm-4"):
+ return "glm-4.7"
+ case strings.Contains(s, "deepseek"):
+ return "deepseek3"
+ case strings.Contains(s, "gemma4"):
+ return "gemma4"
+ case isQwen35Family(s):
+ return "qwen3.5"
+ case strings.Contains(s, "qwen3"):
+ return "qwen3"
+ // Nemotron-H publishes NemotronHForCausalLM for text and
+ // NemotronH_Nano_Omni_Reasoning_V3 for omni; model_type is nemotron_h,
+ // nemotron_h_moe, or the omni name. The two stems cover all of them.
+ case strings.Contains(s, "nemotronh") || strings.Contains(s, "nemotron_h"):
+ return "nemotron-3-nano"
+ default:
+ return ""
+ }
+}
+
// getRendererName returns the renderer name for a model based on its architecture.
// This reads the config.json from the model directory and determines the appropriate renderer.
func getRendererName(modelDir string) string {
@@ -688,68 +675,53 @@ func getRendererName(modelDir string) string {
var cfg struct {
Architectures []string `json:"architectures"`
ModelType string `json:"model_type"`
+ LLMConfig struct {
+ ModelType string `json:"model_type"`
+ } `json:"llm_config"`
}
if err := json.Unmarshal(data, &cfg); err != nil {
return ""
}
- // Check architectures for known renderers
for _, arch := range cfg.Architectures {
- archLower := strings.ToLower(arch)
- if strings.HasPrefix(arch, "MuseGlimmer") {
- return "glimmer"
- }
- if strings.Contains(archLower, "laguna") {
- return lagunaRendererParserName(modelDir)
- }
- if strings.Contains(archLower, "cohere2moe") || strings.Contains(archLower, "cohere2_moe") {
- return "cohere"
- }
- if strings.Contains(archLower, "gemma4") {
- return "gemma4"
- }
- if strings.Contains(archLower, "glm4") || strings.Contains(archLower, "glm-4") {
- return "glm-4.7"
- }
- if strings.Contains(archLower, "deepseek") {
- return "deepseek3"
- }
- if isQwen35Family(archLower) {
- return "qwen3.5"
- }
- if strings.Contains(archLower, "qwen3") {
- return "qwen3-coder"
+ if name := rendererNameForIdentifier(modelDir, arch); name != "" {
+ return name
}
}
-
- // Also check model_type
- if cfg.ModelType != "" {
- typeLower := strings.ToLower(cfg.ModelType)
- if typeLower == "muse_glimmer" {
- return "glimmer"
- }
- if strings.Contains(typeLower, "laguna") {
- return lagunaRendererParserName(modelDir)
- }
- if strings.Contains(typeLower, "cohere2_moe") {
- return "cohere"
- }
- if strings.Contains(typeLower, "gemma4") {
- return "gemma4"
- }
- if strings.Contains(typeLower, "glm4") || strings.Contains(typeLower, "glm-4") {
- return "glm-4.7"
- }
- if strings.Contains(typeLower, "deepseek") {
- return "deepseek3"
- }
- if isQwen35Family(typeLower) {
- return "qwen3.5"
- }
- if strings.Contains(typeLower, "qwen3") {
- return "qwen3-coder"
+ for _, modelType := range []string{cfg.ModelType, cfg.LLMConfig.ModelType} {
+ if name := rendererNameForIdentifier(modelDir, modelType); name != "" {
+ return name
}
}
return ""
}
+
+func rendererNameForIdentifier(modelDir, s string) string {
+ s = strings.ToLower(s)
+ switch {
+ case strings.HasPrefix(s, "museglimmer") || s == "muse_glimmer":
+ return "glimmer"
+ case strings.Contains(s, "laguna"):
+ return lagunaRendererParserName(modelDir)
+ case strings.Contains(s, "cohere2moe") || strings.Contains(s, "cohere2_moe"):
+ return "cohere"
+ case strings.Contains(s, "gemma4"):
+ return "gemma4"
+ case strings.Contains(s, "glm4") || strings.Contains(s, "glm-4"):
+ return "glm-4.7"
+ case strings.Contains(s, "deepseek"):
+ return "deepseek3"
+ case isQwen35Family(s):
+ return "qwen3.5"
+ case strings.Contains(s, "qwen3"):
+ return "qwen3-coder"
+ // Nemotron-H publishes NemotronHForCausalLM for text and
+ // NemotronH_Nano_Omni_Reasoning_V3 for omni; model_type is nemotron_h,
+ // nemotron_h_moe, or the omni name. The two stems cover all of them.
+ case strings.Contains(s, "nemotronh") || strings.Contains(s, "nemotron_h"):
+ return "nemotron-3-nano"
+ default:
+ return ""
+ }
+}
diff --git a/x/create/client/create_test.go b/x/create/client/create_test.go
index 50f54d316..67c0d8530 100644
--- a/x/create/client/create_test.go
+++ b/x/create/client/create_test.go
@@ -41,6 +41,30 @@ func TestModelfileConfig(t *testing.T) {
}
}
+func TestNemotronNanoOmniMetadataInference(t *testing.T) {
+ dir := t.TempDir()
+ config := `{
+ "architectures": ["NemotronH_Nano_Omni_Reasoning_V3"],
+ "model_type": "NemotronH_Nano_Omni_Reasoning_V3",
+ "vision_config": {"patch_size": 16},
+ "sound_config": {"model_type": "parakeet"},
+ "llm_config": {"model_type": "nemotron_h"}
+ }`
+ if err := os.WriteFile(filepath.Join(dir, "config.json"), []byte(config), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if got, want := getParserName(dir), "nemotron-3-nano"; got != want {
+ t.Fatalf("parser = %q, want %q", got, want)
+ }
+ if got, want := getRendererName(dir), "nemotron-3-nano"; got != want {
+ t.Fatalf("renderer = %q, want %q", got, want)
+ }
+ caps := inferSafetensorsCapabilities(dir, getParserName(dir))
+ if !slices.Equal(caps, []string{"completion", "vision", "audio", "tools", "thinking"}) {
+ t.Fatalf("capabilities = %v, want completion/vision/audio/tools/thinking", caps)
+ }
+}
+
func TestConfigFromModelfile(t *testing.T) {
modelfile, err := parser.ParseFile(strings.NewReader(`
FROM ./model
@@ -399,6 +423,15 @@ func TestInferSafetensorsCapabilities(t *testing.T) {
}`,
want: []string{"completion", "audio"},
},
+ {
+ name: "model with sound config",
+ configJSON: `{
+ "architectures": ["SomeSoundModel"],
+ "model_type": "other",
+ "sound_config": {"model_type": "parakeet"}
+ }`,
+ want: []string{"completion", "audio"},
+ },
{
name: "non-qwen conditional generation model",
configJSON: `{
@@ -766,6 +799,21 @@ func TestGetParserName(t *testing.T) {
configJSON: `{"architectures": ["MuseGlimmerForConditionalGeneration"], "model_type": "muse_glimmer"}`,
want: "glimmer",
},
+ {
+ name: "nemotron text architecture",
+ configJSON: `{"architectures": ["NemotronHForCausalLM"], "model_type": "nemotron_h"}`,
+ want: "nemotron-3-nano",
+ },
+ {
+ name: "nemotron omni architecture",
+ configJSON: `{"architectures": ["NemotronH_Nano_Omni_Reasoning_V3"], "model_type": "NemotronH_Nano_Omni_Reasoning_V3"}`,
+ want: "nemotron-3-nano",
+ },
+ {
+ name: "nemotron nested llm config",
+ configJSON: `{"model_type": "nemotron_h_omni", "llm_config": {"model_type": "nemotron_h"}}`,
+ want: "nemotron-3-nano",
+ },
{
name: "no config",
configJSON: `{}`,
@@ -826,6 +874,21 @@ func TestGetRendererName(t *testing.T) {
configJSON: `{"architectures": ["MuseGlimmerForConditionalGeneration"], "model_type": "muse_glimmer"}`,
want: "glimmer",
},
+ {
+ name: "nemotron text architecture",
+ configJSON: `{"architectures": ["NemotronHForCausalLM"], "model_type": "nemotron_h"}`,
+ want: "nemotron-3-nano",
+ },
+ {
+ name: "nemotron omni architecture",
+ configJSON: `{"architectures": ["NemotronH_Nano_Omni_Reasoning_V3"], "model_type": "NemotronH_Nano_Omni_Reasoning_V3"}`,
+ want: "nemotron-3-nano",
+ },
+ {
+ name: "nemotron nested llm config",
+ configJSON: `{"model_type": "nemotron_h_omni", "llm_config": {"model_type": "nemotron_h"}}`,
+ want: "nemotron-3-nano",
+ },
}
for _, tt := range tests {
diff --git a/x/create/create.go b/x/create/create.go
index 8ba6f3753..9940cb8cf 100644
--- a/x/create/create.go
+++ b/x/create/create.go
@@ -243,7 +243,8 @@ func isStackedExpertWeight(name string) bool {
// as gemma's bare "...layers.N.experts.gate_up_proj" (no .mlp/.moe prefix).
return strings.Contains(name, ".experts.") ||
strings.Contains(name, ".mlp.switch_mlp.") ||
- strings.Contains(name, ".mlp.shared_experts.")
+ strings.Contains(name, ".mlp.shared_experts.") ||
+ strings.Contains(name, ".mixer.shared_experts.")
}
// isRoutingGate reports the small MoE routing/gate weights that select the
@@ -251,6 +252,7 @@ func isStackedExpertWeight(name string) bool {
// are kept at source precision regardless of architecture.
func isRoutingGate(name string) bool {
return strings.HasSuffix(name, ".mlp.gate.weight") ||
+ strings.HasSuffix(name, ".mixer.gate.weight") ||
strings.HasSuffix(name, ".shared_expert_gate.weight") ||
strings.HasSuffix(name, ".router.proj.weight")
}
@@ -319,7 +321,7 @@ func GetTensorQuantization(name string, shape []int32, quantize string) string {
return quantNorm
}
-var expertLayerPrefixRegexp = regexp.MustCompile(`^(?:model\.language_model\.|language_model(?:\.model)?\.|model\.)?layers\.\d+$`)
+var expertLayerPrefixRegexp = regexp.MustCompile(`^(?:model\.language_model\.backbone\.|model\.language_model\.|language_model(?:\.model)?\.|language_model\.backbone\.|model\.|backbone\.|mtp\.)?layers\.\d+$`)
// ExpertGroupPrefix returns the group prefix for expert tensors that should be packed together.
// For example:
@@ -338,6 +340,8 @@ func ExpertGroupPrefix(tensorName string) string {
".mlp.shared_experts.",
".mlp.switch_mlp.",
".moe.experts.",
+ ".mixer.experts.",
+ ".mixer.shared_experts.",
} {
idx := strings.Index(tensorName, marker)
if idx == -1 {
@@ -490,6 +494,9 @@ var tensorImportTransformRegistry = map[string]tensorImportTransformFactory{
"Gemma4AssistantForCausalLM": newGemma4ImportTransform,
"Gemma4UnifiedAssistantForCausalLM": newGemma4ImportTransform,
"gemma4_unified_assistant": newGemma4ImportTransform,
+ "NemotronH_Nano_VL_V2": newNemotronHImportTransform,
+ "NemotronH_Nano_Omni_Reasoning_V3": newNemotronHImportTransform,
+ "NemotronHForCausalLM": newNemotronHImportTransform,
}
func newTensorImportTransform(inv Inventory) (quantizePolicy, error) {
diff --git a/x/create/create_test.go b/x/create/create_test.go
index 59e4dcbdf..609a92b8d 100644
--- a/x/create/create_test.go
+++ b/x/create/create_test.go
@@ -391,6 +391,30 @@ func TestExpertGroupPrefix(t *testing.T) {
{"language_model.model.layers.3.mlp.switch_mlp.up_proj.weight", "language_model.model.layers.3.mlp.switch_mlp"},
{"model.language_model.layers.4.mlp.switch_mlp.gate_proj.weight", "model.language_model.layers.4.mlp.switch_mlp"},
+ // Nemotron-style expert tensors (backbone.layers.N.mixer.experts.M)
+ {"backbone.layers.1.mixer.experts.0.down_proj.weight", "backbone.layers.1.mixer.experts"},
+ {"backbone.layers.2.mixer.experts.127.up_proj.weight", "backbone.layers.2.mixer.experts"},
+ {"language_model.backbone.layers.3.mixer.experts.42.down_proj.weight", "language_model.backbone.layers.3.mixer.experts"},
+ {"model.language_model.backbone.layers.4.mixer.experts.7.up_proj.weight", "model.language_model.backbone.layers.4.mixer.experts"},
+
+ // Nemotron-style shared expert tensors
+ {"backbone.layers.1.mixer.shared_experts.down_proj.weight", "backbone.layers.1.mixer.shared_experts"},
+ {"backbone.layers.2.mixer.shared_experts.up_proj.weight", "backbone.layers.2.mixer.shared_experts"},
+
+ // Nemotron routing gate is not an expert
+ {"backbone.layers.1.mixer.gate.weight", ""},
+
+ // MTP expert tensors (mtp.layers.N.mixer.experts.M)
+ {"mtp.layers.1.mixer.experts.0.up_proj.weight", "mtp.layers.1.mixer.experts"},
+ {"mtp.layers.1.mixer.experts.127.down_proj.weight", "mtp.layers.1.mixer.experts"},
+
+ // MTP shared expert tensors
+ {"mtp.layers.1.mixer.shared_experts.up_proj.weight", "mtp.layers.1.mixer.shared_experts"},
+ {"mtp.layers.1.mixer.shared_experts.down_proj.weight", "mtp.layers.1.mixer.shared_experts"},
+
+ // MTP routing gate is not an expert
+ {"mtp.layers.1.mixer.gate.weight", ""},
+
// Non-expert tensors should return empty string
{"model.layers.0.mlp.down_proj.weight", ""}, // dense layer, no experts
{"model.layers.1.mlp.gate.weight", ""}, // routing gate, not an expert
diff --git a/x/create/nemotron_h.go b/x/create/nemotron_h.go
new file mode 100644
index 000000000..c811577f6
--- /dev/null
+++ b/x/create/nemotron_h.go
@@ -0,0 +1,99 @@
+package create
+
+import (
+ "encoding/json"
+ "fmt"
+ "strings"
+)
+
+type nemotronHImportTransform struct {
+ numLayers int
+}
+
+func newNemotronHImportTransform(rawConfig json.RawMessage) (quantizePolicy, error) {
+ var cfg struct {
+ NumHiddenLayers int `json:"num_hidden_layers"`
+ LLMConfig struct {
+ NumHiddenLayers int `json:"num_hidden_layers"`
+ } `json:"llm_config"`
+ }
+ if err := json.Unmarshal(rawConfig, &cfg); err != nil {
+ return nil, fmt.Errorf("nemotron_h: parse config.json: %w", err)
+ }
+ numLayers := cfg.NumHiddenLayers
+ if numLayers == 0 {
+ numLayers = cfg.LLMConfig.NumHiddenLayers
+ }
+ return nemotronHImportTransform{numLayers: numLayers}, nil
+}
+
+func nemotronHIsUnsupportedModalityTensor(name string) bool {
+ return strings.HasPrefix(name, "vision_model.") ||
+ strings.HasPrefix(name, "mlp1.") ||
+ strings.HasPrefix(name, "sound_encoder.") ||
+ strings.HasPrefix(name, "sound_projection.")
+}
+
+func nemotronHShouldKeepBF16ForDirectNonAffine(name string) bool {
+ switch {
+ case strings.HasSuffix(name, ".mixer.gate.weight"):
+ return true
+ case strings.HasSuffix(name, ".mixer.conv1d.weight"):
+ return true
+ default:
+ return false
+ }
+}
+
+func nemotronHIsAttentionProjection(name string) bool {
+ return strings.HasSuffix(name, ".mixer.q_proj.weight") ||
+ strings.HasSuffix(name, ".mixer.k_proj.weight") ||
+ strings.HasSuffix(name, ".mixer.v_proj.weight") ||
+ strings.HasSuffix(name, ".mixer.o_proj.weight")
+}
+
+// promoteSensitive reports whether a sensitive tensor takes the 8-bit type.
+// Attention always does: few layers carry it, 4-bit attention degrades
+// structured output, and promoting all of it is free. Experts keep the
+// schedule, where the decode bandwidth saving is real.
+func (t nemotronHImportTransform) promoteSensitive(name string) bool {
+ if nemotronHIsAttentionProjection(name) {
+ return true
+ }
+ layerIdx := layerIndex(name)
+ return layerIdx < 0 || useMoreBits(layerIdx, t.numLayers)
+}
+
+func (t nemotronHImportTransform) quantizationType(name string, shape []int32, quantize string) string {
+ if nemotronHIsUnsupportedModalityTensor(name) || nemotronHShouldKeepBF16ForDirectNonAffine(name) {
+ return ""
+ }
+
+ quantNorm := normalizeQuantType(quantize)
+
+ // lm_head and token embeddings are sensitive but high-bandwidth;
+ // promote them to 8-bit in the requested quant family when the
+ // shape fits, otherwise keep them at source precision.
+ if strings.HasSuffix(name, "embeddings.weight") || strings.HasSuffix(name, "lm_head.weight") {
+ return promoteEmbedding(shape, quantNorm)
+ }
+
+ if quantNorm == "nvfp4" || quantNorm == "mxfp4" {
+ isSensitive := nemotronHIsAttentionProjection(name) ||
+ strings.HasSuffix(name, ".mixer.out_proj.weight") ||
+ strings.HasSuffix(name, ".mixer.down_proj.weight") ||
+ strings.Contains(name, ".mixer.experts.") && strings.HasSuffix(name, ".down_proj.weight") ||
+ strings.HasSuffix(name, ".mixer.shared_experts.down_proj.weight")
+ if isSensitive {
+ if isAligned(shape, "mxfp8") && t.promoteSensitive(name) {
+ return "mxfp8"
+ }
+ if isAligned(shape, quantNorm) {
+ return quantNorm
+ }
+ return ""
+ }
+ }
+
+ return GetTensorQuantization(name, shape, quantize)
+}
diff --git a/x/create/nemotron_h_test.go b/x/create/nemotron_h_test.go
new file mode 100644
index 000000000..bebd68feb
--- /dev/null
+++ b/x/create/nemotron_h_test.go
@@ -0,0 +1,118 @@
+package create
+
+import (
+ "encoding/json"
+ "slices"
+ "testing"
+)
+
+func TestNemotronHImportTransformRegistration(t *testing.T) {
+ inv := Inventory{
+ Config: sourceModelConfig{Architectures: []string{"NemotronH_Nano_Omni_Reasoning_V3"}},
+ RawConfig: json.RawMessage(`{"architectures":["NemotronH_Nano_Omni_Reasoning_V3"],"llm_config":{"num_hidden_layers":52}}`),
+ }
+
+ policy, err := newTensorImportTransform(inv)
+ if err != nil {
+ t.Fatalf("newTensorImportTransform() error = %v", err)
+ }
+ transform, ok := policy.(nemotronHImportTransform)
+ if !ok {
+ t.Fatalf("newTensorImportTransform() = %T, want nemotronHImportTransform", policy)
+ }
+ if transform.numLayers != 52 {
+ t.Fatalf("numLayers = %d, want 52", transform.numLayers)
+ }
+}
+
+func TestNemotronHPlanKeepsUnsupportedModalitiesAtSourcePrecision(t *testing.T) {
+ transform := nemotronHImportTransform{numLayers: 52}
+ inv := Inventory{Dir: "test", Tensors: map[string]SourceTensor{
+ "language_model.backbone.embeddings.weight": {Name: "language_model.backbone.embeddings.weight", Dtype: "BF16", Shape: []int32{128, 128}},
+ "language_model.backbone.layers.0.mixer.in_proj.weight": {Name: "language_model.backbone.layers.0.mixer.in_proj.weight", Dtype: "BF16", Shape: []int32{128, 128}},
+ "vision_model.radio_model.model.patch_generator.proj.weight": {Name: "vision_model.radio_model.model.patch_generator.proj.weight", Dtype: "BF16", Shape: []int32{128, 128}},
+ "mlp1.0.weight": {Name: "mlp1.0.weight", Dtype: "BF16", Shape: []int32{128, 128}},
+ "sound_encoder.encoder.layers.0.self_attn.q_proj.weight": {Name: "sound_encoder.encoder.layers.0.self_attn.q_proj.weight", Dtype: "BF16", Shape: []int32{128, 128}},
+ "sound_projection.adapter.weight": {Name: "sound_projection.adapter.weight", Dtype: "BF16", Shape: []int32{128, 128}},
+ }}
+
+ specs, err := Plan(inv, Classification{Kind: SourceFloat, Quantize: "nvfp4"}, transform)
+ if err != nil {
+ t.Fatalf("Plan() error = %v", err)
+ }
+
+ got := specNames(specs)
+ want := []string{
+ "language_model.backbone.embeddings.weight",
+ "language_model.backbone.layers.0.mixer.in_proj.weight",
+ "mlp1.0.weight",
+ "sound_encoder.encoder.layers.0.self_attn.q_proj.weight",
+ "sound_projection.adapter.weight",
+ "vision_model.radio_model.model.patch_generator.proj.weight",
+ }
+ if !slices.Equal(got, want) {
+ t.Fatalf("spec names = %v, want %v", got, want)
+ }
+
+ for _, name := range []string{
+ "mlp1.0.weight",
+ "sound_encoder.encoder.layers.0.self_attn.q_proj.weight",
+ "sound_projection.adapter.weight",
+ "vision_model.radio_model.model.patch_generator.proj.weight",
+ } {
+ spec, ok := specByName(specs, name)
+ if !ok {
+ t.Fatalf("missing spec %s", name)
+ }
+ if got := spec.Tensors[0].Quantize; got != "" {
+ t.Fatalf("%s quantize = %q, want source precision", name, got)
+ }
+ }
+}
+
+func TestNemotronHImportTransformQuantizationPolicy(t *testing.T) {
+ transform := nemotronHImportTransform{numLayers: 52}
+
+ tests := []struct {
+ name string
+ tensor string
+ shape []int32
+ quantize string
+ want string
+ }{
+ {"mamba in_proj nvfp4", "language_model.backbone.layers.0.mixer.in_proj.weight", []int32{96, 32}, "nvfp4", "nvfp4"},
+ {"mamba out_proj promoted", "language_model.backbone.layers.0.mixer.out_proj.weight", []int32{32, 32}, "nvfp4", "mxfp8"},
+ {"attention v_proj promoted", "language_model.backbone.layers.0.mixer.v_proj.weight", []int32{32, 32}, "nvfp4", "mxfp8"},
+ {"attention o_proj promoted", "language_model.backbone.layers.0.mixer.o_proj.weight", []int32{32, 32}, "nvfp4", "mxfp8"},
+ {"attention o_proj mxfp8", "language_model.backbone.layers.1.mixer.o_proj.weight", []int32{32, 32}, "mxfp8", "mxfp8"},
+ {"expert up_proj nvfp4", "language_model.backbone.layers.2.mixer.experts.1.up_proj.weight", []int32{64, 32}, "nvfp4", "nvfp4"},
+ {"expert down_proj promoted", "language_model.backbone.layers.2.mixer.experts.1.down_proj.weight", []int32{32, 32}, "nvfp4", "mxfp8"},
+ {"shared expert down_proj promoted", "language_model.backbone.layers.2.mixer.shared_experts.down_proj.weight", []int32{32, 32}, "nvfp4", "mxfp8"},
+ {"shared expert down_proj mxfp8", "language_model.backbone.layers.2.mixer.shared_experts.down_proj.weight", []int32{32, 64}, "mxfp8", "mxfp8"},
+ {"late dense down_proj promoted", "language_model.backbone.layers.51.mixer.down_proj.weight", []int32{32, 32}, "nvfp4", "mxfp8"},
+ {"middle dense down_proj stays nvfp4", "language_model.backbone.layers.16.mixer.down_proj.weight", []int32{32, 32}, "nvfp4", "nvfp4"},
+ {"router gate kept bf16", "language_model.backbone.layers.2.mixer.gate.weight", []int32{8, 32}, "nvfp4", ""},
+ {"conv kept bf16", "language_model.backbone.layers.0.mixer.conv1d.weight", []int32{96, 32}, "nvfp4", ""},
+ {"embedding promoted to mxfp8", "language_model.backbone.embeddings.weight", []int32{4096, 32}, "mxfp8", "mxfp8"},
+ {"embedding promoted to mxfp8 from nvfp4", "language_model.backbone.embeddings.weight", []int32{4096, 32}, "nvfp4", "mxfp8"},
+ {"embedding promoted to int8 from int4", "language_model.backbone.embeddings.weight", []int32{4096, 64}, "int4", "int8"},
+ {"embedding promoted to int8", "language_model.backbone.embeddings.weight", []int32{4096, 64}, "int8", "int8"},
+ {"embedding unaligned kept bf16", "language_model.backbone.embeddings.weight", []int32{4096, 31}, "mxfp8", ""},
+ {"lm head promoted to mxfp8", "language_model.lm_head.weight", []int32{4096, 32}, "nvfp4", "mxfp8"},
+ {"lm head promoted to int8 from int4", "language_model.lm_head.weight", []int32{4096, 64}, "int4", "int8"},
+ {"lm head promoted to int8", "language_model.lm_head.weight", []int32{4096, 64}, "int8", "int8"},
+ {"lm head unaligned kept bf16", "language_model.lm_head.weight", []int32{4096, 31}, "nvfp4", ""},
+ {"vision kept bf16", "vision_model.radio_model.model.patch_generator.proj.weight", []int32{32, 32}, "nvfp4", ""},
+ {"vision projector kept bf16", "mlp1.0.weight", []int32{32, 32}, "nvfp4", ""},
+ {"sound encoder kept bf16", "sound_encoder.encoder.layers.0.self_attn.q_proj.weight", []int32{32, 32}, "nvfp4", ""},
+ {"sound projector kept bf16", "sound_projection.adapter.weight", []int32{32, 32}, "nvfp4", ""},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ if got := transform.quantizationType(tt.tensor, tt.shape, tt.quantize); got != tt.want {
+ t.Fatalf("quantizationType(%q, %v, %q) = %q, want %q", tt.tensor, tt.shape, tt.quantize, got, tt.want)
+ }
+ })
+ }
+}
diff --git a/x/mlxrunner/cache_trie.go b/x/mlxrunner/cache_trie.go
index 2a456bf77..c312af601 100644
--- a/x/mlxrunner/cache_trie.go
+++ b/x/mlxrunner/cache_trie.go
@@ -84,9 +84,22 @@ func (n *trieNode) hasSnapshots() bool {
return slices.ContainsFunc(n.snapshots, func(s cache.Snapshot) bool { return s != nil })
}
-// hasAllSnapshots returns true if every layer has snapshot data.
-func (n *trieNode) hasAllSnapshots() bool {
- return len(n.snapshots) > 0 && !slices.Contains(n.snapshots, nil)
+// hasAllSnapshots reports whether every stateful layer has snapshot data.
+// Stateless layers have a nil cache and never snapshot, so requiring one from
+// them would report every node as incompletely paged out.
+func hasAllSnapshots(n *trieNode, caches []cache.Cache) bool {
+ if len(n.snapshots) == 0 {
+ return false
+ }
+ for i, c := range caches {
+ if c == nil {
+ continue
+ }
+ if i >= len(n.snapshots) || n.snapshots[i] == nil {
+ return false
+ }
+ }
+ return true
}
// findBestMatch walks the trie matching input tokens, returning the path of
@@ -216,7 +229,7 @@ func splitNode(node *trieNode, at int, caches []cache.Cache, counter *int64) *tr
parentSnaps := make([]cache.Snapshot, len(oldSnaps))
childSnaps := make([]cache.Snapshot, len(oldSnaps))
for i, snap := range oldSnaps {
- if snap != nil {
+ if snap != nil && caches[i] != nil {
parentSnaps[i], childSnaps[i] = caches[i].Split(snap, newParent.endOffset)
}
}
@@ -259,6 +272,10 @@ func mergeWithChild(node *trieNode, caches []cache.Cache, counter *int64) {
childSnaps := child.swapSnapshots(nil, counter)
merged := make([]cache.Snapshot, len(caches))
for i := range caches {
+ if caches[i] == nil {
+ continue
+ }
+
var ps, cs cache.Snapshot
if nodeSnaps != nil {
ps = nodeSnaps[i]
diff --git a/x/mlxrunner/imports.go b/x/mlxrunner/imports.go
index 8761a391c..5f2cc4cb9 100644
--- a/x/mlxrunner/imports.go
+++ b/x/mlxrunner/imports.go
@@ -9,6 +9,7 @@ import (
_ "github.com/ollama/ollama/x/models/glm4_moe_lite"
_ "github.com/ollama/ollama/x/models/laguna"
_ "github.com/ollama/ollama/x/models/llama"
+ _ "github.com/ollama/ollama/x/models/nemotron_h"
_ "github.com/ollama/ollama/x/models/qwen3"
_ "github.com/ollama/ollama/x/models/qwen3_5"
_ "github.com/ollama/ollama/x/models/qwen3_5_moe"
diff --git a/x/mlxrunner/mlx/act.go b/x/mlxrunner/mlx/act.go
index deb1d5a75..267e9ce63 100644
--- a/x/mlxrunner/mlx/act.go
+++ b/x/mlxrunner/mlx/act.go
@@ -45,6 +45,17 @@ var SiLU = Compile1(
Shapeless(),
)
+// ReLUSquared returns relu(x)^2 as a fused kernel.
+var ReLUSquared = Compile1(
+ "ReLUSquared",
+ func(x *Array) *Array {
+ zero := FromValue[float32](0).AsType(x.DType())
+ x = Maximum(x, zero)
+ return x.Multiply(x)
+ },
+ Shapeless(),
+)
+
// SoftplusF32 returns softplus(x) computed in float32 precision and cast back
// to x's original dtype, as a fused kernel. Matches the laguna attention
// output-gate formula: softplus(cast_f32(x)).cast(orig_dtype).
diff --git a/x/mlxrunner/mlx/act_test.go b/x/mlxrunner/mlx/act_test.go
index 90d4fc4ba..e3c39891f 100644
--- a/x/mlxrunner/mlx/act_test.go
+++ b/x/mlxrunner/mlx/act_test.go
@@ -97,3 +97,26 @@ func benchmarkGELU(b *testing.B, fn func(*Array) *Array) {
b.Fatal(err)
}
}
+
+func TestReLUSquared(t *testing.T) {
+ var got []float32
+ withMLXThread(t, func() {
+ x := FromValues([]float32{-2, -0, 0.5, 2}, 4)
+ Pin(x)
+ defer Unpin(x)
+
+ y := ReLUSquared(x)
+ Eval(y)
+ got = append(got, y.Floats()...)
+ })
+
+ want := []float32{0, 0, 0.25, 4}
+ if len(got) != len(want) {
+ t.Fatalf("got %d values, want %d", len(got), len(want))
+ }
+ for i, v := range got {
+ if v != want[i] {
+ t.Errorf("got[%d]=%v want %v", i, v, want[i])
+ }
+ }
+}
diff --git a/x/mlxrunner/mlx/depthwise_conv.go b/x/mlxrunner/mlx/depthwise_conv.go
index d92cd30f7..12df18c9f 100644
--- a/x/mlxrunner/mlx/depthwise_conv.go
+++ b/x/mlxrunner/mlx/depthwise_conv.go
@@ -24,7 +24,10 @@ for (int i = 0; i < K; ++i) {
acc += static_cast<float>(x[in_base + i * C]) * static_cast<float>(w[c * K + i]);
}
+// The graph path is Add(conv(x, w), bias), so it rounds twice. Folding the
+// bias into the float accumulator would round once and drift by an ULP.
InT conv_out = static_cast<InT>(acc);
+conv_out = static_cast<InT>(static_cast<float>(conv_out) + DEPTHWISE_CONV_BIAS(c));
InT sigmoid = stable_sigmoid(conv_out);
out[elem] = static_cast<InT>(conv_out * sigmoid);
`
@@ -37,31 +40,45 @@ T stable_sigmoid(T x) {
}
`
-var depthwiseConvSiLU = &gpuKernel{
- name: "depthwise_conv_silu",
- inputs: []string{"x", "w", "dims"},
- outputs: []string{"out"},
- metal: gpuSource{
- source: depthwiseConvSiLUMetalSource,
- header: depthwiseConvSiLUMetalHeader,
- },
- fallback: func(launch gpuLaunch) []*Array {
- return []*Array{depthwiseConvSiLUGraph(launch.inputs[0], launch.inputs[1])}
- },
-}
+var (
+ depthwiseConvSiLU = &gpuKernel{
+ name: "depthwise_conv_silu",
+ inputs: []string{"x", "w", "dims"},
+ outputs: []string{"out"},
+ metal: gpuSource{
+ source: depthwiseConvSiLUMetalSource,
+ header: depthwiseConvSiLUMetalHeader + "#define DEPTHWISE_CONV_BIAS(c) 0.0f\n",
+ },
+ fallback: func(launch gpuLaunch) []*Array {
+ return []*Array{depthwiseConvSiLUGraph(launch.inputs[0], launch.inputs[1], nil)}
+ },
+ }
+ depthwiseConvSiLUBias = &gpuKernel{
+ name: "depthwise_conv_silu_bias",
+ inputs: []string{"x", "w", "bias", "dims"},
+ outputs: []string{"out"},
+ metal: gpuSource{
+ source: depthwiseConvSiLUMetalSource,
+ header: depthwiseConvSiLUMetalHeader + "#define DEPTHWISE_CONV_BIAS(c) static_cast<float>(bias[c])\n",
+ },
+ fallback: func(launch gpuLaunch) []*Array {
+ in := launch.inputs
+ return []*Array{depthwiseConvSiLUGraph(in[0], in[1], in[2])}
+ },
+ }
+)
-func depthwiseConvSiLUGraph(x, w *Array) *Array {
+func depthwiseConvSiLUGraph(x, w, bias *Array) *Array {
Cdim, K := int32(w.Dim(0)), int32(w.Dim(1))
- return SiLU(Conv1d(x, Reshape(w, Cdim, K, 1), nil, 1, 0, 1, Cdim))
+ return SiLU(Conv1d(x, Reshape(w, Cdim, K, 1), bias, 1, 0, 1, Cdim))
}
// DepthwiseConvSiLU computes SiLU of a valid depthwise conv: x
// [B, T+K-1, C] and w [C, K] give [B, T, C], each output reading the K
-// trailing input rows starting at its own index. Inputs that fit the fused
-// kernel's contract run there; anything else runs the same computation as
-// graph ops. The accumulator is rounded to the input dtype before the
-// activation so the result matches SiLU applied to the graph conv's output.
-func DepthwiseConvSiLU(x, w *Array, outLen int) *Array {
+// trailing input rows starting at its own index. bias, when non-nil, is [C].
+// Inputs that fit the fused kernel's contract run there; anything else runs
+// the same computation as graph ops, bit for bit.
+func DepthwiseConvSiLU(x, w, bias *Array, outLen int) *Array {
if x == nil || w == nil || x.NumDims() != 3 || w.NumDims() != 2 {
panic("mlx.DepthwiseConvSiLU: need x [B, T+K-1, C] and w [C, K]")
}
@@ -69,12 +86,24 @@ func DepthwiseConvSiLU(x, w *Array, outLen int) *Array {
if w.Dim(0) != Cdim || K <= 0 || x.Dim(1) != outLen+K-1 {
panic(fmt.Sprintf("mlx.DepthwiseConvSiLU: shapes x %v, w %v do not fit outLen %d", x.Dims(), w.Dims(), outLen))
}
- if x.DType() != w.DType() || (x.DType() != DTypeBFloat16 && x.DType() != DTypeFloat32) {
- return depthwiseConvSiLUGraph(x, w)
+ if bias != nil && (bias.NumDims() != 1 || bias.Dim(0) != Cdim) {
+ panic(fmt.Sprintf("mlx.DepthwiseConvSiLU: bias %v does not match %d channels", bias.Dims(), Cdim))
+ }
+ if x.DType() != w.DType() || (x.DType() != DTypeBFloat16 && x.DType() != DTypeFloat32) ||
+ (bias != nil && bias.DType() != x.DType()) {
+ return depthwiseConvSiLUGraph(x, w, bias)
+ }
+
+ kernel := depthwiseConvSiLU
+ inputs := []*Array{x, w}
+ if bias != nil {
+ kernel = depthwiseConvSiLUBias
+ inputs = append(inputs, bias)
}
+ inputs = append(inputs, NewArrayInt32([]int32{int32(B), int32(outLen)}, []int32{2}))
total := B * outLen * Cdim
- outs := depthwiseConvSiLU.run(gpuLaunch{
+ outs := kernel.run(gpuLaunch{
dtypes: []gpuDTypeArg{{"InT", x.DType()}},
ints: []gpuIntArg{{"C", Cdim}, {"K", K}},
outputs: []gpuOutputSpec{
@@ -82,7 +111,7 @@ func DepthwiseConvSiLU(x, w *Array, outLen int) *Array {
},
grid: [3]int{(total + 255) / 256 * 256, 1, 1},
threadGroup: [3]int{256, 1, 1},
- inputs: []*Array{x, w, NewArrayInt32([]int32{int32(B), int32(outLen)}, []int32{2})},
+ inputs: inputs,
})
return outs[0]
}
diff --git a/x/mlxrunner/mlx/depthwise_conv_test.go b/x/mlxrunner/mlx/depthwise_conv_test.go
index 61b39d6f1..bc409d1d9 100644
--- a/x/mlxrunner/mlx/depthwise_conv_test.go
+++ b/x/mlxrunner/mlx/depthwise_conv_test.go
@@ -7,31 +7,47 @@ import (
func TestDepthwiseConvSiLUMatchesGraph(t *testing.T) {
skipIfNoMLX(t)
+
+ // Collected, not reported inside the callback: a t.Fatal there calls
+ // runtime.Goexit, which the MLX worker cannot recover, so the job's result
+ // is never delivered and the test hangs until the binary timeout.
+ var mismatches []string
withMLXThread(t, func() {
- testDepthwiseConvSiLUMatchesGraph(t)
+ mismatches = depthwiseConvSiLUMismatches()
})
+ for _, m := range mismatches {
+ t.Error(m)
+ }
}
-func testDepthwiseConvSiLUMatchesGraph(t *testing.T) {
+func depthwiseConvSiLUMismatches() []string {
+ var mismatches []string
for _, dtype := range []DType{DTypeBFloat16, DTypeFloat32} {
- for _, shape := range []struct{ B, T, C, K int }{
- {1, 1, 64, 4},
- {1, 4, 64, 4},
- {1, 11, 96, 4},
- {1, 64, 64, 4},
- {1, 333, 64, 4},
- {3, 7, 64, 4},
- {2, 5, 32, 2},
- } {
- name := fmt.Sprintf("%v_b%d_t%d_c%d_k%d", dtype, shape.B, shape.T, shape.C, shape.K)
- x := patternArray(dtype, []int{shape.B, shape.T + shape.K - 1, shape.C}, 0.02, 0.004, 41, 263)
- w := patternArray(dtype, []int{shape.C, shape.K}, 0.1, 0.01, 7, 53)
+ for _, withBias := range []bool{false, true} {
+ for _, shape := range []struct{ B, T, C, K int }{
+ {1, 1, 64, 4},
+ {1, 4, 64, 4},
+ {1, 11, 96, 4},
+ {1, 64, 64, 4},
+ {1, 333, 64, 4},
+ {3, 7, 64, 4},
+ {2, 5, 32, 2},
+ } {
+ name := fmt.Sprintf("%v_bias%v_b%d_t%d_c%d_k%d", dtype, withBias, shape.B, shape.T, shape.C, shape.K)
+ x := patternArray(dtype, []int{shape.B, shape.T + shape.K - 1, shape.C}, 0.02, 0.004, 41, 263)
+ w := patternArray(dtype, []int{shape.C, shape.K}, 0.1, 0.01, 7, 53)
+ var bias *Array
+ if withBias {
+ bias = patternArray(dtype, []int{shape.C}, -0.3, 0.02, 11, 37)
+ }
- ref := SiLU(Conv1d(x, Reshape(w, int32(shape.C), int32(shape.K), 1), nil, 1, 0, 1, int32(shape.C)))
- y := DepthwiseConvSiLU(x, w, shape.T)
- if err := requireExact("y", y, ref); err != nil {
- t.Fatalf("%s: %v", name, err)
+ ref := SiLU(Conv1d(x, Reshape(w, int32(shape.C), int32(shape.K), 1), bias, 1, 0, 1, int32(shape.C)))
+ y := DepthwiseConvSiLU(x, w, bias, shape.T)
+ if err := requireExact("y", y, ref); err != nil {
+ mismatches = append(mismatches, fmt.Sprintf("%s: %v", name, err))
+ }
}
}
}
+ return mismatches
}
diff --git a/x/mlxrunner/mlx/mamba2_scan.go b/x/mlxrunner/mlx/mamba2_scan.go
new file mode 100644
index 000000000..a52847591
--- /dev/null
+++ b/x/mlxrunner/mlx/mamba2_scan.go
@@ -0,0 +1,265 @@
+package mlx
+
+import "math"
+
+// The states variant records the state after every token but the last, which is
+// what MTP verify needs to roll back to any position.
+var (
+ mamba2Scan = &gpuKernel{
+ name: "mamba2_scan",
+ inputs: []string{"hidden", "b_state", "c_state", "dt", "state_in", "a", "d", "dt_bias", "T"},
+ outputs: []string{"y", "state_out"},
+ metal: gpuSource{
+ source: mamba2ScanMetalSource,
+ header: "#define MAMBA2_STORE_INTERIOR(index, value)\n",
+ },
+ fallback: func(launch gpuLaunch) []*Array {
+ in := launch.inputs
+ y, end, _ := mamba2ScanGraph(in[0], in[1], in[2], in[3], in[4], in[5], in[6], in[7], false)
+ return []*Array{y, end}
+ },
+ }
+ mamba2ScanStates = &gpuKernel{
+ name: "mamba2_scan_states",
+ inputs: []string{"hidden", "b_state", "c_state", "dt", "state_in", "a", "d", "dt_bias", "T"},
+ outputs: []string{"y", "state_out", "state_seq"},
+ metal: gpuSource{
+ source: mamba2ScanMetalSource,
+ header: "#define MAMBA2_STORE_INTERIOR(index, value) state_seq[index] = value\n",
+ },
+ fallback: func(launch gpuLaunch) []*Array {
+ in := launch.inputs
+ y, end, interior := mamba2ScanGraph(in[0], in[1], in[2], in[3], in[4], in[5], in[6], in[7], true)
+ for i, s := range interior {
+ interior[i] = ExpandDims(s, 0)
+ }
+ return []*Array{y, end, Concatenate(interior, 0)}
+ },
+ }
+)
+
+const mamba2ScanMetalSource = `
+auto lane = thread_position_in_threadgroup.x;
+auto d_idx = thread_position_in_grid.y;
+auto bh_idx = thread_position_in_grid.z;
+auto b_idx = bh_idx / H;
+auto h_idx = bh_idx % H;
+// B/C groups repeat across contiguous head blocks.
+auto g_idx = h_idx / (H / G);
+constexpr int n_per_t = S / 32;
+constexpr int state_count = B * H * D * S;
+
+auto state_offset = ((b_idx * H + h_idx) * D + d_idx) * S;
+float state[n_per_t];
+for (int i = 0; i < n_per_t; ++i) {
+ auto s_idx = n_per_t * lane + i;
+ state[i] = static_cast<float>(state_in[state_offset + s_idx]);
+}
+
+for (int t = 0; t < T; ++t) {
+ auto bth = (b_idx * T + t) * H + h_idx;
+ float dt_raw = static_cast<float>(dt[bth]) + static_cast<float>(dt_bias[h_idx]);
+ float dt_val = log(1.0f + exp(dt_raw));
+ float decay = exp(dt_val * static_cast<float>(a[h_idx]));
+ float x_val = static_cast<float>(hidden[bth * D + d_idx]);
+
+ float out = 0.0f;
+ auto bs_base = ((b_idx * T + t) * G + g_idx) * S;
+ for (int i = 0; i < n_per_t; ++i) {
+ auto s_idx = n_per_t * lane + i;
+ float b_val = static_cast<float>(b_state[bs_base + s_idx]);
+ float c_val = static_cast<float>(c_state[bs_base + s_idx]);
+ state[i] = state[i] * decay + x_val * (dt_val * b_val);
+ out += state[i] * c_val;
+ }
+
+ if (t + 1 < T) {
+ auto seq_offset = t * state_count + state_offset;
+ for (int i = 0; i < n_per_t; ++i) {
+ auto s_idx = n_per_t * lane + i;
+ MAMBA2_STORE_INTERIOR(seq_offset + s_idx, state[i]);
+ }
+ }
+
+ out = simd_sum(out);
+ if (thread_index_in_simdgroup == 0) {
+ y[bth * D + d_idx] = out + x_val * static_cast<float>(d[h_idx]);
+ }
+}
+
+for (int i = 0; i < n_per_t; ++i) {
+ auto s_idx = n_per_t * lane + i;
+ state_out[state_offset + s_idx] = state[i];
+}
+`
+
+type mamba2ScanDims struct {
+ B, T, H, G, D, S int
+}
+
+func resolveMamba2ScanDims(hidden, bState, cState, dt, state, a, d, dtBias *Array) (mamba2ScanDims, bool) {
+ var dims mamba2ScanDims
+ if hidden == nil || bState == nil || cState == nil || dt == nil || state == nil || a == nil || d == nil || dtBias == nil {
+ return dims, false
+ }
+ if hidden.DType() != DTypeFloat32 || bState.DType() != DTypeFloat32 || cState.DType() != DTypeFloat32 || dt.DType() != DTypeFloat32 ||
+ state.DType() != DTypeFloat32 || a.DType() != DTypeFloat32 || d.DType() != DTypeFloat32 || dtBias.DType() != DTypeFloat32 {
+ return dims, false
+ }
+
+ hd, bd, cd := hidden.Dims(), bState.Dims(), cState.Dims()
+ dd, sd := dt.Dims(), state.Dims()
+ ad, wd, td := a.Dims(), d.Dims(), dtBias.Dims()
+ if len(hd) != 4 || len(bd) != 4 || len(cd) != 4 || len(dd) != 3 || len(sd) != 4 || len(ad) != 1 || len(wd) != 1 || len(td) != 1 {
+ return dims, false
+ }
+
+ dims.B, dims.T, dims.H, dims.D = hd[0], hd[1], hd[2], hd[3]
+ dims.G, dims.S = bd[2], bd[3]
+ // S must be a multiple of the Metal simdgroup width (32): the kernel
+ // partitions the S state slots across 32 lanes (n_per_t = S/32) and
+ // reduces with simd_sum, so a non-multiple would drop tail slots.
+ if dims.B <= 0 || dims.T <= 0 || dims.H <= 0 || dims.G <= 0 || dims.D <= 0 || dims.S <= 0 || dims.H%dims.G != 0 || dims.S%32 != 0 {
+ return dims, false
+ }
+ if bd[0] != dims.B || bd[1] != dims.T || cd[0] != dims.B || cd[1] != dims.T || cd[2] != dims.G || cd[3] != dims.S {
+ return dims, false
+ }
+ if dd[0] != dims.B || dd[1] != dims.T || dd[2] != dims.H {
+ return dims, false
+ }
+ if sd[0] != dims.B || sd[1] != dims.H || sd[2] != dims.D || sd[3] != dims.S {
+ return dims, false
+ }
+ if ad[0] != dims.H || wd[0] != dims.H || td[0] != dims.H {
+ return dims, false
+ }
+ return dims, true
+}
+
+func repeatMambaGroups(x *Array, repeats int32) *Array {
+ if repeats <= 1 {
+ return x
+ }
+ // Mamba2 maps each B/C group to a contiguous block of heads.
+ dims := x.Dims()
+ x = ExpandDims(x, 3)
+ x = Tile(x, []int32{1, 1, 1, repeats, 1})
+ return Reshape(x, int32(dims[0]), int32(dims[1]), int32(dims[2])*repeats, int32(dims[3]))
+}
+
+func sliceMambaTime(x *Array, t int32) *Array {
+ dims := x.Dims()
+ start := make([]int32, len(dims))
+ stop := make([]int32, len(dims))
+ for i, d := range dims {
+ stop[i] = int32(d)
+ }
+ start[1], stop[1] = t, t+1
+ return Squeeze(SliceStartStop(x, start, stop), 1)
+}
+
+func mamba2ScanGraph(hidden, bState, cState, dt, state, a, d, dtBias *Array, captureAll bool) (y, nextState *Array, interior []*Array) {
+ B := int32(hidden.Dim(0))
+ T := int32(hidden.Dim(1))
+ H := int32(hidden.Dim(2))
+ G := int32(bState.Dim(2))
+
+ if G > 0 && H%G == 0 {
+ bState = repeatMambaGroups(bState, H/G)
+ cState = repeatMambaGroups(cState, H/G)
+ }
+
+ a4 := Reshape(a, 1, H, 1, 1)
+ d3 := Reshape(d, 1, H, 1)
+ bias2 := Reshape(dtBias, 1, H)
+
+ outs := make([]*Array, 0, T)
+ for t := range T {
+ xt := sliceMambaTime(hidden, t)
+ bt := sliceMambaTime(bState, t)
+ ct := sliceMambaTime(cState, t)
+
+ dtt := Add(sliceMambaTime(dt, t), bias2)
+ dtt = Log(AddScalar(Exp(dtt), 1))
+ dA := Exp(Mul(Reshape(dtt, B, H, 1, 1), a4))
+ dB := Mul(Reshape(dtt, B, H, 1), bt)
+
+ state = Add(Mul(state, dA), Mul(ExpandDims(xt, -1), ExpandDims(dB, 2)))
+ yt := Sum(Mul(state, ExpandDims(ct, 2)), 3, false)
+ outs = append(outs, Add(yt, Mul(xt, d3)))
+
+ if captureAll && t+1 < T {
+ interior = append(interior, state)
+ }
+ }
+ return Stack(outs, 1), state, interior
+}
+
+// Mamba2Scan runs the Mamba2 recurrent scan. Inputs must be float32 with
+// shapes hidden [B, T, H, D], bState/cState [B, T, G, S] where H%G == 0,
+// dt [B, T, H], state [B, H, D, S], and a/d/dtBias [H]. captureAll also
+// returns the state after every token but the last.
+//
+// mask, when non-nil, is a [B, T] bool marking real (true) vs padded
+// positions; padded positions are identity steps.
+func Mamba2Scan(hidden, bState, cState, dt, state, a, d, dtBias, mask *Array, captureAll bool) (y, nextState *Array, interior []*Array) {
+ if mask != nil {
+ B, T := int32(mask.Dim(0)), int32(mask.Dim(1))
+ zero := FromValue(float32(0)).AsType(hidden.DType())
+ mask4 := Reshape(mask, B, T, 1, 1)
+ hidden = Where(mask4, hidden, zero)
+ cState = Where(mask4, cState, zero)
+ negInf := FromValue(float32(math.Inf(-1))).AsType(dt.DType())
+ dt = Where(Reshape(mask, B, T, 1), dt, negInf)
+ }
+
+ dims, ok := resolveMamba2ScanDims(hidden, bState, cState, dt, state, a, d, dtBias)
+ if !ok {
+ return mamba2ScanGraph(hidden, bState, cState, dt, state, a, d, dtBias, captureAll)
+ }
+
+ kernel := mamba2Scan
+ outputs := []gpuOutputSpec{
+ {"MAMBA2_SCAN_Y", []int32{int32(dims.B), int32(dims.T), int32(dims.H), int32(dims.D)}, DTypeFloat32},
+ {"MAMBA2_SCAN_STATE", []int32{int32(dims.B), int32(dims.H), int32(dims.D), int32(dims.S)}, DTypeFloat32},
+ }
+ useAllStates := captureAll && dims.T > 1
+ if useAllStates {
+ kernel = mamba2ScanStates
+ outputs = append(outputs, gpuOutputSpec{
+ "MAMBA2_SCAN_STATE_SEQ",
+ []int32{int32(dims.T - 1), int32(dims.B), int32(dims.H), int32(dims.D), int32(dims.S)},
+ DTypeFloat32,
+ })
+ }
+
+ outs := kernel.run(gpuLaunch{
+ ints: []gpuIntArg{
+ {"B", dims.B},
+ {"H", dims.H},
+ {"G", dims.G},
+ {"D", dims.D},
+ {"S", dims.S},
+ },
+ outputs: outputs,
+ grid: [3]int{32, dims.D, dims.B * dims.H},
+ threadGroup: [3]int{32, min(dims.D, 4), 1},
+ inputs: []*Array{hidden, bState, cState, dt, state, a, d, dtBias, FromValue(dims.T)},
+ })
+ if useAllStates {
+ interior = sliceMamba2ScanStates(outs[2], dims)
+ }
+ return outs[0], outs[1], interior
+}
+
+func sliceMamba2ScanStates(stateSeq *Array, dims mamba2ScanDims) []*Array {
+ interior := make([]*Array, dims.T-1)
+ for t := range interior {
+ s := SliceStartStop(stateSeq,
+ []int32{int32(t), 0, 0, 0, 0},
+ []int32{int32(t) + 1, int32(dims.B), int32(dims.H), int32(dims.D), int32(dims.S)})
+ interior[t] = Reshape(s, int32(dims.B), int32(dims.H), int32(dims.D), int32(dims.S))
+ }
+ return interior
+}
diff --git a/x/mlxrunner/mlx/mamba_kernels_test.go b/x/mlxrunner/mlx/mamba_kernels_test.go
new file mode 100644
index 000000000..1b18245b4
--- /dev/null
+++ b/x/mlxrunner/mlx/mamba_kernels_test.go
@@ -0,0 +1,277 @@
+package mlx
+
+import (
+ "fmt"
+ "math"
+ "testing"
+)
+
+func TestMamba2ScanMatchesReference(t *testing.T) {
+ requireMamba2Metal(t)
+ var failures []error
+ withMLXThread(t, func() {
+ in := newMamba2TestInputs(1, 3, 2, 2, 2, 32)
+ gotY, gotState, interior := Mamba2Scan(in.hidden, in.bState, in.cState, in.dt, in.state, in.a, in.d, in.dtBias, nil, false)
+ if len(interior) != 0 {
+ failures = append(failures, fmt.Errorf("interior states = %d, want 0 without captureAll", len(interior)))
+ }
+ wantY, wantState := mamba2ScanReference(in.hidden, in.bState, in.cState, in.dt, in.state, in.a, in.d, in.dtBias)
+ failures = appendArrayCloseError(failures, "mamba2 scan y", gotY, wantY, 1e-5)
+ failures = appendArrayCloseError(failures, "mamba2 scan state", gotState, wantState, 1e-5)
+ })
+ reportMamba2Failures(t, failures)
+}
+
+// Every interior state must match, not just one boundary.
+func TestMamba2ScanCaptureAllMatchesPerTokenReference(t *testing.T) {
+ requireMamba2Metal(t)
+ var failures []error
+ withMLXThread(t, func() {
+ const T = 4
+ in := newMamba2TestInputs(1, T, 2, 2, 2, 32)
+ gotY, gotEnd, gotInterior := Mamba2Scan(in.hidden, in.bState, in.cState, in.dt, in.state, in.a, in.d, in.dtBias, nil, true)
+ if len(gotInterior) != T-1 {
+ failures = append(failures, fmt.Errorf("interior states = %d, want %d", len(gotInterior), T-1))
+ }
+
+ state := in.state
+ for ti := range int32(T) {
+ var y *Array
+ y, state = mamba2ScanReference(
+ sliceTimeRange(in.hidden, ti, ti+1),
+ sliceTimeRange(in.bState, ti, ti+1),
+ sliceTimeRange(in.cState, ti, ti+1),
+ sliceTimeRange(in.dt, ti, ti+1),
+ state, in.a, in.d, in.dtBias,
+ )
+ failures = appendArrayCloseError(failures, fmt.Sprintf("token %d y", ti), sliceTimeRange(gotY, ti, ti+1), y, 1e-5)
+ if int(ti) < T-1 && int(ti) < len(gotInterior) {
+ failures = appendArrayCloseError(failures, fmt.Sprintf("token %d interior state", ti), gotInterior[ti], state, 1e-5)
+ }
+ }
+ failures = appendArrayCloseError(failures, "captureAll end state", gotEnd, state, 1e-5)
+ })
+ reportMamba2Failures(t, failures)
+}
+
+func TestMamba2ScanGroupedStatesMatchRepeatedReference(t *testing.T) {
+ requireMamba2Metal(t)
+ var failures []error
+ withMLXThread(t, func() {
+ in := newMamba2TestInputs(1, 2, 4, 2, 2, 32)
+ gotY, gotState, _ := Mamba2Scan(in.hidden, in.bState, in.cState, in.dt, in.state, in.a, in.d, in.dtBias, nil, false)
+ wantY, wantState := mamba2ScanReference(
+ in.hidden,
+ repeatMambaGroupsForTest(in.bState, 2),
+ repeatMambaGroupsForTest(in.cState, 2),
+ in.dt, in.state, in.a, in.d, in.dtBias,
+ )
+ failures = appendArrayCloseError(failures, "grouped mamba2 y", gotY, wantY, 1e-5)
+ failures = appendArrayCloseError(failures, "grouped mamba2 state", gotState, wantState, 1e-5)
+ })
+ reportMamba2Failures(t, failures)
+}
+
+// A shape outside the kernel's contract must still compute the right answer
+// through the graph implementation rather than fail.
+func TestMamba2ScanUnsupportedShapeMatchesGraph(t *testing.T) {
+ var failures []error
+ withMLXThread(t, func() {
+ in := newMamba2TestInputs(1, 2, 2, 2, 2, 31)
+ if _, ok := resolveMamba2ScanDims(in.hidden, in.bState, in.cState, in.dt, in.state, in.a, in.d, in.dtBias); ok {
+ failures = append(failures, fmt.Errorf("resolveMamba2ScanDims ok=true for unsupported S=31 shape"))
+ }
+ gotY, gotState, _ := Mamba2Scan(in.hidden, in.bState, in.cState, in.dt, in.state, in.a, in.d, in.dtBias, nil, false)
+ wantY, wantState := mamba2ScanReference(in.hidden, in.bState, in.cState, in.dt, in.state, in.a, in.d, in.dtBias)
+ failures = appendArrayCloseError(failures, "unsupported-shape y", gotY, wantY, 1e-5)
+ failures = appendArrayCloseError(failures, "unsupported-shape state", gotState, wantState, 1e-5)
+ })
+ reportMamba2Failures(t, failures)
+}
+
+// A padded position must be an identity step. Without the mask it still decays
+// the state by exp(dt*a).
+func TestMamba2ScanPaddedRowIsIdentity(t *testing.T) {
+ requireMamba2Metal(t)
+ var failures []error
+ withMLXThread(t, func() {
+ const (
+ B = 2
+ L = 3
+ H = 2
+ D = 2
+ S = 32
+ )
+ in := newMamba2TestInputs(B, L, H, H, D, S)
+ mask := FromValues([]bool{true, true, true, true, false, false}, B, L)
+
+ gotY, gotState, _ := Mamba2Scan(in.hidden, in.bState, in.cState, in.dt, in.state, in.a, in.d, in.dtBias, mask, false)
+
+ for row, realLen := range []int32{L, 1} {
+ r := int32(row)
+ wantY, wantState := mamba2ScanReference(
+ sliceRowTime(in.hidden, r, realLen),
+ sliceRowTime(in.bState, r, realLen),
+ sliceRowTime(in.cState, r, realLen),
+ sliceRowTime(in.dt, r, realLen),
+ sliceRow(in.state, r), in.a, in.d, in.dtBias,
+ )
+ failures = appendArrayCloseError(failures, fmt.Sprintf("row %d y", row), sliceRowTime(gotY, r, realLen), wantY, 1e-5)
+ failures = appendArrayCloseError(failures, fmt.Sprintf("row %d state", row), sliceRow(gotState, r), wantState, 1e-5)
+ }
+
+ pad := SliceStartStop(gotY, []int32{1, 1, 0, 0}, []int32{2, L, H, D})
+ Eval(pad)
+ for i, v := range pad.Floats() {
+ if v != 0 {
+ failures = append(failures, fmt.Errorf("padded output[%d] = %v, want 0", i, v))
+ }
+ }
+ })
+ reportMamba2Failures(t, failures)
+}
+
+type mamba2TestInputs struct {
+ hidden, bState, cState, dt, state, a, d, dtBias *Array
+}
+
+func newMamba2TestInputs(B, T, H, G, D, S int) mamba2TestInputs {
+ return mamba2TestInputs{
+ hidden: testArrayValues(0.1, B, T, H, D),
+ bState: testArrayValues(0.2, B, T, G, S),
+ cState: testArrayValues(0.3, B, T, G, S),
+ dt: testArrayValues(-0.4, B, T, H),
+ state: testArrayValues(0.5, B, H, D, S),
+ a: MulScalar(onesTest(DTypeFloat32, H), -0.25),
+ d: MulScalar(onesTest(DTypeFloat32, H), 0.1),
+ dtBias: Zeros(DTypeFloat32, H),
+ }
+}
+
+func sliceRow(x *Array, r int32) *Array {
+ dims := x.Dims()
+ start := make([]int32, len(dims))
+ stop := make([]int32, len(dims))
+ for i, d := range dims {
+ stop[i] = int32(d)
+ }
+ start[0], stop[0] = r, r+1
+ return SliceStartStop(x, start, stop)
+}
+
+func sliceRowTime(x *Array, r, realLen int32) *Array {
+ dims := x.Dims()
+ start := make([]int32, len(dims))
+ stop := make([]int32, len(dims))
+ for i, d := range dims {
+ stop[i] = int32(d)
+ }
+ start[0], stop[0] = r, r+1
+ stop[1] = realLen
+ return SliceStartStop(x, start, stop)
+}
+
+func testArrayValues(seed float32, shape ...int) *Array {
+ n := 1
+ for _, d := range shape {
+ n *= d
+ }
+ vals := make([]float32, n)
+ for i := range vals {
+ vals[i] = seed + 0.001*float32(i)
+ }
+ return FromValues(vals, shape...)
+}
+
+func onesTest(dtype DType, shape ...int) *Array {
+ return AddScalar(Zeros(dtype, shape...), 1)
+}
+
+func requireMamba2Metal(t *testing.T) {
+ t.Helper()
+ skipIfNoMLX(t)
+ if !MetalIsAvailable() {
+ t.Skip("MLX Metal not available")
+ }
+}
+
+func appendArrayCloseError(failures []error, name string, got, want *Array, tol float64) []error {
+ Eval(got, want)
+ gotF := got.Floats()
+ wantF := want.Floats()
+ if len(gotF) != len(wantF) {
+ return append(failures, fmt.Errorf("%s length = %d, want %d", name, len(gotF), len(wantF)))
+ }
+ for i := range gotF {
+ if math.Abs(float64(gotF[i]-wantF[i])) > tol {
+ return append(failures, fmt.Errorf("%s[%d] = %v, want %v", name, i, gotF[i], wantF[i]))
+ }
+ }
+ return failures
+}
+
+func reportMamba2Failures(t *testing.T, failures []error) {
+ t.Helper()
+ for _, err := range failures {
+ t.Error(err)
+ }
+}
+
+func mamba2ScanReference(hidden, bState, cState, dt, state, a, d, dtBias *Array) (*Array, *Array) {
+ B := int32(hidden.Dim(0))
+ T := int32(hidden.Dim(1))
+ H := int32(hidden.Dim(2))
+ D := int32(hidden.Dim(3))
+
+ a = Reshape(a, 1, H, 1, 1)
+ d = Reshape(d, 1, H, 1)
+ outs := make([]*Array, 0, T)
+ for t := range T {
+ xt := sliceTimeForTest(hidden, t).AsType(DTypeFloat32)
+ bt := sliceTimeForTest(bState, t).AsType(DTypeFloat32)
+ ct := sliceTimeForTest(cState, t).AsType(DTypeFloat32)
+ dtt := Add(sliceTimeForTest(dt, t).AsType(DTypeFloat32), dtBias)
+ dtt = Log(AddScalar(Exp(dtt), 1))
+ dA := Exp(Mul(Reshape(dtt, B, H, 1, 1), a))
+ dB := Mul(Reshape(dtt, B, H, 1), bt)
+ state = Add(Mul(state, dA), Mul(ExpandDims(xt, -1), ExpandDims(dB, 2)))
+ y := Sum(Mul(state, ExpandDims(ct, 2)), 3, false)
+ y = Add(y, Mul(xt, d))
+ outs = append(outs, Reshape(y, B, H, D))
+ }
+ return Stack(outs, 1), state
+}
+
+func sliceTimeForTest(x *Array, t int32) *Array {
+ dims := x.Dims()
+ start := make([]int32, len(dims))
+ stop := make([]int32, len(dims))
+ for i, d := range dims {
+ stop[i] = int32(d)
+ }
+ start[1] = t
+ stop[1] = t + 1
+ return Squeeze(SliceStartStop(x, start, stop), 1)
+}
+
+func sliceTimeRange(x *Array, start, stop int32) *Array {
+ dims := x.Dims()
+ starts := make([]int32, len(dims))
+ stops := make([]int32, len(dims))
+ for i, d := range dims {
+ stops[i] = int32(d)
+ }
+ starts[1] = start
+ stops[1] = stop
+ return SliceStartStop(x, starts, stops)
+}
+
+func repeatMambaGroupsForTest(x *Array, repeats int32) *Array {
+ if repeats <= 1 {
+ return x
+ }
+ dims := x.Dims()
+ x = ExpandDims(x, 3)
+ x = Tile(x, []int32{1, 1, 1, repeats, 1})
+ return Reshape(x, int32(dims[0]), int32(dims[1]), int32(dims[2])*repeats, int32(dims[3]))
+}
diff --git a/x/mlxrunner/mtp_test.go b/x/mlxrunner/mtp_test.go
index 89b6883c9..80460e3da 100644
--- a/x/mlxrunner/mtp_test.go
+++ b/x/mlxrunner/mtp_test.go
@@ -11,6 +11,7 @@ import (
"testing"
"github.com/ollama/ollama/api"
+ "github.com/ollama/ollama/x/internal/mlxtest"
"github.com/ollama/ollama/x/mlxrunner/batch"
"github.com/ollama/ollama/x/mlxrunner/cache"
"github.com/ollama/ollama/x/mlxrunner/mlx"
@@ -19,13 +20,13 @@ import (
"github.com/ollama/ollama/x/tokenizer"
)
-// skipIfNoMLX skips a test that exercises native MLX when the dynamic library
-// is unavailable, as on CI runners without an MLX build.
+// skipIfNoMLX skips when MLX is unavailable and pins the test to its OS
+// thread. The pin is load-bearing: MLX caches its default stream per thread,
+// so a goroutine that migrates mid-run panics with "There is no Stream(gpu, 0)
+// in current thread".
func skipIfNoMLX(t *testing.T) {
t.Helper()
- if err := mlx.CheckInit(); err != nil {
- t.Skipf("MLX not available: %v", err)
- }
+ mlxtest.Setup(t)
}
// The MTP fakes make hidden state and logits the same tensor (Forward returns
diff --git a/x/mlxrunner/pipeline.go b/x/mlxrunner/pipeline.go
index 0cf9e3d14..e5b8b5fe9 100644
--- a/x/mlxrunner/pipeline.go
+++ b/x/mlxrunner/pipeline.go
@@ -150,6 +150,9 @@ func (r *Runner) prefill(ctx context.Context, session *cacheSession, spec *specu
materializeCaches := func() {
state := make([]*mlx.Array, 0, 2*len(caches))
for _, c := range caches {
+ if c == nil {
+ continue
+ }
state = append(state, c.State()...)
}
if len(state) == 0 {
diff --git a/x/mlxrunner/prefix_cache.go b/x/mlxrunner/prefix_cache.go
index 3da72704b..071496372 100644
--- a/x/mlxrunner/prefix_cache.go
+++ b/x/mlxrunner/prefix_cache.go
@@ -208,7 +208,7 @@ func (c *prefixCache) switchToPath(newPath []*trieNode, matched int) {
leafNeedsRewind := matched < c.activePath[leaf].endOffset
if leafDiverges || leafNeedsRewind {
node := c.activePath[leaf]
- if !node.hasAllSnapshots() {
+ if !hasAllSnapshots(node, c.caches) {
fromOffset := node.startOffset()
snaps := make([]cache.Snapshot, len(c.caches))
for j, kv := range c.caches {
@@ -664,7 +664,7 @@ func (c *prefixCache) dumpTree() {
if n.user {
flags = append(flags, "user")
}
- if n.hasAllSnapshots() {
+ if hasAllSnapshots(n, c.caches) {
snapshotCount++
flags = append(flags, "snap")
}
diff --git a/x/mlxrunner/prefix_cache_test.go b/x/mlxrunner/prefix_cache_test.go
index 31708c7b6..df4888602 100644
--- a/x/mlxrunner/prefix_cache_test.go
+++ b/x/mlxrunner/prefix_cache_test.go
@@ -437,6 +437,21 @@ func newSlidingWindowEnv() *testEnv {
}
}
+// newStatelessLayerEnv gives the cache slice nil holes, the layout a hybrid
+// model produces when some layers own no state.
+func newStatelessLayerEnv() *testEnv {
+ tr := &snapshotTracker{}
+ rc := &fakeRewindableCache{tracker: tr}
+ nrc := &fakeRecurrentCache{tracker: tr}
+ caches := []cache.Cache{nrc, nil, rc, nil}
+ return &testEnv{
+ pc: &prefixCache{caches: caches},
+ caches: caches,
+ tracker: tr,
+ rewindable: false,
+ }
+}
+
// newRecurrentEnv creates a test environment with one rewindable cache and one
// non-rewindable cache (Jamba-style architecture).
func newRecurrentEnv() *testEnv {
@@ -456,12 +471,20 @@ func newRecurrentEnv() *testEnv {
// the expected token sequence.
func (e *testEnv) assertAllTokens(t *testing.T, label string, expected []int32) {
t.Helper()
+ var first cache.Cache
for i, c := range e.caches {
+ if c == nil {
+ continue
+ }
assertTokens(t, label, c, expected)
// Verify all caches report the same offset.
- if i > 0 && c.Offset() != e.caches[0].Offset() {
- t.Errorf("%s: cache %d offset=%d != cache 0 offset=%d",
- label, i, c.Offset(), e.caches[0].Offset())
+ if first == nil {
+ first = c
+ continue
+ }
+ if c.Offset() != first.Offset() {
+ t.Errorf("%s: cache %d offset=%d != first cache offset=%d",
+ label, i, c.Offset(), first.Offset())
}
}
}
@@ -531,13 +554,17 @@ func feedAll(caches []cache.Cache, tokens []int32) {
// assertCacheOffsetAlignment verifies all caches report the same offset.
func assertCacheOffsetAlignment(t *testing.T, pc *prefixCache, label string) {
t.Helper()
- if len(pc.caches) < 2 {
- return
- }
- expected := pc.caches[0].Offset()
- for i := 1; i < len(pc.caches); i++ {
- if got := pc.caches[i].Offset(); got != expected {
- t.Errorf("%s: cache %d offset=%d != cache 0 offset=%d", label, i, got, expected)
+ expected := -1
+ for i, c := range pc.caches {
+ if c == nil {
+ continue
+ }
+ if expected < 0 {
+ expected = c.Offset()
+ continue
+ }
+ if got := c.Offset(); got != expected {
+ t.Errorf("%s: cache %d offset=%d != first cache offset=%d", label, i, got, expected)
}
}
}
@@ -655,6 +682,7 @@ func forEachEnv(t *testing.T, fn func(t *testing.T, env *testEnv)) {
{"Transformer", newTransformerEnv},
{"SlidingWindow", newSlidingWindowEnv},
{"Recurrent", newRecurrentEnv},
+ {"StatelessLayers", newStatelessLayerEnv},
}
for _, e := range envs {
for _, lookahead := range []int{0, 1} {
@@ -1188,3 +1216,72 @@ func TestSwapSnapshotsDetachesHook(t *testing.T) {
t.Fatalf("pagedOutBytes after replacement materialize = %d, want %d", pc.pagedOutBytes, 2<<20)
}
}
+
+// Without this, every node reads as incomplete on a hybrid model and
+// switchToPath re-pages the leaf every time.
+func TestHasAllSnapshotsIgnoresStatelessLayers(t *testing.T) {
+ tr := &snapshotTracker{}
+ caches := []cache.Cache{
+ &fakeRewindableCache{tracker: tr},
+ nil,
+ &fakeRecurrentCache{tracker: tr},
+ }
+
+ node := &trieNode{tokens: []trieKey{1, 2, 3}, endOffset: 3}
+ if hasAllSnapshots(node, caches) {
+ t.Fatal("hasAllSnapshots = true with no snapshots at all")
+ }
+
+ node.snapshots = []cache.Snapshot{&fakeSnapshot{from: 0, to: 3}, nil, &fakeSnapshot{from: 0, to: 3}}
+ if !hasAllSnapshots(node, caches) {
+ t.Fatal("hasAllSnapshots = false when every stateful layer has a snapshot")
+ }
+
+ node.snapshots = []cache.Snapshot{&fakeSnapshot{from: 0, to: 3}, nil, nil}
+ if hasAllSnapshots(node, caches) {
+ t.Fatal("hasAllSnapshots = true with a stateful layer's snapshot missing")
+ }
+}
+
+// Merge is only reached when an interior node with one child is evicted, which
+// the scenario tests never hit, so drive it directly.
+func TestMergeWithChildSkipsStatelessLayers(t *testing.T) {
+ tr := &snapshotTracker{}
+ caches := []cache.Cache{
+ &fakeRewindableCache{tracker: tr},
+ nil,
+ &fakeRecurrentCache{tracker: tr},
+ }
+
+ pc := &prefixCache{caches: caches}
+ pc.ensureRoot()
+
+ parent := &trieNode{parent: pc.root, tokens: []trieKey{1, 2}, endOffset: 2}
+ child := &trieNode{parent: parent, tokens: []trieKey{3, 4}, endOffset: 4}
+ parent.children = []*trieNode{child}
+ pc.root.children = []*trieNode{parent}
+
+ parent.setSnapshots([]cache.Snapshot{
+ &fakeSnapshot{from: 0, to: 2}, nil, &fakeSnapshot{from: 0, to: 2},
+ }, &pc.pagedOutBytes)
+ child.setSnapshots([]cache.Snapshot{
+ &fakeSnapshot{from: 2, to: 4}, nil, &fakeSnapshot{from: 2, to: 4},
+ }, &pc.pagedOutBytes)
+
+ mergeWithChild(parent, caches, &pc.pagedOutBytes)
+
+ if got := len(parent.tokens); got != 4 {
+ t.Fatalf("merged tokens = %d, want 4", got)
+ }
+ if got := parent.endOffset; got != 4 {
+ t.Fatalf("merged endOffset = %d, want 4", got)
+ }
+ if parent.snapshots[1] != nil {
+ t.Fatalf("stateless layer snapshot = %v, want nil", parent.snapshots[1])
+ }
+ for _, i := range []int{0, 2} {
+ if parent.snapshots[i] == nil {
+ t.Fatalf("stateful layer %d lost its merged snapshot", i)
+ }
+ }
+}
diff --git a/x/models/nemotron_h/nemotron_h.go b/x/models/nemotron_h/nemotron_h.go
new file mode 100644
index 000000000..c7c86afdf
--- /dev/null
+++ b/x/models/nemotron_h/nemotron_h.go
@@ -0,0 +1,1505 @@
+// Package nemotron_h provides the Nemotron-H text model implementation for MLX.
+package nemotron_h
+
+import (
+ "encoding/json"
+ "fmt"
+ "math"
+ "sort"
+ "strconv"
+ "strings"
+
+ "github.com/ollama/ollama/x/mlxrunner/batch"
+ "github.com/ollama/ollama/x/mlxrunner/cache"
+ "github.com/ollama/ollama/x/mlxrunner/mlx"
+ "github.com/ollama/ollama/x/mlxrunner/model"
+ "github.com/ollama/ollama/x/mlxrunner/model/base"
+ "github.com/ollama/ollama/x/models/nn"
+ "github.com/ollama/ollama/x/tokenizer"
+)
+
+func init() {
+ base.Register("NemotronH_Nano_VL_V2", newModel)
+ base.Register("NemotronH_Nano_Omni_Reasoning_V3", newModel)
+ base.Register("NemotronHForCausalLM", newModel)
+}
+
+var (
+ _ base.Model = (*Model)(nil)
+ _ base.SelfDraft = (*Model)(nil)
+ _ base.DraftModel = (*mtpDraft)(nil)
+)
+
+type Config struct {
+ ModelType string `json:"model_type"`
+ VocabSize int32 `json:"vocab_size"`
+ HiddenSize int32 `json:"hidden_size"`
+ IntermediateSize int32 `json:"intermediate_size"`
+ NumHiddenLayers int32 `json:"num_hidden_layers"`
+ HybridOverridePattern string `json:"hybrid_override_pattern"`
+ NumAttentionHeads int32 `json:"num_attention_heads"`
+ NumKeyValueHeads int32 `json:"num_key_value_heads"`
+ HeadDim int32 `json:"head_dim"`
+ LayerNormEpsilon float32 `json:"layer_norm_epsilon"`
+ RMSNormEps float32 `json:"rms_norm_eps"`
+ TieWordEmbeddings bool `json:"tie_word_embeddings"`
+ MaxPositionEmbeddings int32 `json:"max_position_embeddings"`
+ AttentionBias bool `json:"attention_bias"`
+ MLPBias bool `json:"mlp_bias"`
+ UseBias bool `json:"use_bias"`
+
+ ConvKernel int32 `json:"conv_kernel"`
+ SSMStateSize int32 `json:"ssm_state_size"`
+ MambaNumHeads int32 `json:"mamba_num_heads"`
+ MambaHeadDim int32 `json:"mamba_head_dim"`
+ NGroups int32 `json:"n_groups"`
+ MambaChunkSize int32 `json:"chunk_size"`
+
+ NRoutedExperts int32 `json:"n_routed_experts"`
+ NSharedExperts int32 `json:"n_shared_experts"`
+ NumExpertsPerTok int32 `json:"num_experts_per_tok"`
+ MoEIntermediateSize int32 `json:"moe_intermediate_size"`
+ MoESharedExpertIntermediateSize int32 `json:"moe_shared_expert_intermediate_size"`
+ RoutedScalingFactor float32 `json:"routed_scaling_factor"`
+ ExpertGroupCount int32 `json:"n_group"`
+ ExpertGroupUsedCount int32 `json:"topk_group"`
+ NormTopKProb bool `json:"norm_topk_prob"`
+
+ QuantGroupSize int `json:"-"`
+ QuantBits int `json:"-"`
+ QuantMode string `json:"-"`
+ TensorQuant map[string]*model.TensorQuantInfo `json:"-"`
+
+ LayerTypes []byte `json:"-"`
+ AttnScale float32 `json:"-"`
+}
+
+type Model struct {
+ EmbedTokens nn.EmbeddingLayer
+ Layers []*Layer
+ Norm *nn.RMSNorm
+ LMHead nn.LinearLayer
+
+ MTP *MTPHead
+
+ tok *tokenizer.Tokenizer
+ *Config
+
+ weightPrefix string
+}
+
+type MTPHead struct {
+ Enorm *nn.RMSNorm
+ Hnorm *nn.RMSNorm
+ FC nn.LinearLayer
+ Layers []*Layer
+ Norm *nn.RMSNorm
+}
+
+type Layer struct {
+ Norm *nn.RMSNorm
+
+ Type byte
+ Mamba *Mamba2
+ Attention *Attention
+ Dense *DenseMLP
+ MoE *SparseMoE
+}
+
+type Mamba2 struct {
+ InProj nn.LinearLayer
+ OutProj nn.LinearLayer
+
+ Conv1D *nn.Conv1d
+ DtBias *mlx.Array
+ A *mlx.Array
+ D *mlx.Array
+ NormWeight *mlx.Array
+}
+
+type Attention struct {
+ QProj nn.LinearLayer
+ KProj nn.LinearLayer
+ VProj nn.LinearLayer
+ OProj nn.LinearLayer
+}
+
+type DenseMLP struct {
+ UpProj nn.LinearLayer
+ DownProj nn.LinearLayer
+}
+
+type SparseMoE struct {
+ Router nn.LinearLayer
+ RouterWeight *mlx.Array
+ CorrectionBias *mlx.Array
+
+ UseQuantized bool
+
+ UpWeight *mlx.Array
+ UpWeightQ *mlx.Array
+ UpScales *mlx.Array
+ UpBiases *mlx.Array
+ UpGroupSize int
+ UpBits int
+ UpMode string
+ DownWeight *mlx.Array
+ DownWeightQ *mlx.Array
+ DownScales *mlx.Array
+ DownBiases *mlx.Array
+ DownGroupSize int
+ DownBits int
+ DownMode string
+
+ SharedUp nn.LinearLayer
+ SharedDown nn.LinearLayer
+
+ FoldedSharedExperts int32
+}
+
+type stackedExpertWeights struct {
+ Weight *mlx.Array
+ Scales *mlx.Array
+ Biases *mlx.Array
+ Bits int
+ GroupSize int
+ Mode string
+}
+
+type configEnvelope struct {
+ LLMConfig *Config `json:"llm_config"`
+}
+
+func parseConfig(data []byte) (Config, error) {
+ var cfg Config
+ if err := json.Unmarshal(data, &cfg); err != nil {
+ return Config{}, fmt.Errorf("parse config: %w", err)
+ }
+
+ var env configEnvelope
+ if err := json.Unmarshal(data, &env); err != nil {
+ return Config{}, fmt.Errorf("parse config envelope: %w", err)
+ }
+ if env.LLMConfig != nil {
+ cfg = *env.LLMConfig
+ }
+
+ if cfg.HiddenSize <= 0 {
+ return Config{}, fmt.Errorf("invalid hidden_size: %d", cfg.HiddenSize)
+ }
+ if cfg.NumHiddenLayers <= 0 {
+ return Config{}, fmt.Errorf("invalid num_hidden_layers: %d", cfg.NumHiddenLayers)
+ }
+ if cfg.NumAttentionHeads <= 0 {
+ return Config{}, fmt.Errorf("invalid num_attention_heads: %d", cfg.NumAttentionHeads)
+ }
+ if cfg.NumKeyValueHeads <= 0 {
+ cfg.NumKeyValueHeads = cfg.NumAttentionHeads
+ }
+ if cfg.HeadDim <= 0 {
+ if cfg.HiddenSize%cfg.NumAttentionHeads != 0 {
+ return Config{}, fmt.Errorf("hidden_size (%d) must be divisible by num_attention_heads (%d)", cfg.HiddenSize, cfg.NumAttentionHeads)
+ }
+ cfg.HeadDim = cfg.HiddenSize / cfg.NumAttentionHeads
+ }
+ if cfg.LayerNormEpsilon == 0 {
+ cfg.LayerNormEpsilon = cfg.RMSNormEps
+ }
+ if cfg.LayerNormEpsilon == 0 {
+ cfg.LayerNormEpsilon = 1e-5
+ }
+ if cfg.MaxPositionEmbeddings <= 0 {
+ cfg.MaxPositionEmbeddings = 4096
+ }
+ if cfg.ConvKernel <= 0 {
+ cfg.ConvKernel = 4
+ }
+ if cfg.SSMStateSize <= 0 {
+ cfg.SSMStateSize = 128
+ }
+ if cfg.MambaNumHeads <= 0 {
+ cfg.MambaNumHeads = 128
+ }
+ if cfg.MambaHeadDim <= 0 {
+ cfg.MambaHeadDim = 64
+ }
+ if cfg.NGroups <= 0 {
+ cfg.NGroups = 1
+ }
+ if cfg.MambaChunkSize <= 0 {
+ cfg.MambaChunkSize = 128
+ }
+ if cfg.RoutedScalingFactor == 0 {
+ cfg.RoutedScalingFactor = 1
+ }
+ if cfg.ExpertGroupCount <= 0 {
+ cfg.ExpertGroupCount = 1
+ }
+ if cfg.ExpertGroupUsedCount <= 0 {
+ cfg.ExpertGroupUsedCount = cfg.ExpertGroupCount
+ }
+ if cfg.NRoutedExperts > 0 && cfg.ExpertGroupCount > 0 && cfg.NRoutedExperts%cfg.ExpertGroupCount != 0 {
+ return Config{}, fmt.Errorf("n_routed_experts %d must be divisible by n_group %d", cfg.NRoutedExperts, cfg.ExpertGroupCount)
+ }
+
+ pattern := strings.TrimSpace(cfg.HybridOverridePattern)
+ if pattern == "" {
+ return Config{}, fmt.Errorf("hybrid_override_pattern must be set")
+ }
+ if len(pattern) != int(cfg.NumHiddenLayers) {
+ return Config{}, fmt.Errorf("hybrid_override_pattern length %d does not match num_hidden_layers %d", len(pattern), cfg.NumHiddenLayers)
+ }
+ cfg.LayerTypes = []byte(pattern)
+ for i, t := range cfg.LayerTypes {
+ switch t {
+ case 'M', '*', 'A', 'E', '-':
+ default:
+ return Config{}, fmt.Errorf("unsupported layer type %q at layer %d", t, i)
+ }
+ }
+
+ cfg.AttnScale = float32(1.0 / math.Sqrt(float64(cfg.HeadDim)))
+ return cfg, nil
+}
+
+func newModel(root *model.Root) (base.Model, error) {
+ configData, err := root.Manifest.ReadConfig("config.json")
+ if err != nil {
+ return nil, fmt.Errorf("load config: %w", err)
+ }
+ cfg, err := parseConfig(configData)
+ if err != nil {
+ return nil, err
+ }
+
+ if qt := root.QuantType(); qt != "" {
+ cfg.QuantGroupSize, cfg.QuantBits, cfg.QuantMode = model.QuantizationParams(qt)
+ if gs := root.GroupSize(); gs > 0 {
+ cfg.QuantGroupSize = gs
+ }
+ } else {
+ cfg.QuantGroupSize, cfg.QuantBits, cfg.QuantMode = model.QuantizationParams("")
+ }
+ cfg.TensorQuant = root.AllTensorQuant()
+
+ tokData, err := root.Manifest.ReadConfig("tokenizer.json")
+ if err != nil {
+ return nil, fmt.Errorf("load tokenizer config: %w", err)
+ }
+
+ tokConfig := &tokenizer.TokenizerConfig{ConfigJSON: configData}
+ if genConfigData, err := root.Manifest.ReadConfig("generation_config.json"); err == nil {
+ tokConfig.GenerationConfigJSON = genConfigData
+ }
+ if tokConfigData, err := root.Manifest.ReadConfig("tokenizer_config.json"); err == nil {
+ tokConfig.TokenizerConfigJSON = tokConfigData
+ }
+
+ tok, err := tokenizer.LoadFromBytesWithConfig(tokData, tokConfig)
+ if err != nil {
+ return nil, fmt.Errorf("parse tokenizer: %w", err)
+ }
+
+ m := &Model{
+ Layers: make([]*Layer, cfg.NumHiddenLayers),
+ Config: &cfg,
+ tok: tok,
+ }
+ for i, typ := range cfg.LayerTypes {
+ m.Layers[i] = &Layer{Type: typ}
+ }
+ return m, nil
+}
+
+type tensorPathLayout struct {
+ containerPrefix string
+ backbonePrefix string
+}
+
+func (l tensorPathLayout) path(suffix string) string {
+ return l.containerPrefix + l.backbonePrefix + suffix
+}
+
+func resolveTensorPathLayout(tensors map[string]*mlx.Array) tensorPathLayout {
+ for _, layout := range []tensorPathLayout{
+ {containerPrefix: "language_model.", backbonePrefix: "backbone."},
+ {containerPrefix: "", backbonePrefix: "backbone."},
+ {containerPrefix: "model.language_model.", backbonePrefix: "backbone."},
+ {containerPrefix: "language_model.", backbonePrefix: "model.backbone."},
+ {containerPrefix: "", backbonePrefix: "model.backbone."},
+ } {
+ if tensors[layout.path("embeddings.weight")] != nil {
+ return layout
+ }
+ }
+ return tensorPathLayout{containerPrefix: "language_model.", backbonePrefix: "backbone."}
+}
+
+func sanitizeConvWeight(w *mlx.Array) *mlx.Array {
+ if w == nil {
+ return nil
+ }
+ if w.NumDims() == 3 {
+ if w.Dim(1) == 1 {
+ return mlx.Reshape(w, int32(w.Dim(0)), int32(w.Dim(2)))
+ }
+ if w.Dim(2) == 1 {
+ return mlx.Reshape(w, int32(w.Dim(0)), int32(w.Dim(1)))
+ }
+ }
+ return w
+}
+
+func stackAndClone(parts []*mlx.Array) *mlx.Array {
+ if len(parts) == 0 {
+ return nil
+ }
+ stacked := mlx.Stack(parts, 0)
+ cloned := stacked.Clone()
+ mlx.Eval(cloned)
+ return cloned
+}
+
+func supportsGatherQMM(mode string, bits int) bool {
+ switch mode {
+ case "affine":
+ return bits == 4 || bits == 8
+ case "mxfp8":
+ return bits == 8
+ case "nvfp4", "mxfp4":
+ return bits == 4
+ default:
+ return false
+ }
+}
+
+func freeTensorKeys(tensors map[string]*mlx.Array, keys ...string) {
+ for _, key := range keys {
+ if key == "" {
+ continue
+ }
+ if tensors[key] != nil {
+ delete(tensors, key)
+ }
+ }
+}
+
+func combinedTensorGlobalScale(tensors map[string]*mlx.Array, key string) (*mlx.Array, []string) {
+ var keys []string
+ weightGlobal := tensors[key+".global_scale"]
+ if weightGlobal == nil {
+ weightGlobal = tensors[key+".weight.global_scale"]
+ }
+ if weightGlobal != nil {
+ keys = append(keys, key+".global_scale", key+".weight.global_scale")
+ }
+ if tensors[key+".input_global_scale"] != nil || tensors[key+".weight.input_global_scale"] != nil {
+ keys = append(keys, key+".input_global_scale", key+".weight.input_global_scale")
+ }
+ return weightGlobal, keys
+}
+
+func applyExpertWeightGlobalScale(weight, scale *mlx.Array) *mlx.Array {
+ if scale == nil {
+ return weight
+ }
+ if scale.DType() != weight.DType() {
+ scale = scale.AsType(weight.DType())
+ }
+ switch scale.NumDims() {
+ case 1:
+ if scale.Dim(0) == 1 {
+ break
+ }
+ if weight.NumDims() == 3 && scale.Dim(0) == weight.Dim(0) {
+ scale = mlx.Reshape(scale, int32(scale.Dim(0)), 1, 1)
+ } else if weight.NumDims() == 2 && scale.Dim(0) == weight.Dim(0) {
+ scale = mlx.Reshape(scale, int32(scale.Dim(0)), 1)
+ }
+ case 2:
+ if weight.NumDims() == 3 && scale.Dim(0) == weight.Dim(0) && scale.Dim(1) == weight.Dim(1) {
+ scale = mlx.ExpandDims(scale, -1)
+ }
+ }
+ return mlx.Mul(weight, scale)
+}
+
+func transposeExpertWeightForGatherMM(w *mlx.Array) *mlx.Array {
+ if w == nil || !w.Valid() || w.NumDims() != 3 {
+ return w
+ }
+ t := mlx.Transpose(w, 0, 2, 1)
+ cloned := t.Clone()
+ mlx.Eval(cloned)
+ return cloned
+}
+
+func sliceAxis(a *mlx.Array, axis int, start, stop int32) *mlx.Array {
+ dims := a.Dims()
+ starts := make([]int32, len(dims))
+ stops := make([]int32, len(dims))
+ for i, d := range dims {
+ stops[i] = int32(d)
+ }
+ starts[axis] = start
+ stops[axis] = stop
+ return mlx.SliceStartStop(a, starts, stops)
+}
+
+func appendAndClone(dst, src *mlx.Array) *mlx.Array {
+ out := mlx.Concatenate([]*mlx.Array{dst, src}, 0).Clone()
+ mlx.Eval(out)
+ return out
+}
+
+func stackSlicesAndClone(slices []*mlx.Array) *mlx.Array {
+ if len(slices) == 0 {
+ return nil
+ }
+ out := mlx.Stack(slices, 0).Clone()
+ mlx.Eval(out)
+ return out
+}
+
+func foldSharedExperts(m *SparseMoE, cfg *Config) bool {
+ if m == nil || cfg == nil || cfg.NSharedExperts != 1 {
+ return false
+ }
+ if cfg.MoEIntermediateSize <= 0 || cfg.MoESharedExpertIntermediateSize <= 0 {
+ return false
+ }
+ if cfg.MoESharedExpertIntermediateSize%cfg.MoEIntermediateSize != 0 {
+ return false
+ }
+ parts := cfg.MoESharedExpertIntermediateSize / cfg.MoEIntermediateSize
+ if parts <= 0 {
+ return false
+ }
+
+ if !m.UseQuantized || !foldQuantizedSharedExperts(m, cfg, parts) {
+ return false
+ }
+
+ m.FoldedSharedExperts = parts
+ m.SharedUp = nil
+ m.SharedDown = nil
+ return true
+}
+
+func foldQuantizedSharedExperts(m *SparseMoE, cfg *Config, parts int32) bool {
+ up, ok := m.SharedUp.(*nn.QuantizedLinear)
+ if !ok || up == nil {
+ return false
+ }
+ down, ok := m.SharedDown.(*nn.QuantizedLinear)
+ if !ok || down == nil {
+ return false
+ }
+ if up.Bias != nil || up.GlobalScale != nil || down.Bias != nil || down.GlobalScale != nil {
+ return false
+ }
+ if m.UpWeightQ == nil || m.UpScales == nil || m.DownWeightQ == nil || m.DownScales == nil {
+ return false
+ }
+ if up.GroupSize != m.UpGroupSize || up.Bits != m.UpBits || up.Mode != m.UpMode {
+ return false
+ }
+ if down.GroupSize != m.DownGroupSize || down.Bits != m.DownBits || down.Mode != m.DownMode {
+ return false
+ }
+ if (up.QBiases == nil) != (m.UpBiases == nil) || (down.QBiases == nil) != (m.DownBiases == nil) {
+ return false
+ }
+ if up.Weight.Dim(0) != int(cfg.MoESharedExpertIntermediateSize) || down.Weight.Dim(0) != int(cfg.HiddenSize) {
+ return false
+ }
+
+ upWeightStack := stackQuantizedUpParts(up.Weight, cfg.MoEIntermediateSize, parts)
+ upScaleStack := stackQuantizedUpParts(up.Scales, cfg.MoEIntermediateSize, parts)
+ if upWeightStack == nil || upScaleStack == nil {
+ return false
+ }
+ if upWeightStack.Dim(1) != m.UpWeightQ.Dim(1) || upWeightStack.Dim(2) != m.UpWeightQ.Dim(2) {
+ return false
+ }
+ if upScaleStack.Dim(1) != m.UpScales.Dim(1) || upScaleStack.Dim(2) != m.UpScales.Dim(2) {
+ return false
+ }
+
+ downWeightStack := stackQuantizedDownParts(down.Weight, m.DownWeightQ.Dim(2), parts)
+ downScaleStack := stackQuantizedDownParts(down.Scales, m.DownScales.Dim(2), parts)
+ if downWeightStack == nil || downScaleStack == nil {
+ return false
+ }
+ if downWeightStack.Dim(1) != m.DownWeightQ.Dim(1) || downWeightStack.Dim(2) != m.DownWeightQ.Dim(2) {
+ return false
+ }
+ if downScaleStack.Dim(1) != m.DownScales.Dim(1) || downScaleStack.Dim(2) != m.DownScales.Dim(2) {
+ return false
+ }
+
+ var upBiasStack, downBiasStack *mlx.Array
+ if m.UpBiases != nil {
+ upBiasStack = stackQuantizedUpParts(up.QBiases, cfg.MoEIntermediateSize, parts)
+ if upBiasStack == nil || upBiasStack.Dim(1) != m.UpBiases.Dim(1) || upBiasStack.Dim(2) != m.UpBiases.Dim(2) {
+ return false
+ }
+ }
+ if m.DownBiases != nil {
+ downBiasStack = stackQuantizedDownParts(down.QBiases, m.DownBiases.Dim(2), parts)
+ if downBiasStack == nil || downBiasStack.Dim(1) != m.DownBiases.Dim(1) || downBiasStack.Dim(2) != m.DownBiases.Dim(2) {
+ return false
+ }
+ }
+
+ m.UpWeightQ = appendAndClone(m.UpWeightQ, upWeightStack)
+ m.UpScales = appendAndClone(m.UpScales, upScaleStack)
+ m.DownWeightQ = appendAndClone(m.DownWeightQ, downWeightStack)
+ m.DownScales = appendAndClone(m.DownScales, downScaleStack)
+ if upBiasStack != nil {
+ m.UpBiases = appendAndClone(m.UpBiases, upBiasStack)
+ }
+ if downBiasStack != nil {
+ m.DownBiases = appendAndClone(m.DownBiases, downBiasStack)
+ }
+
+ return true
+}
+
+func stackQuantizedUpParts(a *mlx.Array, partSize int32, parts int32) *mlx.Array {
+ if a == nil || a.NumDims() != 2 || a.Dim(0) != int(partSize*parts) {
+ return nil
+ }
+ slices := make([]*mlx.Array, 0, parts)
+ for i := range parts {
+ start := i * partSize
+ slices = append(slices, sliceAxis(a, 0, start, start+partSize))
+ }
+ return stackSlicesAndClone(slices)
+}
+
+func stackQuantizedDownParts(a *mlx.Array, packedPartSize int, parts int32) *mlx.Array {
+ if a == nil || a.NumDims() != 2 || packedPartSize <= 0 || a.Dim(1) != packedPartSize*int(parts) {
+ return nil
+ }
+ slices := make([]*mlx.Array, 0, parts)
+ for i := range parts {
+ start := int(i) * packedPartSize
+ slices = append(slices, sliceAxis(a, 1, int32(start), int32(start+packedPartSize)))
+ }
+ return stackSlicesAndClone(slices)
+}
+
+func tensorAny(tensors map[string]*mlx.Array, keys ...string) (*mlx.Array, string) {
+ for _, k := range keys {
+ if v := tensors[k]; v != nil {
+ return v, k
+ }
+ }
+ return nil, ""
+}
+
+func tensorByBase(tensors map[string]*mlx.Array, base string) (*mlx.Array, string) {
+ return tensorAny(tensors, base+".weight", base)
+}
+
+// loadStackedExpertProjection loads a pre-stacked [experts, out, in] expert
+// tensor (as produced by ollama create's TransformStackExperts). It returns
+// nil if no stacked tensor is found, so the caller can fall back to
+// per-expert collection.
+func loadStackedExpertProjection(tensors map[string]*mlx.Array, cfg *Config, useQuantized bool, layerPrefix, proj string) *stackedExpertWeights {
+ base := fmt.Sprintf("%s.mixer.experts.%s", layerPrefix, proj)
+ w, key := tensorByBase(tensors, base)
+ if w == nil {
+ return nil
+ }
+
+ scales := tensors[key+"_scale"]
+ globalScale, globalScaleKeys := combinedTensorGlobalScale(tensors, key)
+ if scales == nil {
+ freeTensorKeys(tensors, append([]string{key}, globalScaleKeys...)...)
+ return &stackedExpertWeights{Weight: applyExpertWeightGlobalScale(w, globalScale)}
+ }
+
+ qbiases := tensors[key+"_qbias"]
+ groupSize, bits, mode := model.ResolveLinearQuantParams(
+ cfg.QuantGroupSize, cfg.QuantBits, cfg.QuantMode, cfg.TensorQuant,
+ key, w, scales,
+ )
+
+ freeTensorKeys(tensors, append([]string{key, key + "_scale"}, globalScaleKeys...)...)
+ if qbiases != nil {
+ freeTensorKeys(tensors, key+"_qbias")
+ }
+
+ if useQuantized && supportsGatherQMM(mode, bits) && globalScale == nil {
+ return &stackedExpertWeights{
+ Weight: w,
+ Scales: scales,
+ Biases: qbiases,
+ Bits: bits,
+ GroupSize: groupSize,
+ Mode: mode,
+ }
+ }
+
+ return &stackedExpertWeights{
+ Weight: applyExpertWeightGlobalScale(mlx.Dequantize(w, scales, qbiases, groupSize, bits, mode, nil), globalScale),
+ Bits: bits,
+ GroupSize: groupSize,
+ Mode: mode,
+ }
+}
+
+func collectExpertProjection(tensors map[string]*mlx.Array, cfg *Config, useQuantized bool, layerPrefix, proj string, numExperts int32) *stackedExpertWeights {
+ weights := make([]*mlx.Array, 0, numExperts)
+ scales := make([]*mlx.Array, 0, numExperts)
+ biases := make([]*mlx.Array, 0, numExperts)
+ consumed := make([]string, 0, numExperts*3)
+ bits := 0
+ groupSize := 0
+ mode := cfg.QuantMode
+
+ for e := range numExperts {
+ key := fmt.Sprintf("%s.mixer.experts.%d.%s.weight", layerPrefix, e, proj)
+ w := tensors[key]
+ if w == nil {
+ return nil
+ }
+ consumed = append(consumed, key)
+
+ scaleKey := key + "_scale"
+ scale := tensors[scaleKey]
+ if scale == nil {
+ weights = append(weights, w)
+ continue
+ }
+
+ consumed = append(consumed, scaleKey)
+ qbiasKey := key + "_qbias"
+ qbias := tensors[qbiasKey]
+ if qbias != nil {
+ consumed = append(consumed, qbiasKey)
+ }
+ globalScale, globalScaleKeys := combinedTensorGlobalScale(tensors, key)
+ consumed = append(consumed, globalScaleKeys...)
+
+ gs, b, m := model.ResolveLinearQuantParams(
+ cfg.QuantGroupSize,
+ cfg.QuantBits,
+ cfg.QuantMode,
+ cfg.TensorQuant,
+ key,
+ w,
+ scale,
+ )
+ if bits == 0 {
+ bits = b
+ groupSize = gs
+ mode = m
+ }
+ if useQuantized && supportsGatherQMM(m, b) && globalScale == nil {
+ weights = append(weights, w)
+ scales = append(scales, scale)
+ if qbias != nil {
+ biases = append(biases, qbias)
+ }
+ continue
+ }
+
+ weights = append(weights, applyExpertWeightGlobalScale(mlx.Dequantize(w, scale, qbias, gs, b, m, nil), globalScale))
+ }
+
+ out := &stackedExpertWeights{
+ Weight: stackAndClone(weights),
+ Bits: bits,
+ GroupSize: groupSize,
+ Mode: mode,
+ }
+ if len(scales) == len(weights) {
+ out.Scales = stackAndClone(scales)
+ }
+ if len(biases) == len(weights) {
+ out.Biases = stackAndClone(biases)
+ }
+ freeTensorKeys(tensors, consumed...)
+ return out
+}
+
+func loadRMSNorm(tensors map[string]*mlx.Array, key string, eps float32) *nn.RMSNorm {
+ if weight := tensors[key]; weight != nil {
+ return nn.NewRMSNorm(weight, eps)
+ }
+ return nil
+}
+
+func loadRMSNormAny(tensors map[string]*mlx.Array, eps float32, keys ...string) *nn.RMSNorm {
+ for _, key := range keys {
+ if norm := loadRMSNorm(tensors, key, eps); norm != nil {
+ return norm
+ }
+ }
+ return nil
+}
+
+func makeLinearAny(linears model.LinearFactory, bases ...string) nn.LinearLayer {
+ for _, base := range bases {
+ if l := linears.Make(base); l != nil {
+ return l
+ }
+ }
+ return nil
+}
+
+func hasTensorByBase(tensors map[string]*mlx.Array, base string) bool {
+ t, _ := tensorByBase(tensors, base)
+ return t != nil
+}
+
+func hasMTPHeadTensors(tensors map[string]*mlx.Array) bool {
+ if hasTensorByBase(tensors, "mtp.fc") {
+ return true
+ }
+ for name, tensor := range tensors {
+ if tensor != nil && strings.HasPrefix(name, "mtp.layers.") && strings.HasSuffix(name, ".eh_proj.weight") {
+ return true
+ }
+ }
+ return false
+}
+
+func detectMTPLayerType(tensors map[string]*mlx.Array, layerPrefix string) (byte, error) {
+ mixerPrefix := layerPrefix + ".mixer"
+ switch {
+ case hasTensorByBase(tensors, mixerPrefix+".q_proj") ||
+ hasTensorByBase(tensors, mixerPrefix+".k_proj") ||
+ hasTensorByBase(tensors, mixerPrefix+".v_proj") ||
+ hasTensorByBase(tensors, mixerPrefix+".o_proj"):
+ return 'A', nil
+ case hasTensorByBase(tensors, mixerPrefix+".gate") ||
+ hasTensorByBase(tensors, mixerPrefix+".experts.up_proj") ||
+ tensors[mixerPrefix+".experts.0.up_proj.weight"] != nil:
+ return 'E', nil
+ case hasTensorByBase(tensors, mixerPrefix+".up_proj") ||
+ hasTensorByBase(tensors, mixerPrefix+".down_proj"):
+ return '-', nil
+ case hasTensorByBase(tensors, mixerPrefix+".in_proj") ||
+ tensors[mixerPrefix+".conv1d.weight"] != nil:
+ return 0, fmt.Errorf("recurrent MTP layers are not supported")
+ default:
+ return 0, fmt.Errorf("missing supported MTP mixer tensors")
+ }
+}
+
+func mtpLayerPrefixes(tensors map[string]*mlx.Array) ([]string, error) {
+ const prefix = "mtp.layers."
+ indices := map[int]struct{}{}
+
+ for name, tensor := range tensors {
+ if tensor == nil || !strings.HasPrefix(name, prefix) {
+ continue
+ }
+ rest := strings.TrimPrefix(name, prefix)
+ indexText, _, ok := strings.Cut(rest, ".")
+ if !ok {
+ continue
+ }
+ index, err := strconv.Atoi(indexText)
+ if err != nil {
+ continue
+ }
+ indices[index] = struct{}{}
+ }
+
+ if len(indices) == 0 {
+ return nil, fmt.Errorf("missing MTP layer tensors")
+ }
+ sorted := make([]int, 0, len(indices))
+ for index := range indices {
+ sorted = append(sorted, index)
+ }
+ sort.Ints(sorted)
+
+ prefixes := make([]string, len(sorted))
+ for i, index := range sorted {
+ prefixes[i] = fmt.Sprintf("mtp.layers.%d", index)
+ }
+ return prefixes, nil
+}
+
+func loadLayer(linears model.LinearFactory, tensors map[string]*mlx.Array, cfg *Config, layerPrefix string, typ byte, useQuantizedExperts bool) (*Layer, error) {
+ layer := &Layer{Type: typ}
+
+ norm := loadRMSNorm(tensors, layerPrefix+".norm.weight", cfg.LayerNormEpsilon)
+ if norm == nil {
+ return nil, fmt.Errorf("missing norm weight")
+ }
+ layer.Norm = norm
+
+ mixerPrefix := layerPrefix + ".mixer"
+ switch layer.Type {
+ case 'M':
+ mamba := &Mamba2{}
+ mamba.InProj = linears.Make(mixerPrefix + ".in_proj")
+ mamba.OutProj = linears.Make(mixerPrefix + ".out_proj")
+ convWeight := sanitizeConvWeight(tensors[mixerPrefix+".conv1d.weight"])
+ convBias := tensors[mixerPrefix+".conv1d.bias"]
+ mamba.DtBias = tensors[mixerPrefix+".dt_bias"]
+ aLog := tensors[mixerPrefix+".A_log"]
+ if aLog != nil {
+ mamba.A = mlx.Neg(mlx.Exp(aLog.AsType(mlx.DTypeFloat32)))
+ }
+ mamba.D = tensors[mixerPrefix+".D"]
+ mamba.NormWeight = tensors[mixerPrefix+".norm.weight"]
+ if mamba.InProj == nil || mamba.OutProj == nil || convWeight == nil || mamba.DtBias == nil || mamba.A == nil || mamba.D == nil || mamba.NormWeight == nil {
+ return nil, fmt.Errorf("missing mamba2 tensors")
+ }
+ if convWeight.NumDims() != 2 {
+ return nil, fmt.Errorf("conv1d weight must be 2D after sanitization, got %dD", convWeight.NumDims())
+ }
+ // The fused conv kernel needs weight, bias and input to agree on
+ // dtype. Promoting matches what the graph conv would do anyway.
+ convWeight = convWeight.AsType(mlx.DTypeFloat32)
+ if convBias != nil {
+ convBias = convBias.AsType(mlx.DTypeFloat32)
+ }
+ mamba.Conv1D = nn.NewConv1d(mlx.ExpandDims(convWeight, 2), convBias, 1, 0, 1, int32(convWeight.Dim(0)))
+ layer.Mamba = mamba
+ case '*', 'A':
+ attn := &Attention{
+ QProj: linears.Make(mixerPrefix + ".q_proj"),
+ KProj: linears.Make(mixerPrefix + ".k_proj"),
+ VProj: linears.Make(mixerPrefix + ".v_proj"),
+ OProj: linears.Make(mixerPrefix + ".o_proj"),
+ }
+ if attn.QProj == nil || attn.KProj == nil || attn.VProj == nil || attn.OProj == nil {
+ return nil, fmt.Errorf("missing attention projections")
+ }
+ layer.Attention = attn
+ case '-':
+ dense := &DenseMLP{
+ UpProj: linears.Make(mixerPrefix + ".up_proj"),
+ DownProj: linears.Make(mixerPrefix + ".down_proj"),
+ }
+ if dense.UpProj == nil || dense.DownProj == nil {
+ return nil, fmt.Errorf("missing dense mlp projections")
+ }
+ layer.Dense = dense
+ case 'E':
+ moe := &SparseMoE{
+ Router: linears.Make(mixerPrefix + ".gate"),
+ RouterWeight: tensors[mixerPrefix+".gate.weight"],
+ CorrectionBias: tensors[mixerPrefix+".gate.e_score_correction_bias"],
+ SharedUp: linears.Make(mixerPrefix + ".shared_experts.up_proj"),
+ SharedDown: linears.Make(mixerPrefix + ".shared_experts.down_proj"),
+ }
+ if moe.Router == nil || moe.RouterWeight == nil || moe.SharedUp == nil || moe.SharedDown == nil {
+ return nil, fmt.Errorf("missing moe router or shared expert projections")
+ }
+ if cfg.NRoutedExperts <= 0 || cfg.NumExpertsPerTok <= 0 {
+ return nil, fmt.Errorf("invalid moe config")
+ }
+ up := loadStackedExpertProjection(tensors, cfg, useQuantizedExperts, layerPrefix, "up_proj")
+ if up == nil {
+ up = collectExpertProjection(tensors, cfg, useQuantizedExperts, layerPrefix, "up_proj", cfg.NRoutedExperts)
+ }
+ down := loadStackedExpertProjection(tensors, cfg, useQuantizedExperts, layerPrefix, "down_proj")
+ if down == nil {
+ down = collectExpertProjection(tensors, cfg, useQuantizedExperts, layerPrefix, "down_proj", cfg.NRoutedExperts)
+ }
+ if up == nil || down == nil {
+ return nil, fmt.Errorf("missing routed expert weights")
+ }
+ if up.Scales != nil {
+ moe.UpWeightQ = up.Weight
+ moe.UpScales = up.Scales
+ moe.UpBiases = up.Biases
+ moe.UpGroupSize = up.GroupSize
+ moe.UpBits = up.Bits
+ moe.UpMode = up.Mode
+ } else {
+ moe.UpWeight = transposeExpertWeightForGatherMM(up.Weight)
+ }
+ if down.Scales != nil {
+ moe.DownWeightQ = down.Weight
+ moe.DownScales = down.Scales
+ moe.DownBiases = down.Biases
+ moe.DownGroupSize = down.GroupSize
+ moe.DownBits = down.Bits
+ moe.DownMode = down.Mode
+ } else {
+ moe.DownWeight = transposeExpertWeightForGatherMM(down.Weight)
+ }
+ moe.UseQuantized = moe.UpWeightQ != nil || moe.DownWeightQ != nil
+ if moe.UseQuantized {
+ foldSharedExperts(moe, cfg)
+ }
+ layer.MoE = moe
+ default:
+ return nil, fmt.Errorf("unsupported layer type %q", layer.Type)
+ }
+
+ return layer, nil
+}
+
+func (m *Model) loadMTPHead(linears model.LinearFactory, tensors map[string]*mlx.Array, useQuantizedExperts bool) error {
+ cfg := m.Config
+ layerPrefixes, err := mtpLayerPrefixes(tensors)
+ if err != nil {
+ return fmt.Errorf("mtp head: %w", err)
+ }
+ firstPrefix := layerPrefixes[0]
+ lastPrefix := layerPrefixes[len(layerPrefixes)-1]
+
+ head := &MTPHead{
+ Enorm: loadRMSNormAny(tensors, cfg.LayerNormEpsilon,
+ "mtp.pre_fc_norm_embedding.weight",
+ firstPrefix+".enorm.weight",
+ ),
+ Hnorm: loadRMSNormAny(tensors, cfg.LayerNormEpsilon,
+ "mtp.pre_fc_norm_hidden.weight",
+ firstPrefix+".hnorm.weight",
+ ),
+ FC: makeLinearAny(linears,
+ "mtp.fc",
+ firstPrefix+".eh_proj",
+ ),
+ Norm: loadRMSNormAny(tensors, cfg.LayerNormEpsilon,
+ "mtp.norm.weight",
+ "mtp.shared_head.norm.weight",
+ lastPrefix+".final_layernorm.weight",
+ ),
+ }
+ if head.Enorm == nil || head.Hnorm == nil || head.FC == nil || head.Norm == nil {
+ return fmt.Errorf("mtp head: missing enorm/hnorm/fc/norm tensors")
+ }
+
+ head.Layers = make([]*Layer, len(layerPrefixes))
+ for i, layerPrefix := range layerPrefixes {
+ typ, err := detectMTPLayerType(tensors, layerPrefix)
+ if err != nil {
+ return fmt.Errorf("mtp layer %s: %w", layerPrefix, err)
+ }
+ layer, err := loadLayer(linears, tensors, cfg, layerPrefix, typ, useQuantizedExperts)
+ if err != nil {
+ return fmt.Errorf("mtp layer %s: %w", layerPrefix, err)
+ }
+ head.Layers[i] = layer
+ }
+ m.MTP = head
+ return nil
+}
+
+func (m *Model) LoadWeights(tensors map[string]*mlx.Array) error {
+ layout := resolveTensorPathLayout(tensors)
+ m.weightPrefix = layout.containerPrefix
+ backbonePrefix := layout.containerPrefix + layout.backbonePrefix
+ cfg := m.Config
+
+ linears := model.NewLinearFactory(tensors, cfg.QuantGroupSize, cfg.QuantBits, cfg.QuantMode, cfg.TensorQuant)
+ useQuantizedExperts := supportsGatherQMM(cfg.QuantMode, cfg.QuantBits)
+ if !useQuantizedExperts && cfg.TensorQuant != nil {
+ for _, tq := range cfg.TensorQuant {
+ if tq == nil {
+ continue
+ }
+ _, bits, mode := model.QuantizationParams(tq.QuantType)
+ if supportsGatherQMM(mode, bits) {
+ useQuantizedExperts = true
+ break
+ }
+ }
+ }
+
+ m.EmbedTokens = model.MakeEmbeddingLayer(tensors, backbonePrefix+"embeddings", cfg.QuantGroupSize, cfg.QuantBits, cfg.QuantMode, cfg.TensorQuant)
+ if m.EmbedTokens == nil {
+ return fmt.Errorf("missing embedding weight: %sembeddings.weight", backbonePrefix)
+ }
+
+ normWeight := tensors[backbonePrefix+"norm_f.weight"]
+ if normWeight == nil {
+ return fmt.Errorf("missing final norm weight: %snorm_f.weight", backbonePrefix)
+ }
+ m.Norm = nn.NewRMSNorm(normWeight, cfg.LayerNormEpsilon)
+
+ if cfg.TieWordEmbeddings {
+ m.LMHead = m.EmbedTokens.AsLinear()
+ } else if head := linears.Make(layout.containerPrefix + "lm_head"); head != nil {
+ m.LMHead = head
+ } else if head := linears.Make("lm_head"); head != nil {
+ m.LMHead = head
+ } else {
+ m.LMHead = m.EmbedTokens.AsLinear()
+ }
+
+ for i := range cfg.NumHiddenLayers {
+ layerPrefix := fmt.Sprintf("%slayers.%d", backbonePrefix, i)
+ layer, err := loadLayer(linears, tensors, cfg, layerPrefix, cfg.LayerTypes[i], useQuantizedExperts)
+ if err != nil {
+ return fmt.Errorf("layer %d: %w", i, err)
+ }
+ m.Layers[i] = layer
+ }
+ if hasMTPHeadTensors(tensors) {
+ if err := m.loadMTPHead(linears, tensors, useQuantizedExperts); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func (m *Mamba2) Forward(x *mlx.Array, b *batch.Batch, c cache.Cache, B, L int32, cfg *Config) *mlx.Array {
+ dtype := x.DType()
+ projected := m.InProj.Forward(x)
+ inner := cfg.MambaNumHeads * cfg.MambaHeadDim
+ convDim := inner + 2*cfg.NGroups*cfg.SSMStateSize
+
+ gate := mlx.SliceStartStop(projected, []int32{0, 0, 0}, []int32{B, L, inner})
+ xBC := mlx.SliceStartStop(projected, []int32{0, 0, inner}, []int32{B, L, inner + convDim}).AsType(mlx.DTypeFloat32)
+ dt := mlx.SliceStartStop(projected, []int32{0, 0, inner + convDim}, []int32{B, L, inner + convDim + cfg.MambaNumHeads})
+
+ convTail := cfg.ConvKernel - 1
+ var rc *cache.RecurrentCache
+ opts := make([]nn.RecurrentOption, 0, 3)
+ opts = append(opts, nn.WithConvSiLU())
+ if typed, ok := c.(*cache.RecurrentCache); ok {
+ rc = typed
+ opts = append(opts, nn.WithRecurrentHistory(rc.Get(b, mlx.DTypeFloat32)))
+ if splits := rc.SnapshotSplits(int(L)); len(splits) > 0 {
+ opts = append(opts, nn.WithSnapshotSplits(splits))
+ }
+ } else {
+ opts = append(opts, nn.WithRecurrentState(
+ mlx.Zeros(mlx.DTypeFloat32, int(B), int(convTail), int(convDim)),
+ mlx.Zeros(mlx.DTypeFloat32, int(B), int(cfg.MambaNumHeads), int(cfg.MambaHeadDim), int(cfg.SSMStateSize))))
+ }
+
+ convOut, convStates := nn.CausalConv1D(b, xBC, m.Conv1D, int(convTail), opts...)
+ if dtype != mlx.DTypeFloat32 {
+ convOut = convOut.AsType(dtype).AsType(mlx.DTypeFloat32)
+ }
+
+ hidden := mlx.SliceStartStop(convOut, []int32{0, 0, 0}, []int32{B, L, inner})
+ bState := mlx.SliceStartStop(convOut, []int32{0, 0, inner}, []int32{B, L, inner + cfg.NGroups*cfg.SSMStateSize})
+ cState := mlx.SliceStartStop(convOut, []int32{0, 0, inner + cfg.NGroups*cfg.SSMStateSize}, []int32{B, L, inner + 2*cfg.NGroups*cfg.SSMStateSize})
+
+ hidden = mlx.Reshape(hidden, B, L, cfg.MambaNumHeads, cfg.MambaHeadDim)
+ bState = mlx.Reshape(bState, B, L, cfg.NGroups, cfg.SSMStateSize)
+ cState = mlx.Reshape(cState, B, L, cfg.NGroups, cfg.SSMStateSize)
+
+ y, deltaStates := nn.Mamba2Scan(b, hidden, bState, cState, dt.AsType(mlx.DTypeFloat32),
+ mlx.Reshape(m.A.AsType(mlx.DTypeFloat32), cfg.MambaNumHeads),
+ mlx.Reshape(m.D.AsType(mlx.DTypeFloat32), cfg.MambaNumHeads),
+ mlx.Reshape(m.DtBias.AsType(mlx.DTypeFloat32), cfg.MambaNumHeads),
+ opts...)
+
+ y = mlx.Reshape(y, B, L, inner)
+ y = gatedGroupRMSNorm(y, gate, m.NormWeight, cfg, dtype)
+ out := m.OutProj.Forward(y)
+ if rc != nil {
+ rc.Put(b, convStates, deltaStates)
+ }
+ return out
+}
+
+// gatedGroupRMSNorm computes RMSNorm(y * SiLU(gate), groups) * weight. The
+// weight varies across groups while the norm reduces within one, so it is a
+// separate multiply rather than the norm's own weight argument.
+func gatedGroupRMSNorm(y, gate, weight *mlx.Array, cfg *Config, dtype mlx.DType) *mlx.Array {
+ inner := cfg.MambaNumHeads * cfg.MambaHeadDim
+ dims := y.Dims()
+ B, L := int32(dims[0]), int32(dims[1])
+ groupSize := inner / cfg.NGroups
+
+ y = mlx.Mul(y, mlx.SiLU(gate.AsType(y.DType())))
+ y = mlx.RMSNormFn(mlx.Reshape(y, B, L, cfg.NGroups, groupSize), nil, cfg.LayerNormEpsilon)
+ y = mlx.Mul(y, mlx.Reshape(weight.AsType(y.DType()), 1, 1, cfg.NGroups, groupSize))
+ return mlx.Reshape(y, B, L, inner).AsType(dtype)
+}
+
+func (a *Attention) Forward(x *mlx.Array, b *batch.Batch, c cache.Cache, B, L int32, cfg *Config) *mlx.Array {
+ q := a.QProj.Forward(x)
+ k := a.KProj.Forward(x)
+ v := a.VProj.Forward(x)
+
+ q = mlx.Reshape(q, B, L, cfg.NumAttentionHeads, cfg.HeadDim)
+ k = mlx.Reshape(k, B, L, cfg.NumKeyValueHeads, cfg.HeadDim)
+ v = mlx.Reshape(v, B, L, cfg.NumKeyValueHeads, cfg.HeadDim)
+
+ q = mlx.Transpose(q, 0, 2, 1, 3)
+ k = mlx.Transpose(k, 0, 2, 1, 3)
+ v = mlx.Transpose(v, 0, 2, 1, 3)
+
+ var kv nn.SDPAOption
+ if c != nil {
+ history := c.(cache.Attention).Update(b, k, v)
+ kv = nn.WithKVHistory(history)
+ } else {
+ kv = nn.WithKV(k, v, b.SeqQueryLens)
+ }
+
+ out := nn.ScaledDotProductAttention(b, q, cfg.AttnScale, kv, nn.WithMask(nn.CausalMask()))
+ out = mlx.Reshape(mlx.Transpose(out, 0, 2, 1, 3), B, L, cfg.NumAttentionHeads*cfg.HeadDim)
+ out = a.OProj.Forward(out)
+ return out
+}
+
+func (m *DenseMLP) Forward(x *mlx.Array) *mlx.Array {
+ up := m.UpProj.Forward(x)
+ hidden := mlx.ReLUSquared(up)
+ out := m.DownProj.Forward(hidden)
+ return out
+}
+
+func shouldSortMoEExperts(tokens int32) bool {
+ return tokens >= 64
+}
+
+func (m *SparseMoE) gatherExpertUp(xFlat, idxFlat *mlx.Array, doSort bool) *mlx.Array {
+ if m.UpWeightQ != nil {
+ return mlx.GatherQMM(
+ xFlat,
+ m.UpWeightQ,
+ m.UpScales,
+ m.UpBiases,
+ nil,
+ idxFlat,
+ true,
+ m.UpGroupSize,
+ m.UpBits,
+ m.UpMode,
+ doSort,
+ )
+ }
+ return mlx.GatherMM(xFlat, m.UpWeight, nil, idxFlat, doSort)
+}
+
+func (m *SparseMoE) gatherExpertDown(hidden, idxFlat *mlx.Array, doSort bool) *mlx.Array {
+ if m.DownWeightQ != nil {
+ return mlx.GatherQMM(
+ hidden,
+ m.DownWeightQ,
+ m.DownScales,
+ m.DownBiases,
+ nil,
+ idxFlat,
+ true,
+ m.DownGroupSize,
+ m.DownBits,
+ m.DownMode,
+ doSort,
+ )
+ }
+ return mlx.GatherMM(hidden, m.DownWeight, nil, idxFlat, doSort)
+}
+
+func (m *SparseMoE) expertForward(x *mlx.Array, indices *mlx.Array, cfg *Config) *mlx.Array {
+ dims := x.Dims()
+ B, L := int32(dims[0]), int32(dims[1])
+ topK := int32(indices.Dim(2))
+
+ xExpanded := mlx.ExpandDims(mlx.ExpandDims(x, -2), -2)
+ xFlat := mlx.Reshape(xExpanded, B*L, 1, 1, cfg.HiddenSize)
+ idxFlat := mlx.Reshape(indices, B*L, topK)
+
+ doSort := shouldSortMoEExperts(B * L)
+ var invOrder *mlx.Array
+ n := B * L * topK
+ if doSort {
+ idxAll := mlx.Flatten(idxFlat)
+ order := mlx.Argsort(idxAll, 0)
+ invOrder = mlx.Argsort(order, 0)
+ tokenOrder := mlx.FloorDivideScalar(order, topK)
+ xFlat = mlx.ExpandDims(mlx.Take(mlx.Squeeze(xFlat, 1), tokenOrder, 0), 1)
+ idxFlat = mlx.Reshape(mlx.Take(idxAll, order, 0), n, 1)
+ }
+
+ up := m.gatherExpertUp(xFlat, idxFlat, doSort)
+
+ hidden := mlx.ReLUSquared(up)
+ if hidden.DType() != up.DType() {
+ // Keep the activation in the projection dtype so dense and quantized
+ // down projections stay on the BF16 fast path.
+ hidden = hidden.AsType(up.DType())
+ }
+ down := m.gatherExpertDown(hidden, idxFlat, doSort)
+
+ if doSort {
+ down = mlx.Reshape(mlx.Take(mlx.Squeeze(mlx.Squeeze(down, 2), 1), invOrder, 0), B*L, topK, cfg.HiddenSize)
+ } else {
+ down = mlx.Squeeze(down, 2)
+ }
+ return mlx.Reshape(down, B, L, topK, cfg.HiddenSize)
+}
+
+func appendFoldedSharedExperts(inds, scores *mlx.Array, cfg *Config, folded int32) (*mlx.Array, *mlx.Array) {
+ if folded <= 0 {
+ return inds, scores
+ }
+ dims := inds.Dims()
+ B, L := int32(dims[0]), int32(dims[1])
+
+ sharedInds := make([]*mlx.Array, 0, folded+1)
+ sharedInds = append(sharedInds, inds)
+ for i := range folded {
+ idx := mlx.AddScalar(mlx.Zeros(mlx.DTypeInt32, int(B), int(L), 1), float32(cfg.NRoutedExperts+i))
+ if idx.DType() != inds.DType() {
+ idx = idx.AsType(inds.DType())
+ }
+ sharedInds = append(sharedInds, idx)
+ }
+ inds = mlx.Concatenate(sharedInds, 2)
+
+ ones := mlx.AddScalar(mlx.Zeros(scores.DType(), int(B), int(L), int(folded)), 1)
+ scores = mlx.Concatenate([]*mlx.Array{scores, ones}, 2)
+ return inds, scores
+}
+
+func (m *SparseMoE) Forward(x *mlx.Array, cfg *Config) *mlx.Array {
+ dims := x.Dims()
+ B, L := int32(dims[0]), int32(dims[1])
+
+ inds, scores := m.route(x, cfg, B, L)
+ inds, scores = appendFoldedSharedExperts(inds, scores, cfg, m.FoldedSharedExperts)
+
+ expertOut := m.expertForward(x, inds, cfg)
+ y := moeWeightedSum(expertOut, scores, x.DType())
+ if m.FoldedSharedExperts > 0 {
+ return mlx.Reshape(y, B, L, cfg.HiddenSize)
+ }
+
+ sharedUp := m.SharedUp.Forward(x)
+ sharedHidden := mlx.ReLUSquared(sharedUp)
+ shared := m.SharedDown.Forward(sharedHidden)
+ y = mlx.Add(y, shared)
+ return mlx.Reshape(y, B, L, cfg.HiddenSize)
+}
+
+// moeWeightedSum reduces per-expert outputs [B, L, topK, H] by their scores
+// [B, L, topK]. A matmul with a one-row left operand, so it rides MLX's
+// existing matmul kernels instead of materializing the elementwise product.
+func moeWeightedSum(expertOut, scores *mlx.Array, dtype mlx.DType) *mlx.Array {
+ scores = mlx.ExpandDims(scores.AsType(expertOut.DType()), 2)
+ return mlx.Squeeze(mlx.Matmul(scores, expertOut), 2).AsType(dtype)
+}
+
+func (m *SparseMoE) route(x *mlx.Array, cfg *Config, B, L int32) (*mlx.Array, *mlx.Array) {
+ routeDType := mlx.DTypeFloat32
+
+ routerWeight := mlx.Transpose(m.RouterWeight.AsType(routeDType), 1, 0)
+ logits := mlx.Matmul(x.AsType(routeDType), routerWeight)
+
+ var probs, selection, negSelection *mlx.Array
+ if m.CorrectionBias != nil {
+ // The fused helper returns both the unbiased sigmoid probabilities
+ // used for scores and the negated bias-corrected values used for top-k.
+ probs, negSelection = mlx.SigmoidRouter(logits, m.CorrectionBias.AsType(routeDType))
+ } else {
+ probs = mlx.Sigmoid(logits)
+ selection = probs
+ }
+ if cfg.ExpertGroupCount > 1 && cfg.ExpertGroupUsedCount > 0 && cfg.ExpertGroupUsedCount < cfg.ExpertGroupCount {
+ if selection == nil {
+ selection = mlx.Neg(negSelection)
+ }
+ expertsPerGroup := cfg.NRoutedExperts / cfg.ExpertGroupCount
+ grouped := mlx.Reshape(selection, B, L, cfg.ExpertGroupCount, expertsPerGroup)
+ topPerGroup := expertsPerGroup
+ if topPerGroup > 2 {
+ topPerGroup = 2
+ }
+ if topPerGroup > 0 {
+ groupInds := mlx.Argpartition(mlx.Neg(grouped), int(topPerGroup)-1, -1)
+ groupInds = mlx.SliceStartStop(groupInds, []int32{0, 0, 0, 0}, []int32{B, L, cfg.ExpertGroupCount, topPerGroup})
+ groupScores := mlx.Sum(mlx.TakeAlongAxis(grouped, groupInds, -1), -1, false)
+ activeGroups := mlx.Argpartition(mlx.Neg(groupScores), int(cfg.ExpertGroupUsedCount)-1, -1)
+ activeGroups = mlx.SliceStartStop(activeGroups, []int32{0, 0, 0}, []int32{B, L, cfg.ExpertGroupUsedCount})
+ mask := mlx.Zeros(selection.DType(), int(B), int(L), int(cfg.ExpertGroupCount))
+ values := mlx.AddScalar(mlx.Zeros(selection.DType(), int(B), int(L), int(cfg.ExpertGroupUsedCount)), 1)
+ mask = mask.PutAlongAxis(activeGroups, values, -1)
+ mask = mlx.Reshape(
+ mlx.Tile(mlx.ExpandDims(mask, -1), []int32{1, 1, 1, expertsPerGroup}),
+ B, L, cfg.NRoutedExperts,
+ )
+ selection = mlx.Mul(selection, mask)
+ negSelection = nil
+ }
+ }
+
+ if negSelection == nil {
+ negSelection = mlx.Neg(selection)
+ }
+ inds := mlx.Argpartition(negSelection, int(cfg.NumExpertsPerTok)-1, -1)
+ inds = mlx.SliceStartStop(inds, []int32{0, 0, 0}, []int32{B, L, cfg.NumExpertsPerTok})
+
+ scores := mlx.TakeAlongAxis(probs, inds, -1)
+ if cfg.NormTopKProb && cfg.NumExpertsPerTok > 1 {
+ sumScores := mlx.AddScalar(mlx.Sum(scores, 2, true), 1e-20)
+ scores = mlx.Div(scores, sumScores)
+ }
+ if cfg.RoutedScalingFactor != 1 {
+ scores = mlx.MulScalar(scores, cfg.RoutedScalingFactor)
+ }
+
+ return inds, scores
+}
+
+func (l *Layer) Forward(x *mlx.Array, b *batch.Batch, c cache.Cache, B, L int32, cfg *Config) *mlx.Array {
+ residual := x
+ h := l.Norm.Forward(x, cfg.LayerNormEpsilon)
+ switch l.Type {
+ case 'M':
+ h = l.Mamba.Forward(h, b, c, B, L, cfg)
+ case '*', 'A':
+ h = l.Attention.Forward(h, b, c, B, L, cfg)
+ case '-':
+ h = l.Dense.Forward(h)
+ case 'E':
+ h = l.MoE.Forward(h, cfg)
+ }
+ if h.DType() != residual.DType() {
+ h = h.AsType(residual.DType())
+ }
+ out := mlx.Add(residual, h)
+ return out
+}
+
+func (m *Model) Forward(b *batch.Batch, caches []cache.Cache) (hidden, auxHidden *mlx.Array) {
+ tokens := b.InputIDs
+ dims := tokens.Dims()
+ B, L := int32(dims[0]), int32(dims[1])
+
+ h := m.EmbedTokens.Forward(tokens)
+ for i, layer := range m.Layers {
+ var c cache.Cache
+ if caches != nil && i < len(caches) {
+ c = caches[i]
+ }
+ h = layer.Forward(h, b, c, B, L, m.Config)
+ }
+ h = m.Norm.Forward(h, m.LayerNormEpsilon)
+ return h, h
+}
+
+func (m *Model) Unembed(x *mlx.Array) *mlx.Array {
+ return m.LMHead.Forward(x)
+}
+
+// mtpDraft is the model viewed as its own draft: the same struct, carrying
+// the DraftModel method set for the inline MTP head.
+type mtpDraft Model
+
+// SelfDraft returns the model's drafting view, or nil when no MTP head was
+// loaded. The methods exist either way, so this is what decides availability.
+func (m *Model) SelfDraft() base.DraftModel {
+ if m.MTP == nil {
+ return nil
+ }
+ return (*mtpDraft)(m)
+}
+
+// LoadWeights does nothing: an inline head's weights load with the target's.
+func (m *mtpDraft) LoadWeights(map[string]*mlx.Array) error { return nil }
+
+func (m *mtpDraft) Unembed(x *mlx.Array) *mlx.Array { return (*Model)(m).Unembed(x) }
+
+// NewCaches builds one slot per MTP layer that keeps state; layers that keep
+// none (MoE, dense) contribute nothing.
+func (m *mtpDraft) NewCaches() []cache.Cache {
+ if m.MTP == nil {
+ return nil
+ }
+ caches := make([]cache.Cache, 0, mtpCacheCount(m.MTP))
+ for _, layer := range m.MTP.Layers {
+ if c := newMTPLayerCache(layer); c != nil {
+ caches = append(caches, c)
+ }
+ }
+ return caches
+}
+
+// Forward runs one MTP step; the head's hidden also serves as the aux hidden
+// seeding the next step.
+func (m *mtpDraft) Forward(b *batch.Batch, _, draftCaches []cache.Cache) (hidden, auxHidden *mlx.Array) {
+ dims := b.InputIDs.Dims()
+ B, L := int32(dims[0]), int32(dims[1])
+
+ emb := m.MTP.Enorm.Forward(m.EmbedTokens.Forward(b.InputIDs), m.LayerNormEpsilon)
+ h := m.MTP.Hnorm.Forward(b.Hidden, m.LayerNormEpsilon)
+ fused := m.MTP.FC.Forward(emb.Concatenate(-1, h))
+
+ cacheIndex := 0
+ for _, layer := range m.MTP.Layers {
+ var c cache.Cache
+ if mtpLayerUsesCache(layer) && cacheIndex < len(draftCaches) {
+ c = draftCaches[cacheIndex]
+ cacheIndex++
+ }
+ fused = layer.Forward(fused, b, c, B, L, m.Config)
+ }
+ hidden = m.MTP.Norm.Forward(fused, m.LayerNormEpsilon)
+ return hidden, hidden
+}
+
+func (m *Model) NumLayers() int {
+ return len(m.Layers)
+}
+
+func (m *Model) Tokenizer() *tokenizer.Tokenizer {
+ return m.tok
+}
+
+func (m *Model) MaxContextLength() int {
+ return int(m.MaxPositionEmbeddings)
+}
+
+func (m *Model) NewCaches() []cache.Cache {
+ caches := make([]cache.Cache, len(m.Layers))
+ for i, layer := range m.Layers {
+ caches[i] = newLayerCache(layer, m.Config)
+ }
+ return caches
+}
+
+func newLayerCache(layer *Layer, cfg *Config) cache.Cache {
+ if layer == nil {
+ return nil
+ }
+ switch layer.Type {
+ case 'M':
+ return cache.NewRecurrentCache(cfg.ConvKernel-1, cfgConvDim(cfg), cfg.MambaNumHeads, cfg.MambaHeadDim, cfg.SSMStateSize)
+ case '*', 'A':
+ return cache.NewKVCache()
+ default:
+ return nil
+ }
+}
+
+func mtpLayerUsesCache(layer *Layer) bool {
+ return layer != nil && (layer.Type == '*' || layer.Type == 'A')
+}
+
+func mtpCacheCount(head *MTPHead) int {
+ if head == nil {
+ return 0
+ }
+ count := 0
+ for _, layer := range head.Layers {
+ if mtpLayerUsesCache(layer) {
+ count++
+ }
+ }
+ return count
+}
+
+func newMTPLayerCache(layer *Layer) cache.Cache {
+ if mtpLayerUsesCache(layer) {
+ return cache.NewKVCache()
+ }
+ return nil
+}
+
+func cfgConvDim(cfg *Config) int32 {
+ inner := cfg.MambaNumHeads * cfg.MambaHeadDim
+ return inner + 2*cfg.NGroups*cfg.SSMStateSize
+}
diff --git a/x/models/nemotron_h/nemotron_h_test.go b/x/models/nemotron_h/nemotron_h_test.go
new file mode 100644
index 000000000..db2bd3cc9
--- /dev/null
+++ b/x/models/nemotron_h/nemotron_h_test.go
@@ -0,0 +1,396 @@
+package nemotron_h
+
+import (
+ "math"
+ "slices"
+ "strings"
+ "testing"
+
+ "github.com/ollama/ollama/x/internal/mlxtest"
+ "github.com/ollama/ollama/x/mlxrunner/cache"
+ "github.com/ollama/ollama/x/mlxrunner/mlx"
+)
+
+func TestParseConfigNestedWrapper(t *testing.T) {
+ cfg, err := parseConfig([]byte(`{
+ "architectures": ["NemotronH_Nano_VL_V2"],
+ "model_type": "NemotronH_Nano_VL_V2",
+ "llm_config": {
+ "model_type": "nemotron_h",
+ "hidden_size": 2688,
+ "num_hidden_layers": 4,
+ "hybrid_override_pattern": "M*E-",
+ "num_attention_heads": 32,
+ "num_key_value_heads": 2,
+ "head_dim": 84,
+ "mamba_num_heads": 64,
+ "mamba_head_dim": 64,
+ "conv_kernel": 4,
+ "ssm_state_size": 128,
+ "n_groups": 8,
+ "n_routed_experts": 128,
+ "num_experts_per_tok": 6,
+ "routed_scaling_factor": 2.5,
+ "layer_norm_epsilon": 0.00001
+ }
+ }`))
+ if err != nil {
+ t.Fatalf("parseConfig returned error: %v", err)
+ }
+
+ if got, want := cfg.ModelType, "nemotron_h"; got != want {
+ t.Fatalf("ModelType = %q, want %q", got, want)
+ }
+ if got, want := string(cfg.LayerTypes), "M*E-"; got != want {
+ t.Fatalf("LayerTypes = %q, want %q", got, want)
+ }
+ if got, want := cfg.NGroups, int32(8); got != want {
+ t.Fatalf("NGroups = %d, want %d", got, want)
+ }
+ if got, want := cfg.RoutedScalingFactor, float32(2.5); got != want {
+ t.Fatalf("RoutedScalingFactor = %v, want %v", got, want)
+ }
+}
+
+func TestParseConfigRejectsBadPattern(t *testing.T) {
+ _, err := parseConfig([]byte(`{
+ "hidden_size": 4,
+ "num_hidden_layers": 2,
+ "hybrid_override_pattern": "M",
+ "num_attention_heads": 2
+ }`))
+ if err == nil || !strings.Contains(err.Error(), "hybrid_override_pattern length") {
+ t.Fatalf("parseConfig error = %v, want hybrid pattern length error", err)
+ }
+}
+
+func TestParseConfigRejectsUndividedExpertGroups(t *testing.T) {
+ _, err := parseConfig([]byte(`{
+ "hidden_size": 4,
+ "num_hidden_layers": 1,
+ "hybrid_override_pattern": "E",
+ "num_attention_heads": 2,
+ "n_routed_experts": 10,
+ "n_group": 3,
+ "num_experts_per_tok": 2
+ }`))
+ if err == nil || !strings.Contains(err.Error(), "must be divisible by n_group") {
+ t.Fatalf("parseConfig error = %v, want expert-group divisibility error", err)
+ }
+}
+
+func TestNewCachesLayout(t *testing.T) {
+ m := &Model{
+ Config: &Config{
+ ConvKernel: 4,
+ MambaNumHeads: 2,
+ MambaHeadDim: 2,
+ SSMStateSize: 3,
+ NGroups: 1,
+ },
+ Layers: []*Layer{
+ {Type: 'M'},
+ {Type: '*'},
+ {Type: 'E'},
+ {Type: '-'},
+ },
+ }
+
+ caches := m.NewCaches()
+ if got, want := len(caches), 4; got != want {
+ t.Fatalf("len(NewCaches()) = %d, want %d", got, want)
+ }
+ if _, ok := caches[0].(*cache.RecurrentCache); !ok {
+ t.Fatalf("caches[0] = %T, want *cache.RecurrentCache", caches[0])
+ }
+ if _, ok := caches[1].(*cache.KVCache); !ok {
+ t.Fatalf("caches[1] = %T, want *cache.KVCache", caches[1])
+ }
+ if caches[2] != nil || caches[3] != nil {
+ t.Fatalf("MLP-only caches = %T/%T, want nil/nil", caches[2], caches[3])
+ }
+}
+
+func TestNewCachesLayoutWithAttentionMTP(t *testing.T) {
+ m := &Model{
+ Config: &Config{
+ ConvKernel: 4,
+ MambaNumHeads: 2,
+ MambaHeadDim: 2,
+ SSMStateSize: 3,
+ NGroups: 1,
+ },
+ Layers: []*Layer{
+ {Type: 'M'},
+ {Type: 'A'},
+ {Type: 'E'},
+ {Type: '-'},
+ },
+ MTP: &MTPHead{Layers: []*Layer{{Type: 'A'}, {Type: 'E'}}},
+ }
+
+ // The model declares only its own layers; the draft declares its own.
+ caches := m.NewCaches()
+ if got, want := len(caches), 4; got != want {
+ t.Fatalf("len(NewCaches()) = %d, want %d", got, want)
+ }
+
+ draft := m.SelfDraft()
+ if draft == nil {
+ t.Fatal("SelfDraft() = nil, want the MTP draft")
+ }
+ draftCaches := draft.NewCaches()
+ if got, want := len(draftCaches), 1; got != want {
+ t.Fatalf("len(draft.NewCaches()) = %d, want %d", got, want)
+ }
+ if _, ok := draftCaches[0].(*cache.KVCache); !ok {
+ t.Fatalf("draft.NewCaches()[0] = %T, want *cache.KVCache", draftCaches[0])
+ }
+}
+
+func TestNewCachesLayoutWithCachelessMTP(t *testing.T) {
+ m := &Model{
+ Config: &Config{
+ ConvKernel: 4,
+ MambaNumHeads: 2,
+ MambaHeadDim: 2,
+ SSMStateSize: 3,
+ NGroups: 1,
+ },
+ Layers: []*Layer{
+ {Type: 'M'},
+ {Type: 'A'},
+ {Type: 'E'},
+ {Type: '-'},
+ },
+ MTP: &MTPHead{Layers: []*Layer{{Type: 'E'}}},
+ }
+
+ caches := m.NewCaches()
+ if got, want := len(caches), 4; got != want {
+ t.Fatalf("len(NewCaches()) = %d, want %d", got, want)
+ }
+
+ draft := m.SelfDraft()
+ if draft == nil {
+ t.Fatal("SelfDraft() = nil, want the MTP draft")
+ }
+ if draftCaches := draft.NewCaches(); len(draftCaches) != 0 {
+ t.Fatalf("draft.NewCaches() = %v, want none for a cacheless MTP", draftCaches)
+ }
+}
+
+func TestDetectMTPLayerType(t *testing.T) {
+ present := &mlx.Array{}
+ for _, tt := range []struct {
+ name string
+ tensors map[string]*mlx.Array
+ want byte
+ wantErr string
+ }{
+ {
+ name: "attention",
+ tensors: map[string]*mlx.Array{"mtp.layers.0.mixer.q_proj.weight": present},
+ want: 'A',
+ },
+ {
+ name: "moe",
+ tensors: map[string]*mlx.Array{"mtp.layers.0.mixer.experts.0.up_proj.weight": present},
+ want: 'E',
+ },
+ {
+ name: "dense",
+ tensors: map[string]*mlx.Array{"mtp.layers.0.mixer.up_proj.weight": present},
+ want: '-',
+ },
+ {
+ name: "recurrent unsupported",
+ tensors: map[string]*mlx.Array{"mtp.layers.0.mixer.in_proj.weight": present},
+ wantErr: "recurrent MTP layers are not supported",
+ },
+ } {
+ t.Run(tt.name, func(t *testing.T) {
+ got, err := detectMTPLayerType(tt.tensors, "mtp.layers.0")
+ if tt.wantErr != "" {
+ if err == nil || !strings.Contains(err.Error(), tt.wantErr) {
+ t.Fatalf("detectMTPLayerType error = %v, want %q", err, tt.wantErr)
+ }
+ return
+ }
+ if err != nil {
+ t.Fatalf("detectMTPLayerType returned error: %v", err)
+ }
+ if got != tt.want {
+ t.Fatalf("detectMTPLayerType = %q, want %q", got, tt.want)
+ }
+ })
+ }
+}
+
+func TestMTPLayerPrefixes(t *testing.T) {
+ present := &mlx.Array{}
+ for _, tt := range []struct {
+ name string
+ tensors map[string]*mlx.Array
+ want []string
+ wantErr string
+ }{
+ {
+ name: "nonzero layer index",
+ tensors: map[string]*mlx.Array{"mtp.layers.1.mixer.experts.0.up_proj.weight": present},
+ want: []string{"mtp.layers.1"},
+ },
+ {
+ name: "multiple layers",
+ tensors: map[string]*mlx.Array{
+ "mtp.layers.0.mixer.q_proj.weight": present,
+ "mtp.layers.1.mixer.experts.0.up_proj.weight": present,
+ },
+ want: []string{"mtp.layers.0", "mtp.layers.1"},
+ },
+ {
+ name: "missing layer",
+ tensors: map[string]*mlx.Array{"mtp.fc.weight": present},
+ wantErr: "missing MTP layer tensors",
+ },
+ } {
+ t.Run(tt.name, func(t *testing.T) {
+ got, err := mtpLayerPrefixes(tt.tensors)
+ if tt.wantErr != "" {
+ if err == nil || !strings.Contains(err.Error(), tt.wantErr) {
+ t.Fatalf("mtpLayerPrefixes error = %v, want %q", err, tt.wantErr)
+ }
+ return
+ }
+ if err != nil {
+ t.Fatalf("mtpLayerPrefixes returned error: %v", err)
+ }
+ if !slices.Equal(got, tt.want) {
+ t.Fatalf("mtpLayerPrefixes = %v, want %v", got, tt.want)
+ }
+ })
+ }
+}
+
+func TestHasMTPHeadTensors(t *testing.T) {
+ present := &mlx.Array{}
+ for _, tt := range []struct {
+ name string
+ tensors map[string]*mlx.Array
+ want bool
+ }{
+ {
+ name: "qwen style",
+ tensors: map[string]*mlx.Array{"mtp.fc.weight": present},
+ want: true,
+ },
+ {
+ name: "nemotron native",
+ tensors: map[string]*mlx.Array{"mtp.layers.0.eh_proj.weight": present},
+ want: true,
+ },
+ {
+ name: "mtp layer without fusion",
+ tensors: map[string]*mlx.Array{"mtp.layers.0.mixer.q_proj.weight": present},
+ want: false,
+ },
+ } {
+ t.Run(tt.name, func(t *testing.T) {
+ if got := hasMTPHeadTensors(tt.tensors); got != tt.want {
+ t.Fatalf("hasMTPHeadTensors() = %v, want %v", got, tt.want)
+ }
+ })
+ }
+}
+
+func TestSupportsGatherQMM(t *testing.T) {
+ for _, tt := range []struct {
+ mode string
+ bits int
+ want bool
+ }{
+ {mode: "affine", bits: 4, want: true},
+ {mode: "mxfp4", bits: 4, want: true},
+ {mode: "nvfp4", bits: 4, want: true},
+ {mode: "mxfp8", bits: 8, want: true},
+ {mode: "mxfp8", bits: 4, want: false},
+ {mode: "unknown", bits: 4, want: false},
+ } {
+ if got := supportsGatherQMM(tt.mode, tt.bits); got != tt.want {
+ t.Fatalf("supportsGatherQMM(%q, %d) = %v, want %v", tt.mode, tt.bits, got, tt.want)
+ }
+ }
+}
+
+func TestApplyExpertWeightGlobalScale(t *testing.T) {
+ mlxtest.Setup(t)
+
+ weight := mlx.FromValues([]float32{
+ 1, 2,
+ 3, 4,
+ 5, 6,
+ 7, 8,
+ }, 2, 2, 2)
+ scale := mlx.FromValues([]float32{2, 3}, 2)
+
+ got := applyExpertWeightGlobalScale(weight, scale)
+ mlx.Eval(got)
+
+ assertAllClose(t, "scaled expert weight", got.Floats(), []float32{
+ 2, 4,
+ 6, 8,
+ 15, 18,
+ 21, 24,
+ }, 1e-5)
+}
+
+// The production form leans on MLX's fused fast RMS norm, so check it against
+// a reference that spells out every step.
+func TestGatedGroupRMSNormMatchesElementwiseReference(t *testing.T) {
+ mlxtest.Setup(t)
+
+ cfg := &Config{MambaNumHeads: 4, MambaHeadDim: 2, NGroups: 2, LayerNormEpsilon: 1e-5}
+ inner := cfg.MambaNumHeads * cfg.MambaHeadDim
+ groupSize := inner / cfg.NGroups
+ B, L := int32(2), int32(3)
+
+ y := testGatedValues(0.1, int(B), int(L), int(inner))
+ gate := testGatedValues(-0.2, int(B), int(L), int(inner))
+ weight := testGatedValues(0.9, int(inner))
+
+ got := gatedGroupRMSNorm(y, gate, weight, cfg, mlx.DTypeFloat32)
+
+ ref := mlx.Mul(y, mlx.SiLU(gate))
+ ref = mlx.Reshape(ref, B, L, cfg.NGroups, groupSize)
+ variance := mlx.Mean(mlx.Mul(ref, ref), 3, true)
+ ref = mlx.Mul(ref, mlx.RSqrt(mlx.AddScalar(variance, cfg.LayerNormEpsilon)))
+ ref = mlx.Mul(ref, mlx.Reshape(weight, 1, 1, cfg.NGroups, groupSize))
+ ref = mlx.Reshape(ref, B, L, inner)
+
+ mlx.Eval(got, ref)
+ assertAllClose(t, "gated group rmsnorm", got.Floats(), ref.Floats(), 1e-5)
+}
+
+func testGatedValues(seed float32, shape ...int) *mlx.Array {
+ n := 1
+ for _, d := range shape {
+ n *= d
+ }
+ vals := make([]float32, n)
+ for i := range vals {
+ vals[i] = seed + 0.01*float32(i)
+ }
+ return mlx.FromValues(vals, shape...)
+}
+
+func assertAllClose(t *testing.T, name string, got, want []float32, tol float64) {
+ t.Helper()
+ if len(got) != len(want) {
+ t.Fatalf("%s length = %d, want %d", name, len(got), len(want))
+ }
+ for i := range got {
+ if math.Abs(float64(got[i]-want[i])) > tol {
+ t.Fatalf("%s[%d] = %v, want %v", name, i, got[i], want[i])
+ }
+ }
+}
diff --git a/x/models/nn/nn_test.go b/x/models/nn/nn_test.go
index be71a24ab..9cba327bc 100644
--- a/x/models/nn/nn_test.go
+++ b/x/models/nn/nn_test.go
@@ -4,14 +4,13 @@ import (
"math"
"testing"
+ "github.com/ollama/ollama/x/internal/mlxtest"
"github.com/ollama/ollama/x/mlxrunner/mlx"
)
func skipIfNoMLX(t *testing.T) {
t.Helper()
- if err := mlx.CheckInit(); err != nil {
- t.Skipf("MLX not available: %v", err)
- }
+ mlxtest.Setup(t)
}
func approxEqual(a, b, tol float32) bool {
diff --git a/x/models/nn/recurrent.go b/x/models/nn/recurrent.go
index fc168e6e0..39ed099c5 100644
--- a/x/models/nn/recurrent.go
+++ b/x/models/nn/recurrent.go
@@ -7,7 +7,7 @@ import (
"github.com/ollama/ollama/x/mlxrunner/mlx"
)
-// RecurrentOption configures a call to CausalConv1D or GatedDelta.
+// RecurrentOption configures a call to CausalConv1D, GatedDelta or Mamba2Scan.
type RecurrentOption func(*recurrentConfig)
// recurrentConfig is the resolved set of inputs supplied via
@@ -38,9 +38,9 @@ func WithRecurrentState(convState, deltaState *mlx.Array) RecurrentOption {
}
}
-// WithConvSiLU applies SiLU to the conv output inside CausalConv1D,
-// fused into the conv kernel when the conv fits its contract. GatedDelta
-// ignores it, so it can ride a shared option list.
+// WithConvSiLU applies SiLU to the conv output inside CausalConv1D, fused
+// into the conv kernel when the conv fits its contract. The scan wrappers
+// ignore it, so it can ride a shared option list.
func WithConvSiLU() RecurrentOption {
return func(c *recurrentConfig) { c.convSiLU = true }
}
@@ -146,7 +146,7 @@ func CausalConv1D(b *batch.Batch, input *mlx.Array, conv *Conv1d, convTail int,
concat := mlx.Concatenate([]*mlx.Array{prior, input}, 1)
if cfg.convSiLU {
if w := depthwiseConvWeight(conv); w != nil {
- out = mlx.DepthwiseConvSiLU(concat, w, int(L))
+ out = mlx.DepthwiseConvSiLU(concat, w, conv.Bias, int(L))
} else {
out = mlx.SiLU(conv.Forward(concat))
}
@@ -174,7 +174,7 @@ func CausalConv1D(b *batch.Batch, input *mlx.Array, conv *Conv1d, convTail int,
// depthwiseConvWeight returns the [C, K] weight view the fused conv kernel
// takes, or nil when the conv is not a plain depthwise causal conv.
func depthwiseConvWeight(c *Conv1d) *mlx.Array {
- if c.Bias != nil || c.Stride != 1 || c.Padding != 0 || c.Dilation != 1 {
+ if c.Stride != 1 || c.Padding != 0 || c.Dilation != 1 {
return nil
}
if c.Weight.NumDims() != 3 || c.Weight.Dim(2) != 1 || int(c.Groups) != c.Weight.Dim(0) {
@@ -254,6 +254,45 @@ func GatedDelta(b *batch.Batch, convOut, ba, dtBias, aExp *mlx.Array, opts ...Re
return mlx.Concatenate(outs, 1), states
}
+// Mamba2Scan runs the Mamba2 selective-scan step with recurrent state
+// management. hidden is [B, L, H, D], bState/cState are [B, L, G, S] with
+// H%G == 0, dt is [B, L, H], and a/d/dtBias are [H]. Prior state comes from
+// exactly one of WithRecurrentHistory or WithRecurrentState.
+//
+// Splits behave as in GatedDelta. Returns the delta state at each boundary,
+// ending with the forward-end state.
+func Mamba2Scan(b *batch.Batch, hidden, bState, cState, dt, a, d, dtBias *mlx.Array, opts ...RecurrentOption) (*mlx.Array, []*mlx.Array) {
+ cfg := resolveRecurrentConfig(opts)
+ prior := cfg.deltaState
+ if cfg.history != nil {
+ prior = cfg.history.DeltaState()
+ }
+
+ L := int32(hidden.Dim(1))
+ mask := paddingMask(b, L)
+
+ // len(splits) == L-1 means the offsets are exactly 1..L-1, the kernels'
+ // captureAll shape, so both it and the no-split case are one call.
+ if n := len(cfg.splits); n == 0 || n == int(L)-1 {
+ y, end, interior := mlx.Mamba2Scan(hidden, bState, cState, dt, prior, a, d, dtBias, mask, n > 0)
+ return y, append(interior, end)
+ }
+
+ segs := segmentRanges(cfg.splits, L)
+ outs := make([]*mlx.Array, 0, len(segs))
+ states := make([]*mlx.Array, 0, len(segs))
+ state := prior
+ for _, seg := range segs {
+ var y *mlx.Array
+ y, state, _ = mlx.Mamba2Scan(
+ sliceSeg(hidden, seg), sliceSeg(bState, seg), sliceSeg(cState, seg), sliceSeg(dt, seg),
+ state, a, d, dtBias, sliceSeg(mask, seg), false)
+ outs = append(outs, y)
+ states = append(states, state)
+ }
+ return mlx.Concatenate(outs, 1), states
+}
+
// RecurrentHistory is an opaque per-forward view a recurrent cache
// hands to the SSM kernel wrappers — prior conv and delta state
// tensors. Models do not construct this directly; pass it through
diff --git a/x/models/nn/recurrent_test.go b/x/models/nn/recurrent_test.go
index 2577942c3..6217e153c 100644
--- a/x/models/nn/recurrent_test.go
+++ b/x/models/nn/recurrent_test.go
@@ -33,6 +33,35 @@ func convFromKernel(w *mlx.Array) *Conv1d {
return NewConv1d(mlx.ExpandDims(w, 2), nil, 1, 0, 1, int32(w.Dim(0)))
}
+// Guards a biased conv silently losing the fused kernel: depthwiseConvWeight
+// returning nil sends WithConvSiLU down separate graph ops.
+func TestCausalConv1DBiasTakesFusedPath(t *testing.T) {
+ skipIfNoMLX(t)
+ B, L, D, convTail := 2, 3, 4, 2
+ K := convTail + 1
+
+ weight := fromValues(-0.3, D, K)
+ bias := fromValues(0.4, D)
+ conv := NewConv1d(mlx.ExpandDims(weight, 2), bias, 1, 0, 1, int32(D))
+
+ if depthwiseConvWeight(conv) == nil {
+ t.Fatal("depthwiseConvWeight = nil for a biased depthwise conv, so the fused path is skipped")
+ }
+
+ prior := fromValues(0.2, B, convTail, D)
+ input := fromValues(0.1, B, L, D)
+ b := &batch.Batch{
+ InputIDs: mlx.Zeros(mlx.DTypeInt32, B, L),
+ SeqOffsets: []int32{0, 0},
+ SeqQueryLens: []int32{int32(L), int32(L)},
+ }
+
+ got, _ := CausalConv1D(b, input, conv, convTail, WithRecurrentState(prior, nil), WithConvSiLU())
+ want := mlx.SiLU(conv.Forward(mlx.Concatenate([]*mlx.Array{prior, input}, 1)))
+ mlx.Eval(got, want)
+ floatsClose(t, "biased fused conv+silu", got.Floats(), want.Floats(), 1e-5)
+}
+
// TestCausalConv1DPaddedRowParity drives a B=2 batch with one short
// row (qLen<L). For the short row, (a) `out` positions [0..qLen)
// must equal a B=1 reference at length qLen, (b) `nextConv` for the
@@ -202,23 +231,21 @@ func TestGatedDeltaSegmentEquivalence(t *testing.T) {
{"sparse", []int{2}},
}
for _, tc := range cases {
- t.Run(tc.name, func(t *testing.T) {
- segOut, segStates := GatedDelta(full, packed, ba, dtBias, aExp,
- WithRecurrentState(nil, prior), WithSnapshotSplits(tc.splits))
- mlx.Eval(refOut, segOut)
- floatsClose(t, "out", segOut.Floats(), refOut.Floats(), 1e-4)
- if len(segStates) != len(tc.splits)+1 {
- t.Fatalf("got %d boundary states, want %d", len(segStates), len(tc.splits)+1)
- }
- boundaries := append(append([]int{}, tc.splits...), T)
- for i, n := range boundaries {
- _, want, _ := mlx.GatedDelta(
- slicePrefix(packed, 0, 1, int32(n)), slicePrefix(ba, 0, 1, int32(n)),
- dtBias, aExp, prior, nil, false)
- mlx.Eval(segStates[i], want)
- floatsClose(t, "boundary delta", segStates[i].Floats(), want.Floats(), 1e-4)
- }
- })
+ segOut, segStates := GatedDelta(full, packed, ba, dtBias, aExp,
+ WithRecurrentState(nil, prior), WithSnapshotSplits(tc.splits))
+ mlx.Eval(refOut, segOut)
+ floatsClose(t, tc.name+" out", segOut.Floats(), refOut.Floats(), 1e-4)
+ if len(segStates) != len(tc.splits)+1 {
+ t.Fatalf("%s: got %d boundary states, want %d", tc.name, len(segStates), len(tc.splits)+1)
+ }
+ boundaries := append(append([]int{}, tc.splits...), T)
+ for i, n := range boundaries {
+ _, want, _ := mlx.GatedDelta(
+ slicePrefix(packed, 0, 1, int32(n)), slicePrefix(ba, 0, 1, int32(n)),
+ dtBias, aExp, prior, nil, false)
+ mlx.Eval(segStates[i], want)
+ floatsClose(t, tc.name+" boundary delta", segStates[i].Floats(), want.Floats(), 1e-4)
+ }
}
}
@@ -293,34 +320,32 @@ func TestGatedDeltaSegmentEquivalenceBatched(t *testing.T) {
{"sparse", []int{2}},
}
for _, tc := range cases {
- t.Run(tc.name, func(t *testing.T) {
- segOut, segStates := GatedDelta(full, packed, ba, dtBias, aExp,
- WithRecurrentState(nil, prior), WithSnapshotSplits(tc.splits))
- mlx.Eval(refOut, segOut, lastState(refStates), lastState(segStates))
- floatsClose(t, "batched out", segOut.Floats(), refOut.Floats(), 1e-4)
- floatsClose(t, "batched final state", lastState(segStates).Floats(), lastState(refStates).Floats(), 1e-4)
- if len(segStates) != len(tc.splits)+1 {
- t.Fatalf("got %d boundary states, want %d", len(segStates), len(tc.splits)+1)
- }
+ segOut, segStates := GatedDelta(full, packed, ba, dtBias, aExp,
+ WithRecurrentState(nil, prior), WithSnapshotSplits(tc.splits))
+ mlx.Eval(refOut, segOut, lastState(refStates), lastState(segStates))
+ floatsClose(t, tc.name+" batched out", segOut.Floats(), refOut.Floats(), 1e-4)
+ floatsClose(t, tc.name+" batched final state", lastState(segStates).Floats(), lastState(refStates).Floats(), 1e-4)
+ if len(segStates) != len(tc.splits)+1 {
+ t.Fatalf("%s: got %d boundary states, want %d", tc.name, len(segStates), len(tc.splits)+1)
+ }
- // Each row's boundary must equal a B=1 single-shot call over that
- // row's real prefix: row 0 advances the full length, row 1 freezes
- // once it reaches its real length.
- boundaries := append(append([]int{}, tc.splits...), T)
- for i, bound := range boundaries {
- for r := range B {
- n := min(int32(bound), rowReal[r])
- lo, hi := int32(r), int32(r)+1
- rowPrior := mlx.SliceStartStop(prior, []int32{lo, 0, 0, 0}, []int32{hi, int32(Hv), int32(Dv), int32(Dk)})
- _, want, _ := mlx.GatedDelta(
- slicePrefix(packed, lo, hi, n), slicePrefix(ba, lo, hi, n),
- dtBias, aExp, rowPrior, nil, false)
- gotRow := mlx.SliceStartStop(segStates[i], []int32{lo, 0, 0, 0}, []int32{hi, int32(Hv), int32(Dv), int32(Dk)})
- mlx.Eval(gotRow, want)
- floatsClose(t, "batched boundary delta", gotRow.Floats(), want.Floats(), 1e-4)
- }
+ // Each row's boundary must equal a B=1 single-shot call over that
+ // row's real prefix: row 0 advances the full length, row 1 freezes
+ // once it reaches its real length.
+ boundaries := append(append([]int{}, tc.splits...), T)
+ for i, bound := range boundaries {
+ for r := range B {
+ n := min(int32(bound), rowReal[r])
+ lo, hi := int32(r), int32(r)+1
+ rowPrior := mlx.SliceStartStop(prior, []int32{lo, 0, 0, 0}, []int32{hi, int32(Hv), int32(Dv), int32(Dk)})
+ _, want, _ := mlx.GatedDelta(
+ slicePrefix(packed, lo, hi, n), slicePrefix(ba, lo, hi, n),
+ dtBias, aExp, rowPrior, nil, false)
+ gotRow := mlx.SliceStartStop(segStates[i], []int32{lo, 0, 0, 0}, []int32{hi, int32(Hv), int32(Dv), int32(Dk)})
+ mlx.Eval(gotRow, want)
+ floatsClose(t, tc.name+" batched boundary delta", gotRow.Floats(), want.Floats(), 1e-4)
}
- })
+ }
}
}
diff --git a/x/models/nn/sdpa_test.go b/x/models/nn/sdpa_test.go
index 88285473f..6536b9375 100644
--- a/x/models/nn/sdpa_test.go
+++ b/x/models/nn/sdpa_test.go
@@ -117,17 +117,15 @@ func TestAttentionMaskRelaxNoopRectsMatchCausal(t *testing.T) {
{"fully under causal", 5, 7, 0, 3},
}
for _, tc := range cases {
- t.Run(tc.name, func(t *testing.T) {
- m := CausalMask().Relax(0, tc.qLo, tc.qHi, tc.kLo, tc.kHi)
- arr := m.AsArray(b, K, mlx.DTypeFloat32)
- mlx.Eval(arr)
- got := arr.Floats()
- for i := range wantF {
- if !sameF(got[i], wantF[i]) {
- t.Fatalf("index %d: want %v, got %v", i, wantF[i], got[i])
- }
+ m := CausalMask().Relax(0, tc.qLo, tc.qHi, tc.kLo, tc.kHi)
+ arr := m.AsArray(b, K, mlx.DTypeFloat32)
+ mlx.Eval(arr)
+ got := arr.Floats()
+ for i := range wantF {
+ if !sameF(got[i], wantF[i]) {
+ t.Fatalf("%s index %d: want %v, got %v", tc.name, i, wantF[i], got[i])
}
- })
+ }
}
}