Skip to content

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

qwen3.8: add renderer and MLX import support (#17745)

Daniel Hiltgen551279752729
diff --git a/model/parsers/qwen35.go b/model/parsers/qwen35.go
index 0da7980a8..6b168172a 100644
--- a/model/parsers/qwen35.go
+++ b/model/parsers/qwen35.go
@@ -34,6 +34,7 @@ type Qwen35Parser struct {
// Some checkpoints may emit an explicit leading <think> even when the
// prompt already opened thinking. Strip at most one such tag.
allowLeadingThinkOpenTag bool
+ trimLeadingThinkingSpace bool
}
func (p *Qwen35Parser) HasToolSupport() bool {
@@ -67,9 +68,11 @@ func (p *Qwen35Parser) Init(tools []api.Tool, lastMessage *api.Message, thinkVal
if thinkingEnabled && !assistantPrefill {
p.state = qwen35ParserStateCollectingThinking
p.allowLeadingThinkOpenTag = true
+ p.trimLeadingThinkingSpace = false
} else {
p.state = qwen35ParserStateCollectingContent
p.allowLeadingThinkOpenTag = false
+ p.trimLeadingThinkingSpace = false
}
return tools
@@ -162,10 +165,11 @@ func (p *Qwen35Parser) maybeConsumeLeadingThinkOpenTag(acc string) (bool, bool)
after = strings.TrimLeftFunc(after, unicode.IsSpace)
p.buffer.Reset()
p.buffer.WriteString(after)
+ p.allowLeadingThinkOpenTag = false
+ p.trimLeadingThinkingSpace = after == ""
if after == "" {
return true, false
}
- p.allowLeadingThinkOpenTag = false
return true, true
}
@@ -187,6 +191,15 @@ func (p *Qwen35Parser) eat() ([]qwen35Event, bool) {
if handled, continueNow := p.maybeConsumeLeadingThinkOpenTag(acc); handled {
return events, continueNow
}
+ if p.trimLeadingThinkingSpace {
+ acc = strings.TrimLeftFunc(acc, unicode.IsSpace)
+ p.buffer.Reset()
+ p.buffer.WriteString(acc)
+ if acc == "" {
+ return events, false
+ }
+ p.trimLeadingThinkingSpace = false
+ }
if strings.Contains(acc, qwen35ThinkingCloseTag) {
thinking, remaining := p.splitAtTag(qwen35ThinkingCloseTag, true)
diff --git a/model/parsers/qwen38_test.go b/model/parsers/qwen38_test.go
new file mode 100644
index 000000000..9870767d6
--- /dev/null
+++ b/model/parsers/qwen38_test.go
@@ -0,0 +1,135 @@
+package parsers
+
+import (
+ "strconv"
+ "strings"
+ "testing"
+ "unicode/utf8"
+
+ "github.com/ollama/ollama/api"
+)
+
+func TestQwen38ParserReferenceContinuationAtEverySplit(t *testing.T) {
+ tools := []api.Tool{
+ tool("get_weather", map[string]api.ToolProperty{
+ "city": {Type: api.PropertyType{"string"}},
+ }),
+ tool("set_uv_threshold", map[string]api.ToolProperty{
+ "index": {Type: api.PropertyType{"integer"}},
+ }),
+ }
+ continuation := `<think>
+Need weather and UV for Montréal.
+</think>
+
+I'll check both.
+
+<tool_call>
+<function=get_weather>
+<parameter=city>
+Montréal
+</parameter>
+</function>
+</tool_call>
+<tool_call>
+<function=set_uv_threshold>
+<parameter=index>
+5
+</parameter>
+</function>
+</tool_call>`
+
+ assertResult := func(t *testing.T, chunks []string) {
+ t.Helper()
+ var content, thinking strings.Builder
+ var calls []api.ToolCall
+
+ parser := ParserForName("qwen3.5")
+ parser.Init(tools, nil, &api.ThinkValue{Value: true})
+ for i, chunk := range chunks {
+ chunkContent, chunkThinking, chunkCalls, err := parser.Add(chunk, i == len(chunks)-1)
+ if err != nil {
+ t.Fatalf("chunk %d parse failed: %v", i, err)
+ }
+ content.WriteString(chunkContent)
+ thinking.WriteString(chunkThinking)
+ calls = append(calls, chunkCalls...)
+ }
+
+ if got, want := thinking.String(), "Need weather and UV for Montréal."; got != want {
+ t.Fatalf("thinking = %q, want %q", got, want)
+ }
+ if got, want := content.String(), "I'll check both."; got != want {
+ t.Fatalf("content = %q, want %q", got, want)
+ }
+ if len(calls) != 2 {
+ t.Fatalf("tool calls = %d, want 2", len(calls))
+ }
+ if got, want := calls[0].Function.Name, "get_weather"; got != want {
+ t.Fatalf("first tool name = %q, want %q", got, want)
+ }
+ if got, ok := calls[0].Function.Arguments.Get("city"); !ok || got != "Montréal" {
+ t.Fatalf("city argument = %#v, %v; want %q, true", got, ok, "Montréal")
+ }
+ if got, want := calls[1].Function.Name, "set_uv_threshold"; got != want {
+ t.Fatalf("second tool name = %q, want %q", got, want)
+ }
+ if got, ok := calls[1].Function.Arguments.Get("index"); !ok || got != 5 {
+ t.Fatalf("index argument = %#v, %v; want 5, true", got, ok)
+ }
+ }
+
+ for split := range len(continuation) + 1 {
+ if !utf8.ValidString(continuation[:split]) || !utf8.ValidString(continuation[split:]) {
+ continue
+ }
+ t.Run("split_"+strconv.Itoa(split), func(t *testing.T) {
+ assertResult(t, []string{continuation[:split], continuation[split:]})
+ })
+ }
+
+ var runeChunks []string
+ for _, r := range continuation {
+ runeChunks = append(runeChunks, string(r))
+ }
+ t.Run("one_rune_per_chunk", func(t *testing.T) {
+ assertResult(t, runeChunks)
+ })
+}
+
+func TestQwen38ParserMalformedAndControlLikeContent(t *testing.T) {
+ tests := []struct {
+ name string
+ continuation string
+ wantContent string
+ wantThinking string
+ }{
+ {
+ name: "ordinary control-like text",
+ continuation: "Plan</think>ordinary <tool_calling> marker.",
+ wantContent: "ordinary <tool_calling> marker.",
+ wantThinking: "Plan",
+ },
+ {
+ name: "truncated tool call",
+ continuation: "Plan</think>Before<tool_call><function=get_weather>",
+ wantContent: "Before",
+ wantThinking: "Plan",
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ parser := ParserForName("qwen3.5")
+ parser.Init(nil, nil, &api.ThinkValue{Value: true})
+ content, thinking, calls, err := parser.Add(tt.continuation, true)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if content != tt.wantContent || thinking != tt.wantThinking || len(calls) != 0 {
+ t.Fatalf("parsed content=%q thinking=%q calls=%d; want content=%q thinking=%q calls=0",
+ content, thinking, len(calls), tt.wantContent, tt.wantThinking)
+ }
+ })
+ }
+}
diff --git a/model/renderers/qwen35.go b/model/renderers/qwen35.go
index 578a32689..4fb27f53f 100644
--- a/model/renderers/qwen35.go
+++ b/model/renderers/qwen35.go
@@ -1,6 +1,7 @@
package renderers
import (
+ "fmt"
"strings"
"github.com/ollama/ollama/api"
@@ -9,6 +10,10 @@ import (
const (
qwen35ThinkOpenTag = "<think>"
qwen35ThinkCloseTag = "</think>"
+
+ qwen38XHighReasoningInstructions = "Reasoning effort is set to xhigh. Please think carefully through the task, validate key assumptions, consider plausible alternatives, and prioritize correctness, consistency, and clarity in the final answer."
+ qwen38LowReasoningInstructions = "Reasoning effort is set to low. Keep your thinking brief and focused, moving directly to the conclusion without unnecessary elaboration."
+
qwen35ToolPostamble = `
</tools>
@@ -36,14 +41,32 @@ Reminder:
</IMPORTANT>`
)
+type qwen35RendererVariant int
+
+const (
+ qwen35RendererDefault qwen35RendererVariant = iota
+ qwen35Renderer38
+)
+
type Qwen35Renderer struct {
isThinking bool
+ variant qwen35RendererVariant
alwaysRenderAssistantThinkBlock bool
emitEmptyThinkOnNoThink bool
useImgTags bool
}
+func newQwen38Renderer() *Qwen35Renderer {
+ return &Qwen35Renderer{
+ isThinking: true,
+ variant: qwen35Renderer38,
+ alwaysRenderAssistantThinkBlock: true,
+ emitEmptyThinkOnNoThink: true,
+ useImgTags: RenderImgTags,
+ }
+}
+
func (r *Qwen35Renderer) LeadingBOS() string {
return ""
}
@@ -64,11 +87,15 @@ func (r *Qwen35Renderer) renderContent(content api.Message, imageOffset int) (st
return subSb.String(), imageOffset
}
-func splitQwen35ReasoningContent(content, messageThinking string, isThinking bool) (reasoning string, remaining string) {
+func splitQwen35ReasoningContent(content, messageThinking string, isThinking, extractTaggedReasoning bool) (reasoning string, remaining string) {
if isThinking && messageThinking != "" {
return strings.TrimSpace(messageThinking), content
}
+ if !extractTaggedReasoning {
+ return "", content
+ }
+
if idx := strings.Index(content, qwen35ThinkCloseTag); idx != -1 {
before := content[:idx]
if open := strings.LastIndex(before, qwen35ThinkOpenTag); open != -1 {
@@ -82,16 +109,96 @@ func splitQwen35ReasoningContent(content, messageThinking string, isThinking boo
return strings.TrimSpace(reasoning), content
}
+func qwen38ReasoningInstructions(think *api.ThinkValue) (string, error) {
+ if think == nil || think.Value == nil {
+ return qwen38XHighReasoningInstructions, nil
+ }
+ if !think.IsValid() {
+ return "", fmt.Errorf("invalid thinking value %v", think.Value)
+ }
+ if !think.Bool() {
+ return "", nil
+ }
+
+ switch think.String() {
+ case "low":
+ return qwen38LowReasoningInstructions, nil
+ case "medium":
+ return "", nil
+ case "high", "max":
+ return qwen38XHighReasoningInstructions, nil
+ default:
+ return "", fmt.Errorf("unsupported Qwen3.8 reasoning effort %q", think.String())
+ }
+}
+
+func (r *Qwen35Renderer) validateMessages(messages []api.Message) error {
+ if r.variant != qwen35Renderer38 {
+ return nil
+ }
+ if len(messages) == 0 {
+ return fmt.Errorf("no messages provided")
+ }
+ if messages[0].Role == "system" && len(messages[0].Images) > 0 {
+ return fmt.Errorf("system message cannot contain images")
+ }
+
+ foundUserQuery := false
+ for _, message := range messages {
+ if message.Role != "user" {
+ continue
+ }
+ content, _ := r.renderContent(message, 0)
+ content = strings.TrimSpace(content)
+ if !(strings.HasPrefix(content, "<tool_response>") && strings.HasSuffix(content, "</tool_response>")) {
+ foundUserQuery = true
+ break
+ }
+ }
+ if !foundUserQuery {
+ return fmt.Errorf("no user query found in messages")
+ }
+
+ for i, message := range messages {
+ switch message.Role {
+ case "system":
+ if i != 0 {
+ return fmt.Errorf("system message must be at the beginning")
+ }
+ case "user", "assistant", "tool":
+ default:
+ return fmt.Errorf("unexpected message role %q", message.Role)
+ }
+ }
+
+ return nil
+}
+
func (r *Qwen35Renderer) Render(messages []api.Message, tools []api.Tool, think *api.ThinkValue) (string, error) {
+ if err := r.validateMessages(messages); err != nil {
+ return "", err
+ }
+
var sb strings.Builder
isThinking := r.isThinking
- if think != nil {
+ if think != nil && think.Value != nil {
isThinking = think.Bool()
}
+ reasoningInstructions := ""
+ if r.variant == qwen35Renderer38 {
+ var err error
+ reasoningInstructions, err = qwen38ReasoningInstructions(think)
+ if err != nil {
+ return "", err
+ }
+ }
if len(tools) > 0 {
sb.WriteString(imStartTag + "system\n")
+ if reasoningInstructions != "" {
+ sb.WriteString(reasoningInstructions + "\n\n")
+ }
sb.WriteString("# Tools\n\nYou have access to the following functions:\n\n<tools>")
for _, tool := range tools {
sb.WriteString("\n")
@@ -111,7 +218,19 @@ func (r *Qwen35Renderer) Render(messages []api.Message, tools []api.Tool, think
sb.WriteString(imEndTag + "\n")
} else if len(messages) > 0 && messages[0].Role == "system" {
systemContent, _ := r.renderContent(messages[0], 0)
- sb.WriteString(imStartTag + "system\n" + strings.TrimSpace(systemContent) + imEndTag + "\n")
+ systemContent = strings.TrimSpace(systemContent)
+ if r.variant != qwen35Renderer38 || systemContent != "" || reasoningInstructions != "" {
+ sb.WriteString(imStartTag + "system\n")
+ if reasoningInstructions != "" {
+ sb.WriteString(reasoningInstructions)
+ if systemContent != "" {
+ sb.WriteString("\n\n")
+ }
+ }
+ sb.WriteString(systemContent + imEndTag + "\n")
+ }
+ } else if reasoningInstructions != "" {
+ sb.WriteString(imStartTag + "system\n" + reasoningInstructions + imEndTag + "\n")
}
multiStepTool := true
@@ -142,7 +261,12 @@ func (r *Qwen35Renderer) Render(messages []api.Message, tools []api.Tool, think
sb.WriteString(imStartTag + message.Role + "\n" + content + imEndTag + "\n")
} else if message.Role == "assistant" {
renderAssistantThinkBlock := r.alwaysRenderAssistantThinkBlock || (isThinking && i > lastQueryIndex)
- contentReasoning, content := splitQwen35ReasoningContent(content, message.Thinking, renderAssistantThinkBlock)
+ contentReasoning, content := splitQwen35ReasoningContent(
+ content,
+ message.Thinking,
+ renderAssistantThinkBlock,
+ r.variant != qwen35Renderer38,
+ )
if renderAssistantThinkBlock {
sb.WriteString(imStartTag + message.Role + "\n<think>\n" + contentReasoning + "\n</think>\n\n" + content)
diff --git a/model/renderers/qwen38_test.go b/model/renderers/qwen38_test.go
new file mode 100644
index 000000000..c5d7e4161
--- /dev/null
+++ b/model/renderers/qwen38_test.go
@@ -0,0 +1,650 @@
+package renderers
+
+import (
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/google/go-cmp/cmp"
+ "github.com/ollama/ollama/api"
+ "github.com/ollama/ollama/x/tokenizer"
+)
+
+const (
+ qwen38Template = "testdata/qwen38_chat_template.jinja"
+
+ qwen38RefXHigh = "Reasoning effort is set to xhigh. Please think carefully through the task, validate key assumptions, consider plausible alternatives, and prioritize correctness, consistency, and clarity in the final answer."
+ qwen38RefLow = "Reasoning effort is set to low. Keep your thinking brief and focused, moving directly to the conclusion without unnecessary elaboration."
+)
+
+func TestQwen38RendererMatchesReferenceFlows(t *testing.T) {
+ think := func(value any) *api.ThinkValue { return &api.ThinkValue{Value: value} }
+ verifyJinja := os.Getenv("VERIFY_JINJA2") != ""
+ if verifyJinja {
+ requireQwen38Jinja(t)
+ t.Log("VERIFY_JINJA2=1: verifying expected values against the Qwen3.8 Jinja template")
+ }
+
+ weatherArgs := api.NewToolCallFunctionArguments()
+ weatherArgs.Set("city", "Montréal")
+ weather := []api.Tool{
+ {
+ Type: "function",
+ Function: api.ToolFunction{
+ Name: "get_weather",
+ Description: "Get weather",
+ Parameters: api.ToolFunctionParameters{
+ Type: "object",
+ Required: []string{"city"},
+ Properties: testPropsOrdered([]orderedProp{{
+ Key: "city",
+ Value: api.ToolProperty{Type: api.PropertyType{"string"}},
+ }}),
+ },
+ },
+ },
+ {
+ Type: "function",
+ Function: api.ToolFunction{
+ Name: "get_uv",
+ Description: "Get UV index",
+ Parameters: api.ToolFunctionParameters{
+ Type: "object",
+ Required: []string{"city"},
+ Properties: testPropsOrdered([]orderedProp{{
+ Key: "city",
+ Value: api.ToolProperty{Type: api.PropertyType{"string"}},
+ }}),
+ },
+ },
+ },
+ }
+
+ toolHeader := `<|im_start|>system
+# Tools
+
+You have access to the following functions:
+
+<tools>
+{"type": "function", "function": {"name": "get_weather", "description": "Get weather", "parameters": {"type": "object", "required": ["city"], "properties": {"city": {"type": "string"}}}}}
+{"type": "function", "function": {"name": "get_uv", "description": "Get UV index", "parameters": {"type": "object", "required": ["city"], "properties": {"city": {"type": "string"}}}}}
+</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|>
+`
+
+ tests := []struct {
+ name string
+ messages []api.Message
+ tools []api.Tool
+ think *api.ThinkValue
+ jinjaEffort string
+ want string
+ matchesTemplate bool
+ }{
+ {
+ name: "default xhigh injects system guidance",
+ messages: []api.Message{{Role: "user", Content: "Hello"}},
+ want: `<|im_start|>system
+` + qwen38RefXHigh + `<|im_end|>
+<|im_start|>user
+Hello<|im_end|>
+<|im_start|>assistant
+<think>
+`,
+ matchesTemplate: true,
+ },
+ {
+ name: "boolean true uses API medium effort",
+ messages: []api.Message{
+ {Role: "system", Content: " Be concise. \n"},
+ {Role: "user", Content: "Hello"},
+ },
+ think: think(true),
+ jinjaEffort: "medium",
+ want: `<|im_start|>system
+Be concise.<|im_end|>
+<|im_start|>user
+Hello<|im_end|>
+<|im_start|>assistant
+<think>
+`,
+ matchesTemplate: true,
+ },
+ {
+ name: "low effort injects concise guidance",
+ messages: []api.Message{{Role: "user", Content: "Hello"}},
+ think: think("low"),
+ jinjaEffort: "low",
+ want: `<|im_start|>system
+` + qwen38RefLow + `<|im_end|>
+<|im_start|>user
+Hello<|im_end|>
+<|im_start|>assistant
+<think>
+`,
+ matchesTemplate: true,
+ },
+ {
+ name: "thinking disabled emits explicit empty block",
+ messages: []api.Message{{Role: "user", Content: "Hello"}},
+ think: think(false),
+ want: `<|im_start|>user
+Hello<|im_end|>
+<|im_start|>assistant
+<think>
+
+</think>
+
+`,
+ matchesTemplate: true,
+ },
+ {
+ name: "preserves reasoning metadata without extracting content tags",
+ messages: []api.Message{
+ {Role: "user", Content: "First"},
+ {Role: "assistant", Thinking: "Plan", Content: "<think>literal</think>\nAnswer"},
+ {Role: "user", Content: "Next"},
+ },
+ want: `<|im_start|>system
+` + qwen38RefXHigh + `<|im_end|>
+<|im_start|>user
+First<|im_end|>
+<|im_start|>assistant
+<think>
+Plan
+</think>
+
+<think>literal</think>
+Answer<|im_end|>
+<|im_start|>user
+Next<|im_end|>
+<|im_start|>assistant
+<think>
+`,
+ matchesTemplate: true,
+ },
+ {
+ name: "tool call result and next generation prompt",
+ messages: []api.Message{
+ {Role: "user", Content: "Weather?"},
+ {
+ Role: "assistant",
+ Thinking: "Need current data.",
+ Content: "I'll check.",
+ ToolCalls: []api.ToolCall{{Function: api.ToolCallFunction{
+ Name: "get_weather",
+ Arguments: weatherArgs,
+ }}},
+ },
+ {Role: "tool", Content: `{"temp": 18}`},
+ },
+ tools: weather,
+ think: think(true),
+ jinjaEffort: "medium",
+ want: toolHeader + `<|im_start|>user
+Weather?<|im_end|>
+<|im_start|>assistant
+<think>
+Need current data.
+</think>
+
+I'll check.
+
+<tool_call>
+<function=get_weather>
+<parameter=city>
+Montréal
+</parameter>
+</function>
+</tool_call><|im_end|>
+<|im_start|>user
+<tool_response>
+{"temp": 18}
+</tool_response><|im_end|>
+<|im_start|>assistant
+<think>
+`,
+ matchesTemplate: true,
+ },
+ {
+ name: "image content",
+ messages: []api.Message{{
+ Role: "user",
+ Content: "Describe this.",
+ Images: []api.ImageData{{1}},
+ }},
+ think: think(false),
+ want: `<|im_start|>user
+<|vision_start|><|image_pad|><|vision_end|>Describe this.<|im_end|>
+<|im_start|>assistant
+<think>
+
+</think>
+
+`,
+ matchesTemplate: true,
+ },
+ }
+
+ renderer := newQwen38Renderer()
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ got, err := renderer.Render(tt.messages, tt.tools, tt.think)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if diff := cmp.Diff(tt.want, got); diff != "" {
+ t.Fatalf("renderer output mismatch (-want +got):\n%s", diff)
+ }
+ if verifyJinja && tt.matchesTemplate {
+ jinja := renderQwen38Jinja(t, tt.messages, tt.tools, tt.think, tt.jinjaEffort)
+ if diff := cmp.Diff(jinja, tt.want); diff != "" {
+ t.Fatalf("hardcoded expected mismatch vs Jinja (-jinja +want):\n%s", diff)
+ }
+ if diff := cmp.Diff(jinja, got); diff != "" {
+ t.Fatalf("renderer output mismatch vs Jinja (-jinja +got):\n%s", diff)
+ }
+ }
+ })
+ }
+}
+
+func TestQwen38RendererReasoningEffortMapping(t *testing.T) {
+ tests := []struct {
+ name string
+ think *api.ThinkValue
+ want string
+ }{
+ {name: "unset", want: qwen38RefXHigh},
+ {name: "true", think: &api.ThinkValue{Value: true}, want: ""},
+ {name: "false", think: &api.ThinkValue{Value: false}, want: ""},
+ {name: "low", think: &api.ThinkValue{Value: "low"}, want: qwen38RefLow},
+ {name: "medium", think: &api.ThinkValue{Value: "medium"}, want: ""},
+ {name: "high", think: &api.ThinkValue{Value: "high"}, want: qwen38RefXHigh},
+ {name: "max", think: &api.ThinkValue{Value: "max"}, want: qwen38RefXHigh},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ got, err := qwen38ReasoningInstructions(tt.think)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got != tt.want {
+ t.Fatalf("reasoning instructions = %q, want %q", got, tt.want)
+ }
+ })
+ }
+}
+
+func TestQwen38RendererRejectsInvalidTranscripts(t *testing.T) {
+ tests := []struct {
+ name string
+ messages []api.Message
+ wantErr string
+ }{
+ {name: "empty", wantErr: "no messages provided"},
+ {
+ name: "no user query",
+ messages: []api.Message{{Role: "system", Content: "Hello"}},
+ wantErr: "no user query found in messages",
+ },
+ {
+ name: "late system",
+ messages: []api.Message{
+ {Role: "user", Content: "Hello"},
+ {Role: "system", Content: "Late"},
+ },
+ wantErr: "system message must be at the beginning",
+ },
+ {
+ name: "system image",
+ messages: []api.Message{
+ {Role: "system", Images: []api.ImageData{{1}}},
+ {Role: "user", Content: "Hello"},
+ },
+ wantErr: "system message cannot contain images",
+ },
+ {
+ name: "unexpected role",
+ messages: []api.Message{
+ {Role: "user", Content: "Hello"},
+ {Role: "developer", Content: "No"},
+ },
+ wantErr: `unexpected message role "developer"`,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ _, err := newQwen38Renderer().Render(tt.messages, nil, nil)
+ if err == nil || err.Error() != tt.wantErr {
+ t.Fatalf("Render() error = %v, want %q", err, tt.wantErr)
+ }
+ })
+ }
+}
+
+func TestQwen38RendererAssistantPrefillKnownJinjaDifference(t *testing.T) {
+ messages := []api.Message{
+ {Role: "user", Content: "Complete this"},
+ {Role: "assistant", Thinking: "Draft", Content: "Partial"},
+ }
+ got, err := newQwen38Renderer().Render(messages, nil, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ want := `<|im_start|>system
+` + qwen38RefXHigh + `<|im_end|>
+<|im_start|>user
+Complete this<|im_end|>
+<|im_start|>assistant
+<think>
+Draft
+</think>
+
+Partial`
+ if diff := cmp.Diff(want, got); diff != "" {
+ t.Fatalf("assistant prefill mismatch (-want +got):\n%s", diff)
+ }
+
+ if os.Getenv("VERIFY_JINJA2") == "" {
+ return
+ }
+ requireQwen38Jinja(t)
+ jinja := renderQwen38Jinja(t, messages, nil, nil, "")
+ wantJinja := got + "<|im_end|>\n<|im_start|>assistant\n<think>\n"
+ if diff := cmp.Diff(wantJinja, jinja); diff != "" {
+ t.Fatalf("assistant prefill Jinja difference changed (-want +jinja):\n%s", diff)
+ }
+}
+
+func TestQwen38TemplateFixtureHash(t *testing.T) {
+ data, err := os.ReadFile(qwen38Template)
+ if err != nil {
+ t.Fatal(err)
+ }
+ // The publisher file has no trailing newline. The checked-in fixture adds
+ // the repository-standard final newline, which does not change Jinja output.
+ sum := sha256.Sum256([]byte(strings.TrimSuffix(string(data), "\n")))
+ if got, want := hex.EncodeToString(sum[:]), "c3cf9e34abf4f9e36c2d72165aa9c132d3e2a725b6c2586aaa3a8af9d7a81041"; got != want {
+ t.Fatalf("template SHA-256 = %s, want %s", got, want)
+ }
+}
+
+func TestQwen38TokenizerMatchesReference(t *testing.T) {
+ modelDir := os.Getenv("QWEN38_MODEL_DIR")
+ if modelDir == "" {
+ t.Skip("set QWEN38_MODEL_DIR to run Qwen3.8 production/reference tokenizer parity")
+ }
+ requireQwen38Jinja(t)
+
+ args := api.NewToolCallFunctionArguments()
+ args.Set("path", "résumé.go")
+ args.Set("options", map[string]any{"indent": 2, "strict": true})
+ tools := []api.Tool{{
+ Type: "function",
+ Function: api.ToolFunction{
+ Name: "read_file",
+ Description: "Read source code",
+ Parameters: api.ToolFunctionParameters{
+ Type: "object",
+ Required: []string{"path"},
+ Properties: testPropsOrdered([]orderedProp{
+ {Key: "path", Value: api.ToolProperty{Type: api.PropertyType{"string"}}},
+ {Key: "options", Value: api.ToolProperty{Type: api.PropertyType{"object"}}},
+ }),
+ },
+ },
+ }}
+
+ renderer := newQwen38Renderer()
+ thinkFalse := &api.ThinkValue{Value: false}
+ cases := []struct {
+ name string
+ messages []api.Message
+ tools []api.Tool
+ think *api.ThinkValue
+ }{
+ {
+ name: "whitespace punctuation contractions and unicode",
+ messages: []api.Message{{
+ Role: "user",
+ Content: "Don't normalize naïve café — punctuation !\n\tline 2: x += 1;\n世界 🌍",
+ }},
+ think: thinkFalse,
+ },
+ {
+ name: "tool JSON and source result",
+ messages: []api.Message{
+ {Role: "user", Content: "Read the file."},
+ {Role: "assistant", Thinking: "Need source.", ToolCalls: []api.ToolCall{{
+ Function: api.ToolCallFunction{Name: "read_file", Arguments: args},
+ }}},
+ {Role: "tool", Content: "{\"ok\":true,\"source\":\"func main() {\\n\\tfmt.Println(\\\"héllo\\\")\\n}\"}"},
+ },
+ tools: tools,
+ },
+ {
+ name: "special-token-looking strings",
+ messages: []api.Message{{
+ Role: "user",
+ Content: "Literal markers: <|im_start|> <|im_end|> <think>not control</think> <|audio_start|>.",
+ }},
+ think: thinkFalse,
+ },
+ }
+
+ prompts := make([]string, 0, len(cases))
+ for _, tc := range cases {
+ prompt, err := renderer.Render(tc.messages, tc.tools, tc.think)
+ if err != nil {
+ t.Fatalf("render %q: %v", tc.name, err)
+ }
+ prompts = append(prompts, prompt)
+ }
+
+ read := func(name string) []byte {
+ t.Helper()
+ data, err := os.ReadFile(filepath.Join(modelDir, name))
+ if err != nil {
+ t.Fatalf("read %s: %v", name, err)
+ }
+ return data
+ }
+ production, err := tokenizer.LoadFromBytesWithConfig(read("tokenizer.json"), &tokenizer.TokenizerConfig{
+ ConfigJSON: read("config.json"),
+ TokenizerConfigJSON: read("tokenizer_config.json"),
+ GenerationConfigJSON: read("generation_config.json"),
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ promptsJSON, err := json.Marshal(prompts)
+ if err != nil {
+ t.Fatal(err)
+ }
+ script := `
+import json
+import sys
+from transformers import AutoTokenizer
+
+tokenizer = AutoTokenizer.from_pretrained(sys.argv[1])
+prompts = json.loads(sys.argv[2])
+print(json.dumps([tokenizer.encode(prompt, add_special_tokens=False) for prompt in prompts]))
+`
+ cmd := qwen38PythonCommand(t, "-c", script, modelDir, string(promptsJSON))
+ output, err := cmd.Output()
+ if err != nil {
+ t.Fatalf("reference tokenization failed: %v", err)
+ }
+ var reference [][]int32
+ if err := json.Unmarshal(output, &reference); err != nil {
+ t.Fatalf("decode reference token IDs: %v", err)
+ }
+ if len(reference) != len(cases) {
+ t.Fatalf("reference returned %d cases, want %d", len(reference), len(cases))
+ }
+
+ for i, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ got := production.Encode(prompts[i], false)
+ if diff := cmp.Diff(reference[i], got); diff != "" {
+ t.Fatalf("production token IDs differ from reference (-reference +production):\n%s", diff)
+ }
+ })
+ }
+}
+
+type qwen38JinjaMessage struct {
+ Role string `json:"role"`
+ Content any `json:"content"`
+ ReasoningContent string `json:"reasoning_content,omitempty"`
+ ToolCalls []api.ToolCall `json:"tool_calls,omitempty"`
+}
+
+type qwen38JinjaContentPart struct {
+ Type string `json:"type"`
+ Text string `json:"text,omitempty"`
+}
+
+func renderQwen38Jinja(t *testing.T, messages []api.Message, tools []api.Tool, think *api.ThinkValue, effort string) string {
+ t.Helper()
+
+ jinjaMessages := make([]qwen38JinjaMessage, 0, len(messages))
+ for _, message := range messages {
+ content := any(message.Content)
+ if len(message.Images) > 0 {
+ parts := make([]qwen38JinjaContentPart, 0, len(message.Images)+1)
+ for range message.Images {
+ parts = append(parts, qwen38JinjaContentPart{Type: "image"})
+ }
+ if message.Content != "" {
+ parts = append(parts, qwen38JinjaContentPart{Type: "text", Text: message.Content})
+ }
+ content = parts
+ }
+ jinjaMessages = append(jinjaMessages, qwen38JinjaMessage{
+ Role: message.Role,
+ Content: content,
+ ReasoningContent: message.Thinking,
+ ToolCalls: message.ToolCalls,
+ })
+ }
+
+ messagesJSON, err := json.Marshal(jinjaMessages)
+ if err != nil {
+ t.Fatal(err)
+ }
+ toolsJSON, err := json.Marshal(tools)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ templatePath, err := filepath.Abs(qwen38Template)
+ if err != nil {
+ t.Fatal(err)
+ }
+ thinking := "unset"
+ if think != nil && think.Value != nil {
+ if think.Bool() {
+ thinking = "true"
+ } else {
+ thinking = "false"
+ }
+ }
+
+ script := `
+import json
+import sys
+from pathlib import Path
+from transformers.utils.chat_template_utils import _compile_jinja_template
+
+template_path, messages_json, tools_json, thinking, effort = sys.argv[1:6]
+tmpl = _compile_jinja_template(Path(template_path).read_text())
+kwargs = {
+ "messages": json.loads(messages_json),
+ "tools": json.loads(tools_json),
+ "add_generation_prompt": True,
+}
+if thinking == "true":
+ kwargs["enable_thinking"] = True
+elif thinking == "false":
+ kwargs["enable_thinking"] = False
+if effort:
+ kwargs["reasoning_effort"] = effort
+print(tmpl.render(**kwargs), end="")
+`
+ cmd := qwen38PythonCommand(t, "-c", script, templatePath, string(messagesJSON), string(toolsJSON), thinking, effort)
+ var stdout, stderr strings.Builder
+ cmd.Stdout = &stdout
+ cmd.Stderr = &stderr
+ if err := cmd.Run(); err != nil {
+ t.Fatalf("Jinja render failed: %v\nstderr: %s", err, stderr.String())
+ }
+ return stdout.String()
+}
+
+func requireQwen38Jinja(t *testing.T) {
+ t.Helper()
+ if err := qwen38PythonCommand(t, "-c", "import transformers").Run(); err != nil {
+ t.Fatal("VERIFY_JINJA2=1 requires .venv/bin/python with transformers 5.x or uv with downloadable transformers")
+ }
+}
+
+func qwen38PythonCommand(t *testing.T, args ...string) *exec.Cmd {
+ t.Helper()
+ if python, ok := findQwen38VenvPython(); ok {
+ return exec.CommandContext(t.Context(), python, args...)
+ }
+
+ uvArgs := append([]string{"run", "--with", "transformers>=5,<6", "python"}, args...)
+ return exec.CommandContext(t.Context(), "uv", uvArgs...)
+}
+
+func findQwen38VenvPython() (string, bool) {
+ dir, err := os.Getwd()
+ if err != nil {
+ return "", false
+ }
+ for {
+ python := filepath.Join(dir, ".venv", "bin", "python")
+ if _, err := os.Stat(python); err == nil {
+ return python, true
+ }
+ parent := filepath.Dir(dir)
+ if parent == dir {
+ return "", false
+ }
+ dir = parent
+ }
+}
diff --git a/model/renderers/renderer.go b/model/renderers/renderer.go
index f49add82a..93d3b0eab 100644
--- a/model/renderers/renderer.go
+++ b/model/renderers/renderer.go
@@ -69,6 +69,8 @@ func rendererForName(name string) Renderer {
case "qwen3.5":
renderer := &Qwen35Renderer{isThinking: true, emitEmptyThinkOnNoThink: true, useImgTags: RenderImgTags}
return renderer
+ case "qwen3.8":
+ return newQwen38Renderer()
case "ornith":
return newOrnithRenderer()
case "cogito":
diff --git a/model/renderers/renderer_test.go b/model/renderers/renderer_test.go
index 89674ffb8..73e741487 100644
--- a/model/renderers/renderer_test.go
+++ b/model/renderers/renderer_test.go
@@ -38,6 +38,7 @@ func TestBuiltInRendererStillWorks(t *testing.T) {
}{
{name: "qwen3-coder"},
{name: "qwen3.5"},
+ {name: "qwen3.8"},
{name: "nemotron-3-nano"},
{name: "nemotron-3.5-nano"},
}
diff --git a/model/renderers/testdata/qwen38_chat_template.jinja b/model/renderers/testdata/qwen38_chat_template.jinja
new file mode 100644
index 000000000..5a39aa2b4
--- /dev/null
+++ b/model/renderers/testdata/qwen38_chat_template.jinja
@@ -0,0 +1,170 @@
+{%- set image_count = namespace(value=0) %}
+{%- set video_count = namespace(value=0) %}
+{%- macro render_content(content, do_vision_count, is_system_content=false) %}
+ {%- if content is string %}
+ {{- content }}
+ {%- elif content is iterable and content is not mapping %}
+ {%- for item in content %}
+ {%- if 'image' in item or 'image_url' in item or item.type == 'image' %}
+ {%- if is_system_content %}
+ {{- raise_exception('System message cannot contain images.') }}
+ {%- endif %}
+ {%- if do_vision_count %}
+ {%- set image_count.value = image_count.value + 1 %}
+ {%- endif %}
+ {%- if add_vision_id %}
+ {{- 'Picture ' ~ image_count.value ~ ': ' }}
+ {%- endif %}
+ {{- '<|vision_start|><|image_pad|><|vision_end|>' }}
+ {%- elif 'video' in item or item.type == 'video' %}
+ {%- if is_system_content %}
+ {{- raise_exception('System message cannot contain videos.') }}
+ {%- endif %}
+ {%- if do_vision_count %}
+ {%- set video_count.value = video_count.value + 1 %}
+ {%- endif %}
+ {%- if add_vision_id %}
+ {{- 'Video ' ~ video_count.value ~ ': ' }}
+ {%- endif %}
+ {{- '<|vision_start|><|video_pad|><|vision_end|>' }}
+ {%- elif 'text' in item %}
+ {{- item.text }}
+ {%- else %}
+ {{- raise_exception('Unexpected item type in content.') }}
+ {%- endif %}
+ {%- endfor %}
+ {%- elif content is none or content is undefined %}
+ {{- '' }}
+ {%- else %}
+ {{- raise_exception('Unexpected content type.') }}
+ {%- endif %}
+{%- endmacro %}
+{%- if not messages %}
+ {{- raise_exception('No messages provided.') }}
+{%- endif %}
+{%- set reasoning_instructions = '' %}
+{%- if enable_thinking is undefined or enable_thinking is true %}
+ {%- set resolved_reasoning_effort = reasoning_effort|default('xhigh') %}
+ {%- if resolved_reasoning_effort not in ('xhigh', 'medium', 'low') %}
+ {{- raise_exception('Unexpected reasoning effort ' ~ reasoning_effort ~ '. Supported types are xhigh (default), medium, and low.') }}
+ {%- endif %}
+ {%- if resolved_reasoning_effort == 'xhigh' %}
+ {%- set reasoning_instructions = 'Reasoning effort is set to xhigh. Please think carefully through the task, validate key assumptions, consider plausible alternatives, and prioritize correctness, consistency, and clarity in the final answer.' %}
+ {%- elif resolved_reasoning_effort == 'low' %}
+ {%- set reasoning_instructions = 'Reasoning effort is set to low. Keep your thinking brief and focused, moving directly to the conclusion without unnecessary elaboration.' %}
+ {%- endif %}
+{%- endif %}
+{%- if tools and tools is iterable and tools is not mapping %}
+ {{- '<|im_start|>system\n' }}
+ {%- if reasoning_instructions %}
+ {{- reasoning_instructions + '\n\n' }}
+ {%- endif %}
+ {{- "# Tools\n\nYou have access to the following functions:\n\n<tools>" }}
+ {%- for tool in tools %}
+ {{- "\n" }}
+ {{- tool | tojson }}
+ {%- endfor %}
+ {{- "\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>' }}
+ {%- if messages[0].role == 'system' %}
+ {%- set content = render_content(messages[0].content, false, true)|trim %}
+ {%- if content %}
+ {{- '\n\n' + content }}
+ {%- endif %}
+ {%- endif %}
+ {{- '<|im_end|>\n' }}
+{%- else %}
+ {%- if messages[0].role == 'system' %}
+ {%- set content = render_content(messages[0].content, false, true)|trim %}
+ {%- if content %}
+ {{- '<|im_start|>system\n' + (reasoning_instructions + '\n\n' if reasoning_instructions else '') + content + '<|im_end|>\n' }}
+ {%- elif reasoning_instructions %}
+ {{- '<|im_start|>system\n' + reasoning_instructions + '<|im_end|>\n' }}
+ {%- endif %}
+ {%- elif reasoning_instructions %}
+ {{- '<|im_start|>system\n' + reasoning_instructions + '<|im_end|>\n' }}
+ {%- endif %}
+{%- endif %}
+{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}
+{%- for message in messages[::-1] %}
+ {%- set index = (messages|length - 1) - loop.index0 %}
+ {%- if ns.multi_step_tool and message.role == "user" %}
+ {%- set content = render_content(message.content, false)|trim %}
+ {%- if not(content.startswith('<tool_response>') and content.endswith('</tool_response>')) %}
+ {%- set ns.multi_step_tool = false %}
+ {%- set ns.last_query_index = index %}
+ {%- endif %}
+ {%- endif %}
+{%- endfor %}
+{%- if ns.multi_step_tool %}
+ {{- raise_exception('No user query found in messages.') }}
+{%- endif %}
+{%- for message in messages %}
+ {%- set content = render_content(message.content, true)|trim %}
+ {%- if message.role == "system" %}
+ {%- if not loop.first %}
+ {{- raise_exception('System message must be at the beginning.') }}
+ {%- endif %}
+ {%- elif message.role == "user" %}
+ {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }}
+ {%- elif message.role == "assistant" %}
+ {%- set reasoning_content = '' %}
+ {%- if message.reasoning_content is string %}
+ {%- set reasoning_content = message.reasoning_content %}
+ {%- endif %}
+ {%- set reasoning_content = reasoning_content|trim %}
+ {%- if preserve_thinking is undefined or preserve_thinking is true or loop.index0 > ns.last_query_index %}
+ {{- '<|im_start|>' + message.role + '\n<think>\n' + reasoning_content + '\n</think>\n\n' + content }}
+ {%- else %}
+ {{- '<|im_start|>' + message.role + '\n' + content }}
+ {%- endif %}
+ {%- if message.tool_calls and message.tool_calls is iterable and message.tool_calls is not mapping %}
+ {%- for tool_call in message.tool_calls %}
+ {%- if tool_call.function is defined %}
+ {%- set tool_call = tool_call.function %}
+ {%- endif %}
+ {%- if loop.first %}
+ {%- if content|trim %}
+ {{- '\n\n<tool_call>\n<function=' + tool_call.name + '>\n' }}
+ {%- else %}
+ {{- '<tool_call>\n<function=' + tool_call.name + '>\n' }}
+ {%- endif %}
+ {%- else %}
+ {{- '\n<tool_call>\n<function=' + tool_call.name + '>\n' }}
+ {%- endif %}
+ {%- if tool_call.arguments is defined and tool_call.arguments != '' %}
+ {%- for args_name, args_value in tool_call.arguments|items %}
+ {{- '<parameter=' + args_name + '>\n' }}
+ {%- set args_value = args_value | string if args_value is string else args_value | tojson | safe %}
+ {{- args_value }}
+ {{- '\n</parameter>\n' }}
+ {%- endfor %}
+ {%- endif %}
+ {{- '</function>\n</tool_call>' }}
+ {%- endfor %}
+ {%- endif %}
+ {{- '<|im_end|>\n' }}
+ {%- elif message.role == "tool" %}
+ {%- if loop.previtem and loop.previtem.role != "tool" %}
+ {{- '<|im_start|>user' }}
+ {%- endif %}
+ {{- '\n<tool_response>\n' }}
+ {{- content }}
+ {{- '\n</tool_response>' }}
+ {%- if not loop.last and loop.nextitem.role != "tool" %}
+ {{- '<|im_end|>\n' }}
+ {%- elif loop.last %}
+ {{- '<|im_end|>\n' }}
+ {%- endif %}
+ {%- else %}
+ {{- raise_exception('Unexpected message role.') }}
+ {%- endif %}
+{%- endfor %}
+{%- if add_generation_prompt %}
+ {{- '<|im_start|>assistant\n' }}
+ {%- if enable_thinking is defined and enable_thinking is false %}
+ {{- '<think>\n\n</think>\n\n' }}
+ {%- else %}
+ {{- '<think>\n' }}
+ {%- endif %}
+{%- endif %}
diff --git a/x/create/classify.go b/x/create/classify.go
index 92507d497..e8fc28e2c 100644
--- a/x/create/classify.go
+++ b/x/create/classify.go
@@ -30,8 +30,8 @@ func (k SourceKind) String() string {
}
// Classification is the decision about a source model: its kind and the
-// quantization that will actually be applied. An empty Quantize means the
-// tensors are stored at source precision (no quantization).
+// effective quantization of the imported weights. Quantize may describe a
+// requested conversion or a quantization already present in the source.
type Classification struct {
Kind SourceKind
Quantize string
@@ -58,7 +58,10 @@ func Classify(inv Inventory, requested string) (Classification, error) {
if requested != "" {
return Classification{}, fmt.Errorf("cannot requantize an already-quantized source model (requested %q): only bf16/fp16/fp32 sources can be quantized", requested)
}
- return Classification{Kind: SourcePrequantized}, nil
+ return Classification{
+ Kind: SourcePrequantized,
+ Quantize: detectPrequantizedQuantization(inv),
+ }, nil
case SourceBlockFP8:
rows, cols, ok := inv.Config.HFFP8WeightBlockSize()
@@ -77,6 +80,28 @@ func Classify(inv Inventory, requested string) (Classification, error) {
return Classification{}, fmt.Errorf("could not classify source model in %s", inv.Dir)
}
+// detectPrequantizedQuantization reports a single quantization shared by the
+// source's recognized prequantized weights. A mixed or unrecognized source has
+// no single file type to record in the model manifest.
+func detectPrequantizedQuantization(inv Inventory) string {
+ var detected string
+ for _, name := range sortedTensorNames(inv) {
+ spec, _, ok := matchPrequant(name, inv)
+ if !ok {
+ continue
+ }
+ q := quant.Canonical(spec.Metadata["quant_type"])
+ if q == "" {
+ continue
+ }
+ if detected != "" && detected != q {
+ return ""
+ }
+ detected = q
+ }
+ return detected
+}
+
// normalizeRequested validates the user's quantize value and returns its
// canonical form ("" for no quantization).
func normalizeRequested(requested string) (string, error) {
diff --git a/x/create/classify_test.go b/x/create/classify_test.go
index 84e696cc4..2af12be08 100644
--- a/x/create/classify_test.go
+++ b/x/create/classify_test.go
@@ -48,20 +48,40 @@ func TestClassify(t *testing.T) {
wantQuant: "int8",
},
{
- name: "mlx prequantized (.scales)",
+ name: "mlx prequantized (.scales)",
+ cfg: sourceModelConfig{Quantization: sourceQuantization{Bits: 4, Mode: "affine", GroupSize: 32}},
+ tensors: map[string]string{"model.layers.0.weight": "U32", "model.layers.0.scales": "BF16"},
+ wantKind: SourcePrequantized,
+ wantQuant: "int4",
+ },
+ {
+ name: "mlx prequantized without quantization metadata",
tensors: map[string]string{"model.layers.0.weight": "U32", "model.layers.0.scales": "BF16"},
wantKind: SourcePrequantized,
},
{
// ModelOpt NVFP4 whose hf_quant_config.json sidecar is absent:
// recognized from the packed weight + scale companion (finding #7).
- name: "modelopt nvfp4 without config sidecar",
- tensors: map[string]string{"model.layers.0.weight": "U8", "model.layers.0.weight_scale": "F8_E4M3"},
- wantKind: SourcePrequantized,
+ name: "modelopt nvfp4 without config sidecar",
+ tensors: map[string]string{"model.layers.0.weight": "U8", "model.layers.0.weight_scale": "F8_E4M3"},
+ wantKind: SourcePrequantized,
+ wantQuant: "nvfp4",
+ },
+ {
+ name: "compressed-tensors nvfp4 (.weight_packed)",
+ tensors: map[string]string{"model.layers.0.weight_packed": "U8", "model.layers.0.weight_scale": "F8_E4M3"},
+ wantKind: SourcePrequantized,
+ wantQuant: "nvfp4",
},
{
- name: "compressed-tensors nvfp4 (.weight_packed)",
- tensors: map[string]string{"model.layers.0.weight_packed": "U8", "model.layers.0.weight_scale": "F8_E4M3"},
+ name: "mixed prequantized formats have no single file type",
+ cfg: sourceModelConfig{Quantization: sourceQuantization{Bits: 4, Mode: "affine", GroupSize: 32}},
+ tensors: map[string]string{
+ "model.layers.0.weight": "U32",
+ "model.layers.0.scales": "BF16",
+ "model.layers.1.weight_packed": "U8",
+ "model.layers.1.weight_scale": "F8_E4M3",
+ },
wantKind: SourcePrequantized,
},
{
diff --git a/x/create/client/create.go b/x/create/client/create.go
index e0900c601..e050cc35f 100644
--- a/x/create/client/create.go
+++ b/x/create/client/create.go
@@ -235,9 +235,9 @@ func CreateModel(opts CreateOptions, p *progress.Progress) error {
}
func appendLayersManifestWriter(next create.ManifestWriter, extra []create.LayerInfo) create.ManifestWriter {
- return func(modelName string, config create.LayerInfo, layers []create.LayerInfo) error {
+ return func(modelName string, config create.LayerInfo, layers []create.LayerInfo, class create.Classification) error {
layers = append(layers, extra...)
- return next(modelName, config, layers)
+ return next(modelName, config, layers, class)
}
}
@@ -314,6 +314,7 @@ func createModelFromBaseWithDraft(opts CreateOptions, draftLayers []create.Layer
Name: configLayer.Name,
},
layers,
+ create.Classification{Quantize: quant.Canonical(opts.Quantize)},
)
}
@@ -377,7 +378,7 @@ func newLayerCreator() create.LayerCreator {
// newManifestWriter returns a ManifestWriter callback for writing the model manifest.
func newManifestWriter(opts CreateOptions, capabilities []string, parserName, rendererName string) create.ManifestWriter {
- return func(modelName string, config create.LayerInfo, layers []create.LayerInfo) error {
+ return func(modelName string, config create.LayerInfo, layers []create.LayerInfo, class create.Classification) error {
name := model.ParseName(modelName)
if !name.IsValid() {
return fmt.Errorf("invalid model name: %s", modelName)
@@ -389,8 +390,8 @@ func newManifestWriter(opts CreateOptions, capabilities []string, parserName, re
configData = *opts.BaseConfig
}
configData.ModelFormat = "safetensors"
- if opts.Quantize != "" || configData.FileType == "" {
- configData.FileType = strings.ToLower(strings.TrimSpace(opts.Quantize))
+ if class.Quantize != "" || configData.FileType == "" {
+ configData.FileType = class.Quantize
}
configData.Capabilities = capabilities
configData.Requires = MinOllamaVersion
@@ -583,6 +584,16 @@ func isQwen35Family(s string) bool {
return strings.Contains(s, "qwen3_5") || strings.Contains(s, "qwen3next")
}
+func qwen35RendererName(modelDir string) string {
+ template := readChatTemplate(modelDir)
+ if strings.Contains(template, "resolved_reasoning_effort") &&
+ strings.Contains(template, "preserve_thinking") {
+ return "qwen3.8"
+ }
+
+ return "qwen3.5"
+}
+
func lagunaRendererParserName(modelDir string) string {
const poolsideV1Marker = "laguna_glm_thinking_v8"
@@ -729,7 +740,7 @@ func rendererNameForIdentifier(modelDir, s string) string {
case strings.Contains(s, "deepseek"):
return "deepseek3"
case isQwen35Family(s):
- return "qwen3.5"
+ return qwen35RendererName(modelDir)
case strings.Contains(s, "qwen3"):
return "qwen3-coder"
// Nemotron-H publishes NemotronHForCausalLM for text and
diff --git a/x/create/client/create_test.go b/x/create/client/create_test.go
index 6e13fbd9f..678fe37b7 100644
--- a/x/create/client/create_test.go
+++ b/x/create/client/create_test.go
@@ -514,17 +514,17 @@ func TestCreateModelfileLayersIncludesParameters(t *testing.T) {
}
}
-func TestNewManifestWriter_PopulatesFileTypeFromQuantize(t *testing.T) {
+func TestNewManifestWriter_PopulatesFileTypeFromEffectiveQuantize(t *testing.T) {
t.Setenv("OLLAMA_MODELS", t.TempDir())
opts := CreateOptions{
ModelName: "test-quantized",
ModelDir: t.TempDir(),
- Quantize: "MXFP8",
}
writer := newManifestWriter(opts, []string{"completion"}, "qwen3", "qwen3")
- if err := writer(opts.ModelName, create.LayerInfo{}, nil); err != nil {
+ class := create.Classification{Kind: create.SourceBlockFP8, Quantize: "mxfp8"}
+ if err := writer(opts.ModelName, create.LayerInfo{}, nil, class); err != nil {
t.Fatalf("newManifestWriter() error = %v", err)
}
@@ -569,7 +569,7 @@ func TestNewManifestWriter_PopulatesDraftMetadata(t *testing.T) {
}
writer := newManifestWriter(opts, []string{"completion"}, "gemma4", "gemma4")
- if err := writer(opts.ModelName, create.LayerInfo{}, nil); err != nil {
+ if err := writer(opts.ModelName, create.LayerInfo{}, nil, create.Classification{}); err != nil {
t.Fatalf("newManifestWriter() error = %v", err)
}
@@ -852,9 +852,11 @@ func TestGetParserName(t *testing.T) {
func TestGetRendererName(t *testing.T) {
tests := []struct {
- name string
- configJSON string
- want string
+ name string
+ configJSON string
+ chatTemplate string
+ standaloneOnly bool
+ want string
}{
{
name: "qwen3 model",
@@ -866,6 +868,19 @@ func TestGetRendererName(t *testing.T) {
configJSON: `{"architectures": ["Qwen3_5ForConditionalGeneration"]}`,
want: "qwen3.5",
},
+ {
+ name: "qwen3.8 embedded template",
+ configJSON: `{"architectures": ["Qwen3_5ForConditionalGeneration"]}`,
+ chatTemplate: `{% set resolved_reasoning_effort = reasoning_effort|default('xhigh') %}{% if preserve_thinking %}{% endif %}`,
+ want: "qwen3.8",
+ },
+ {
+ name: "qwen3.8 standalone template",
+ configJSON: `{"architectures": ["Qwen3_5ForConditionalGeneration"]}`,
+ chatTemplate: `{% set resolved_reasoning_effort = reasoning_effort|default('xhigh') %}{% if preserve_thinking %}{% endif %}`,
+ standaloneOnly: true,
+ want: "qwen3.8",
+ },
{
name: "deepseek model",
configJSON: `{"architectures": ["DeepseekV3ForCausalLM"]}`,
@@ -911,7 +926,24 @@ func TestGetRendererName(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
dir := t.TempDir()
- os.WriteFile(filepath.Join(dir, "config.json"), []byte(tt.configJSON), 0o644)
+ if err := os.WriteFile(filepath.Join(dir, "config.json"), []byte(tt.configJSON), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if tt.chatTemplate != "" {
+ if tt.standaloneOnly {
+ if err := os.WriteFile(filepath.Join(dir, "chat_template.jinja"), []byte(tt.chatTemplate), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ } else {
+ data, err := json.Marshal(map[string]string{"chat_template": tt.chatTemplate})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(dir, "tokenizer_config.json"), data, 0o644); err != nil {
+ t.Fatal(err)
+ }
+ }
+ }
if got := getRendererName(dir); got != tt.want {
t.Errorf("getRendererName() = %q, want %q", got, tt.want)
diff --git a/x/create/create.go b/x/create/create.go
index 9940cb8cf..1c6603c4a 100644
--- a/x/create/create.go
+++ b/x/create/create.go
@@ -161,8 +161,9 @@ type LayerInfo struct {
// name is the path-style name (e.g., "tokenizer/tokenizer.json")
type LayerCreator func(r io.Reader, mediaType, name string) (LayerInfo, error)
-// ManifestWriter writes the manifest file.
-type ManifestWriter func(modelName string, config LayerInfo, layers []LayerInfo) error
+// ManifestWriter writes the manifest file with the source classification used
+// to produce its tensor layers.
+type ManifestWriter func(modelName string, config LayerInfo, layers []LayerInfo, class Classification) error
// ShouldQuantize returns true if a tensor should be quantized.
// For image gen models (component non-empty): quantizes linear weights, skipping VAE, embeddings, norms.
diff --git a/x/create/inventory.go b/x/create/inventory.go
index 6a3995dc7..cdc58a717 100644
--- a/x/create/inventory.go
+++ b/x/create/inventory.go
@@ -55,38 +55,30 @@ func ReadInventory(dir string) (Inventory, error) {
return Inventory{}, fmt.Errorf("read tensor index: %w", err)
}
- entries, err := os.ReadDir(dir)
+ files, err := inventoryShardFiles(dir, index)
if err != nil {
return Inventory{}, err
}
- // Only the standard HF weights - a monolithic model.safetensors or the
- // sharded model-*.safetensors set - are imported. Other safetensors in the
- // same repo - notably Mistral's consolidated-*.safetensors - use a layout
- // we don't support, and are skipped so they can't shadow or pollute the
- // model tensors.
- var monolithic bool
- var files []string
- for _, entry := range entries {
- if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".safetensors") || !strings.HasPrefix(entry.Name(), "model") {
- continue
- }
- if entry.Name() == "model.safetensors" {
- monolithic = true
- }
- files = append(files, entry.Name())
- }
- if monolithic && len(files) > 1 {
- return Inventory{}, fmt.Errorf("found both model.safetensors and sharded model-*.safetensors weights in %s: ambiguous source", dir)
- }
-
tensors := make(map[string]SourceTensor)
for _, file := range files {
ext, err := safetensors.OpenForExtraction(filepath.Join(dir, file))
if err != nil {
+ if len(index) > 0 {
+ return Inventory{}, fmt.Errorf("source model is incomplete: open indexed shard %s: %w", file, err)
+ }
return Inventory{}, fmt.Errorf("open %s: %w", file, err)
}
for _, name := range ext.ListTensors() {
+ if expectedFile, indexed := index[name]; len(index) > 0 {
+ if !indexed {
+ continue
+ }
+ if expectedFile != file {
+ ext.Close()
+ return Inventory{}, fmt.Errorf("source model is incomplete: tensor %s is indexed in %q but found in %q", name, expectedFile, file)
+ }
+ }
td, err := ext.GetTensor(name)
if err != nil {
ext.Close()
@@ -111,14 +103,54 @@ func ReadInventory(dir string) (Inventory, error) {
// tensor) means missing weights, which must fail loudly here rather than
// silently importing an incomplete model.
for name, file := range index {
- if _, ok := tensors[name]; !ok {
+ if tensor, ok := tensors[name]; !ok {
return Inventory{}, fmt.Errorf("source model is incomplete: tensor %s (indexed in %q) was not found", name, file)
+ } else if tensor.File != file {
+ return Inventory{}, fmt.Errorf("source model is incomplete: tensor %s is indexed in %q but found in %q", name, file, tensor.File)
}
}
if len(tensors) == 0 {
- return Inventory{}, fmt.Errorf("no model.safetensors or model-*.safetensors weights found in %s", dir)
+ return Inventory{}, fmt.Errorf("no model weights found in %s", dir)
}
return Inventory{Dir: dir, Config: cfg, RawConfig: rawConfig, Tensors: tensors}, nil
}
+
+func inventoryShardFiles(dir string, index map[string]string) ([]string, error) {
+ if len(index) > 0 {
+ files := make(map[string]struct{})
+ for _, file := range index {
+ if file == "" || filepath.Base(file) != file || !strings.HasSuffix(file, ".safetensors") {
+ return nil, fmt.Errorf("tensor index contains invalid shard path %q", file)
+ }
+ files[file] = struct{}{}
+ }
+ return sortedKeys(files), nil
+ }
+
+ entries, err := os.ReadDir(dir)
+ if err != nil {
+ return nil, err
+ }
+
+ // Without an index, only the standard HF weights - a monolithic
+ // model.safetensors or sharded model-*.safetensors set - are imported.
+ // Other safetensors in the same repo, notably Mistral consolidated files,
+ // are skipped so they cannot shadow or pollute the model tensors.
+ var monolithic bool
+ var files []string
+ for _, entry := range entries {
+ if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".safetensors") || !strings.HasPrefix(entry.Name(), "model") {
+ continue
+ }
+ if entry.Name() == "model.safetensors" {
+ monolithic = true
+ }
+ files = append(files, entry.Name())
+ }
+ if monolithic && len(files) > 1 {
+ return nil, fmt.Errorf("found both model.safetensors and sharded model-*.safetensors weights in %s: ambiguous source", dir)
+ }
+ return files, nil
+}
diff --git a/x/create/inventory_test.go b/x/create/inventory_test.go
index cad766ae4..085916777 100644
--- a/x/create/inventory_test.go
+++ b/x/create/inventory_test.go
@@ -62,6 +62,50 @@ func TestReadInventoryIncomplete(t *testing.T) {
}
}
+func TestReadInventoryUsesIndexShardNames(t *testing.T) {
+ dir := t.TempDir()
+ writeConfigJSON(t, dir, `{"architectures":["TestModel"]}`)
+ createTestSafetensors(t, filepath.Join(dir, "layers-0.safetensors"), []*st.TensorData{
+ st.NewTensorDataFromBytes("model.layers.0.weight", "BF16", []int32{4, 4}, make([]byte, 4*4*2)),
+ st.NewTensorDataFromBytes("unindexed.weight", "BF16", []int32{4, 4}, make([]byte, 4*4*2)),
+ })
+ createTestSafetensors(t, filepath.Join(dir, "outside.safetensors"), []*st.TensorData{
+ st.NewTensorDataFromBytes("model.embed.weight", "BF16", []int32{4, 8}, make([]byte, 4*8*2)),
+ })
+ index := `{"weight_map":{"model.layers.0.weight":"layers-0.safetensors","model.embed.weight":"outside.safetensors"}}`
+ if err := os.WriteFile(filepath.Join(dir, "model.safetensors.index.json"), []byte(index), 0o644); err != nil {
+ t.Fatal(err)
+ }
+
+ inv, err := ReadInventory(dir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(inv.Tensors) != 2 || !inv.Has("model.layers.0.weight") || !inv.Has("model.embed.weight") {
+ t.Fatalf("indexed tensors = %v, want layer and embedding weights", inv.Tensors)
+ }
+ if inv.Has("unindexed.weight") {
+ t.Fatal("unindexed tensor from an indexed shard must not be imported")
+ }
+ if got := inv.Tensors["model.layers.0.weight"].File; got != "layers-0.safetensors" {
+ t.Fatalf("layer shard = %q, want layers-0.safetensors", got)
+ }
+}
+
+func TestReadInventoryRejectsUnsafeIndexShardPath(t *testing.T) {
+ dir := t.TempDir()
+ writeConfigJSON(t, dir, `{"architectures":["TestModel"]}`)
+ index := `{"weight_map":{"model.weight":"../outside.safetensors"}}`
+ if err := os.WriteFile(filepath.Join(dir, "model.safetensors.index.json"), []byte(index), 0o644); err != nil {
+ t.Fatal(err)
+ }
+
+ _, err := ReadInventory(dir)
+ if err == nil || !strings.Contains(err.Error(), "invalid shard path") {
+ t.Fatalf("ReadInventory() error = %v, want invalid shard path", err)
+ }
+}
+
func TestReadInventorySkipsConsolidated(t *testing.T) {
dir := t.TempDir()
writeConfigJSON(t, dir, `{"architectures":["TestModel"]}`)
diff --git a/x/create/pipeline.go b/x/create/pipeline.go
index 6794382ad..22ef3f5c8 100644
--- a/x/create/pipeline.go
+++ b/x/create/pipeline.go
@@ -50,7 +50,7 @@ func Create(modelName, modelDir, quantize string, store BlobStore, writeManifest
}
fn(fmt.Sprintf("writing manifest for %s", modelName))
- if err := writeManifest(modelName, configLayer, layers); err != nil {
+ if err := writeManifest(modelName, configLayer, layers, class); err != nil {
return fmt.Errorf("write manifest: %w", err)
}
fn(fmt.Sprintf("successfully imported %s with %d layers", modelName, len(layers)))
diff --git a/x/create/pipeline_test.go b/x/create/pipeline_test.go
index ba0122d68..a266ffd86 100644
--- a/x/create/pipeline_test.go
+++ b/x/create/pipeline_test.go
@@ -19,8 +19,10 @@ func TestCreatePipeline(t *testing.T) {
var gotName string
var gotConfig LayerInfo
var gotLayers []LayerInfo
- writeManifest := func(name string, config LayerInfo, layers []LayerInfo) error {
+ var gotClass Classification
+ writeManifest := func(name string, config LayerInfo, layers []LayerInfo, class Classification) error {
gotName, gotConfig, gotLayers = name, config, layers
+ gotClass = class
return nil
}
@@ -34,6 +36,9 @@ func TestCreatePipeline(t *testing.T) {
if gotConfig.Name != "config.json" {
t.Errorf("config layer = %q, want config.json", gotConfig.Name)
}
+ if gotClass.Kind != SourceFloat || gotClass.Quantize != "" {
+ t.Errorf("classification = {%s %q}, want {float %q}", gotClass.Kind, gotClass.Quantize, "")
+ }
if len(gotLayers) != 3 {
t.Fatalf("manifest layers = %d, want 3 (2 tensors + config.json)", len(gotLayers))
}
@@ -43,3 +48,26 @@ func TestCreatePipeline(t *testing.T) {
}
}
}
+
+func TestCreatePipelineReportsPrequantizedFileType(t *testing.T) {
+ dir := t.TempDir()
+ writeConfigJSON(t, dir, `{"architectures":["TestModel"]}`)
+ createTestSafetensors(t, filepath.Join(dir, "model.safetensors"), []*st.TensorData{
+ st.NewTensorDataFromBytes("linear.weight", "U8", []int32{16, 8}, make([]byte, 16*8)),
+ st.NewTensorDataFromBytes("linear.weight_scale", "F8_E4M3", []int32{16, 1}, make([]byte, 16)),
+ st.NewTensorDataFromBytes("linear.weight_scale_2", "F32", []int32{}, f32le(1)),
+ })
+
+ store := newCaptureStore()
+ var got Classification
+ writeManifest := func(_ string, _ LayerInfo, _ []LayerInfo, class Classification) error {
+ got = class
+ return nil
+ }
+ if err := Create("mymodel", dir, "", store, writeManifest, func(string) {}); err != nil {
+ t.Fatalf("Create() error = %v", err)
+ }
+ if got.Kind != SourcePrequantized || got.Quantize != "nvfp4" {
+ t.Errorf("classification = {%s %q}, want {prequantized nvfp4}", got.Kind, got.Quantize)
+ }
+}
diff --git a/x/models/qwen3_5/qwen3_5.go b/x/models/qwen3_5/qwen3_5.go
index dda85db44..f67dff614 100644
--- a/x/models/qwen3_5/qwen3_5.go
+++ b/x/models/qwen3_5/qwen3_5.go
@@ -796,10 +796,10 @@ func sanitizeConvWeight(w *mlx.Array) *mlx.Array {
}
if w.NumDims() == 3 {
if w.Dim(1) == 1 {
- return mlx.Squeeze(w, 1)
+ return mlx.Reshape(w, int32(w.Dim(0)), int32(w.Dim(2)))
}
if w.Dim(2) == 1 {
- return mlx.Squeeze(w, 2)
+ return mlx.Reshape(w, int32(w.Dim(0)), int32(w.Dim(1)))
}
}
return w
diff --git a/x/models/qwen3_5/qwen3_5_test.go b/x/models/qwen3_5/qwen3_5_test.go
index 738546830..c136ddfb0 100644
--- a/x/models/qwen3_5/qwen3_5_test.go
+++ b/x/models/qwen3_5/qwen3_5_test.go
@@ -3,6 +3,7 @@ package qwen3_5
import (
"testing"
+ "github.com/ollama/ollama/x/internal/mlxtest"
"github.com/ollama/ollama/x/mlxrunner/cache"
"github.com/ollama/ollama/x/mlxrunner/mlx"
)
@@ -14,6 +15,28 @@ func skipIfNoMLX(t *testing.T) {
}
}
+func TestSanitizeConvWeight(t *testing.T) {
+ mlxtest.Setup(t)
+
+ tests := []struct {
+ name string
+ shape []int
+ want []int
+ }{
+ {name: "publisher layout", shape: []int{8, 1, 4}, want: []int{8, 4}},
+ {name: "imported layout", shape: []int{8, 4, 1}, want: []int{8, 4}},
+ {name: "already sanitized", shape: []int{8, 4}, want: []int{8, 4}},
+ }
+
+ for _, tt := range tests {
+ got := sanitizeConvWeight(mlx.Zeros(mlx.DTypeBFloat16, tt.shape...))
+ mlx.Eval(got)
+ if dims := got.Dims(); len(dims) != len(tt.want) || dims[0] != tt.want[0] || dims[1] != tt.want[1] {
+ t.Fatalf("%s: sanitizeConvWeight() shape = %v, want %v", tt.name, dims, tt.want)
+ }
+ }
+}
+
func TestParseConfigNestedDefaults(t *testing.T) {
data := []byte(`{
"model_type": "Qwen3_5MoeForConditionalGeneration",