mirror of
https://github.com/ollama/ollama.git
synced 2026-04-17 19:54:03 +02:00
* bench: add prompt calibration, context size flag, and NumCtx reporting Add --num-ctx flag to set context size, and report NumCtx in model info header. Calibrate tokens-per-word ratio during warmup using actual tokenization metrics from the model, replacing the fixed 1.3 heuristic. This produces more accurate prompt token counts for --prompt-tokens. Also add fetchContextLength() to query running model context via /api/ps. * integration: improve vision test robustness and add thinking tests Add skipIfNoVisionOverride() to skip vision tests when OLLAMA_TEST_MODEL is set to a non-vision model. Add Think:false to context exhaustion test to prevent thinking models from using all context before the test can measure it. Add third test image (ollama homepage) and replace OCR test with ImageDescription test using it. Relax match strings for broader model compatibility. Add TestThinkingEnabled and TestThinkingSuppressed to verify thinking output and channel tag handling. * gemma4: add Gemma 4 GGML model support Add full Gemma 4 model family support (E2B, E4B, 26B MoE, 31B Dense) for the GGML backend including text, vision, converter, parser, and renderer. Text model features: - Sliding window + full attention with per-layer patterns - KV sharing across layers with donor map - Per-layer embeddings (PLE) with learned projections - MoE routing with RMSNorm + learned scale - Proportional RoPE with freq_factors for global attention - Final logit softcapping Vision model features: - SigLIP vision encoder with 2D RoPE - ClippableLinear with input/output clamping via packed v.clamp_data - Adaptive average pooling with nMerge kernel - Multi-modal projection with unweighted RMSNorm Converter: - Safetensors to GGUF with vision tensor renaming - Fused MoE gate_up_proj splitting - Vision patch embedding reshape (HF to Conv2D layout) - Packed clamp data tensor for ClippableLinear bounds - Proportional RoPE freq_factors generation Also includes: - BackendGet() on ml.Tensor for reading weight tensor data - Q6_K CUDA get_rows kernel support - MoE-aware ffn_down quantization layer counting - Gemma4 parser with tool calling and thinking support - Gemma4 renderer with structured tool format - Architecture-based auto-detection of renderer/parser/stop tokens - Integration test gemma4 model list additions * gemma4: add audio support with USM conformer encoder Add audio encoding for Gemma 4 using the USM conformer architecture: - Converter: audio tensor mapping, SSCP/conformer/embedder name replacements, softplus repacker for per_dim_scale, F32 enforcement for conv weights - GGML backend: Conv1DDW and PadExt tensor ops - Audio encoder: SSCP Conv2D, 12 conformer blocks (FFW + block-local attention with relative position embeddings + LightConv1d + FFW), output projection, audio-to-text embedding projector - Audio preprocessing: WAV decode, mel spectrogram, FFT (pure Go) - Model wiring: WAV detection, audio token handling, unified PostTokenize Correctly transcribes "why is the sky blue" from test audio. * integration: add gemma4 audio tests including OpenAI API coverage Test audio transcription and response via the Ollama native API, plus two new tests exercising the OpenAI-compatible endpoints: - /v1/audio/transcriptions (multipart form upload) - /v1/chat/completions with input_audio content type All tests use capability checks and skip models without audio support. * gemma4: add OpenAI audio API support and capability detection - Add CapabilityAudio and detect from audio.block_count in GGUF - Add /v1/audio/transcriptions endpoint with TranscriptionMiddleware - Add input_audio content type support in /v1/chat/completions - Add TranscriptionRequest/Response types in openai package * gemma4: add audio input support for run command - /audio toggle in interactive mode for voice chat - Platform-specific microphone recording (AVFoundation on macOS, PulseAudio/ALSA on Linux, WASAPI on Windows) - Space to start/stop recording, automatic chunking for long audio * gemma4: add transcribe command (ollama transcribe MODEL) - Interactive mode with readline prompt and slash commands - Non-interactive mode for piped audio or record-until-Ctrl+C - Chunked streaming transcription for long recordings - Word-wrapped output matching run command style * gemma4: add parser, renderer, and integration test plumbing * gemma4: fix renderer to emit BOS token * gemma4: add OpenAI audio transcription API and input_audio support * gemma4: update converter for new weight drop naming * gemma4: add per_expert_scale to MoE router and fix moe_intermediate_size config * gemma4: rewrite renderer to match HF Jinja2 template exactly Fix 8 bugs found by building 55 reference tests verified against the HF Jinja2 chat template (VERIFY_JINJA2=1 shells out to Python): - Tool responses use separate <|turn>tool turns (not inline tags) - Tool calls emitted before content in assistant messages - Thinking content stripped from assistant history (strip_thinking) - User, tool, and system content trimmed (template does | trim) - Empty system message still emits system turn (check role, not content) - Nested object properties rendered recursively with required field - Array items specification rendered for array-type properties - OBJECT/ARRAY type-specific rendering comma logic matches template Also adds Required field to api.ToolProperty for nested object schemas, replaces old gemma4_test.go with comprehensive gemma4_reference_test.go, and commits the Jinja2 template as testdata for verification. * gemma4: fix MoE fused gate_up split and multiline tool-call arg parsing - Text MoE: split `ffn_gate_up_exps` into contiguous `[gate|up]` halves instead of stride-2 slices. - Parser: escape control characters in `<|"|>...<|"|>` string literals when converting tool-call args to JSON. - Fixes warnings like `invalid character '\n' in string literal` for multiline tool arguments. - Add Gemma4 parser regressions for multiline tool-call args and `gemma4ArgsToJSON`. * cmd: simplify audio input to dropped file attachments * gemma4: use full SWA memory for better cache reuse * gemma4: initialize clamps after backend load * convert: align gemma4 audio tensor renames with llama.cpp * Remove redundant comments in gemma4 vision model * Format Gemma4 MoE block field alignment * use 4096 kvcache.NewSWAMemCache * convert: support new Gemma4 audio_tower tensor naming (#15221) Co-authored-by: jmorganca <jmorganca@gmail.com> * fix integration test defaults for audio * review comments and lint fixes * remove unused audio/video files --------- Co-authored-by: jmorganca <jmorganca@gmail.com>
464 lines
12 KiB
Go
464 lines
12 KiB
Go
package parsers
|
|
|
|
import (
|
|
"strings"
|
|
"testing"
|
|
|
|
"github.com/google/go-cmp/cmp"
|
|
|
|
"github.com/ollama/ollama/api"
|
|
)
|
|
|
|
func TestGemma4Parser(t *testing.T) {
|
|
tests := []struct {
|
|
name string
|
|
input string
|
|
expectedContent string
|
|
expectedThinking string
|
|
expectedToolCalls []api.ToolCall
|
|
thinkingEnabled bool
|
|
lastMessage *api.Message
|
|
}{
|
|
{
|
|
name: "simple_content",
|
|
input: "This is a simple response.",
|
|
expectedContent: "This is a simple response.",
|
|
},
|
|
{
|
|
name: "thinking_then_content",
|
|
input: "<|channel>thought\nLet me think about this...<channel|>The answer is 42.",
|
|
expectedContent: "The answer is 42.",
|
|
expectedThinking: "Let me think about this...",
|
|
thinkingEnabled: true,
|
|
},
|
|
{
|
|
name: "multiple_thinking_blocks",
|
|
input: "<|channel>first thought<channel|><|channel>second thought<channel|>Final answer.",
|
|
expectedContent: "Final answer.",
|
|
expectedThinking: "first thoughtsecond thought",
|
|
thinkingEnabled: true,
|
|
},
|
|
{
|
|
name: "thinking_only_no_content",
|
|
input: "<|channel>just thinking<channel|>",
|
|
expectedContent: "",
|
|
expectedThinking: "just thinking",
|
|
thinkingEnabled: true,
|
|
},
|
|
{
|
|
name: "tool_call_simple",
|
|
input: `<|tool_call>call:get_weather{location:<|"|>Paris<|"|>}<tool_call|>`,
|
|
expectedToolCalls: []api.ToolCall{
|
|
{
|
|
Function: api.ToolCallFunction{
|
|
Name: "get_weather",
|
|
Arguments: testArgs(map[string]any{
|
|
"location": "Paris",
|
|
}),
|
|
},
|
|
},
|
|
},
|
|
},
|
|
{
|
|
name: "tool_call_with_multiple_args",
|
|
input: `<|tool_call>call:get_weather{location:<|"|>Paris<|"|>,units:<|"|>metric<|"|>}<tool_call|>`,
|
|
expectedToolCalls: []api.ToolCall{
|
|
{
|
|
Function: api.ToolCallFunction{
|
|
Name: "get_weather",
|
|
Arguments: testArgs(map[string]any{
|
|
"location": "Paris",
|
|
"units": "metric",
|
|
}),
|
|
},
|
|
},
|
|
},
|
|
},
|
|
{
|
|
name: "tool_call_with_number_arg",
|
|
input: `<|tool_call>call:set_temp{value:42}<tool_call|>`,
|
|
expectedToolCalls: []api.ToolCall{
|
|
{
|
|
Function: api.ToolCallFunction{
|
|
Name: "set_temp",
|
|
Arguments: testArgs(map[string]any{
|
|
"value": 42.0,
|
|
}),
|
|
},
|
|
},
|
|
},
|
|
},
|
|
{
|
|
name: "tool_call_with_boolean_arg",
|
|
input: `<|tool_call>call:toggle{enabled:true}<tool_call|>`,
|
|
expectedToolCalls: []api.ToolCall{
|
|
{
|
|
Function: api.ToolCallFunction{
|
|
Name: "toggle",
|
|
Arguments: testArgs(map[string]any{
|
|
"enabled": true,
|
|
}),
|
|
},
|
|
},
|
|
},
|
|
},
|
|
{
|
|
name: "tool_call_with_nested_object",
|
|
input: `<|tool_call>call:process{config:{enabled:true,name:<|"|>test<|"|>}}<tool_call|>`,
|
|
expectedToolCalls: []api.ToolCall{
|
|
{
|
|
Function: api.ToolCallFunction{
|
|
Name: "process",
|
|
Arguments: testArgs(map[string]any{
|
|
"config": map[string]any{
|
|
"enabled": true,
|
|
"name": "test",
|
|
},
|
|
}),
|
|
},
|
|
},
|
|
},
|
|
},
|
|
{
|
|
name: "tool_call_with_array",
|
|
input: `<|tool_call>call:process{items:[<|"|>a<|"|>,<|"|>b<|"|>]}<tool_call|>`,
|
|
expectedToolCalls: []api.ToolCall{
|
|
{
|
|
Function: api.ToolCallFunction{
|
|
Name: "process",
|
|
Arguments: testArgs(map[string]any{
|
|
"items": []any{"a", "b"},
|
|
}),
|
|
},
|
|
},
|
|
},
|
|
},
|
|
{
|
|
name: "tool_call_with_multiline_string_arg",
|
|
input: `<|tool_call>call:bash{command:<|"|>date
|
|
<|"|>}<tool_call|>`,
|
|
expectedToolCalls: []api.ToolCall{
|
|
{
|
|
Function: api.ToolCallFunction{
|
|
Name: "bash",
|
|
Arguments: testArgs(map[string]any{
|
|
"command": "date\n",
|
|
}),
|
|
},
|
|
},
|
|
},
|
|
},
|
|
{
|
|
name: "multiple_tool_calls",
|
|
input: `<|tool_call>call:get_weather{location:<|"|>Paris<|"|>}<tool_call|><|tool_call>call:get_weather{location:<|"|>London<|"|>}<tool_call|>`,
|
|
expectedToolCalls: []api.ToolCall{
|
|
{
|
|
Function: api.ToolCallFunction{
|
|
Name: "get_weather",
|
|
Arguments: testArgs(map[string]any{
|
|
"location": "Paris",
|
|
}),
|
|
},
|
|
},
|
|
{
|
|
Function: api.ToolCallFunction{
|
|
Name: "get_weather",
|
|
Arguments: testArgs(map[string]any{
|
|
"location": "London",
|
|
}),
|
|
},
|
|
},
|
|
},
|
|
},
|
|
{
|
|
name: "thinking_then_tool_call",
|
|
input: "<|channel>thought\nI need to check the weather<channel|><|tool_call>call:get_weather{location:<|\"|>Paris<|\"|>}<tool_call|>",
|
|
expectedThinking: "I need to check the weather",
|
|
expectedToolCalls: []api.ToolCall{
|
|
{
|
|
Function: api.ToolCallFunction{
|
|
Name: "get_weather",
|
|
Arguments: testArgs(map[string]any{
|
|
"location": "Paris",
|
|
}),
|
|
},
|
|
},
|
|
},
|
|
thinkingEnabled: true,
|
|
},
|
|
{
|
|
name: "content_then_tool_call",
|
|
input: `Let me check that for you.<|tool_call>call:get_weather{location:<|"|>Paris<|"|>}<tool_call|>`,
|
|
expectedContent: "Let me check that for you.",
|
|
expectedToolCalls: []api.ToolCall{
|
|
{
|
|
Function: api.ToolCallFunction{
|
|
Name: "get_weather",
|
|
Arguments: testArgs(map[string]any{
|
|
"location": "Paris",
|
|
}),
|
|
},
|
|
},
|
|
},
|
|
},
|
|
{
|
|
name: "thinking_disabled_channel_tags_as_content",
|
|
input: "<|channel>this is not thinking<channel|>actual content",
|
|
expectedContent: "actual content",
|
|
thinkingEnabled: false,
|
|
},
|
|
{
|
|
name: "prefill_content_only",
|
|
input: "Continuing content.",
|
|
expectedContent: "Continuing content.",
|
|
lastMessage: &api.Message{
|
|
Role: "assistant",
|
|
Content: "Previous content",
|
|
},
|
|
thinkingEnabled: true,
|
|
},
|
|
}
|
|
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
parser := &Gemma4Parser{hasThinkingSupport: true}
|
|
parser.Init(nil, tt.lastMessage, &api.ThinkValue{Value: tt.thinkingEnabled})
|
|
|
|
content, thinking, toolCalls, err := parser.Add(tt.input, true)
|
|
if err != nil {
|
|
t.Fatalf("Add() error = %v", err)
|
|
}
|
|
|
|
if diff := cmp.Diff(tt.expectedContent, content); diff != "" {
|
|
t.Errorf("content mismatch (-want +got):\n%s", diff)
|
|
}
|
|
|
|
if diff := cmp.Diff(tt.expectedThinking, thinking); diff != "" {
|
|
t.Errorf("thinking mismatch (-want +got):\n%s", diff)
|
|
}
|
|
|
|
if diff := cmp.Diff(tt.expectedToolCalls, toolCalls, argsComparer); diff != "" {
|
|
t.Errorf("tool calls mismatch (-want +got):\n%s", diff)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestGemma4Parser_Streaming(t *testing.T) {
|
|
parser := &Gemma4Parser{hasThinkingSupport: true}
|
|
parser.Init(nil, nil, &api.ThinkValue{Value: true})
|
|
|
|
chunks := []string{
|
|
"<|channel>thought",
|
|
"\nLet me think",
|
|
"...<channel|>The answer",
|
|
" is 42.",
|
|
}
|
|
|
|
var finalContent, finalThinking strings.Builder
|
|
|
|
for i, chunk := range chunks {
|
|
done := i == len(chunks)-1
|
|
content, thinking, _, err := parser.Add(chunk, done)
|
|
if err != nil {
|
|
t.Fatalf("Add() error on chunk %d: %v", i, err)
|
|
}
|
|
|
|
finalContent.WriteString(content)
|
|
finalThinking.WriteString(thinking)
|
|
}
|
|
|
|
if finalContent.String() != "The answer is 42." {
|
|
t.Errorf("expected content %q, got %q", "The answer is 42.", finalContent.String())
|
|
}
|
|
|
|
if finalThinking.String() != "Let me think..." {
|
|
t.Errorf("expected thinking %q, got %q", "Let me think...", finalThinking.String())
|
|
}
|
|
}
|
|
|
|
func TestGemma4Parser_StreamingToolCall(t *testing.T) {
|
|
parser := &Gemma4Parser{hasThinkingSupport: false}
|
|
parser.Init(nil, nil, nil)
|
|
|
|
chunks := []string{
|
|
`<|tool_call>call:get_`,
|
|
`weather{location:<|"|>Par`,
|
|
`is<|"|>}<tool_call|>`,
|
|
}
|
|
|
|
var finalContent strings.Builder
|
|
var finalToolCalls []api.ToolCall
|
|
|
|
for i, chunk := range chunks {
|
|
done := i == len(chunks)-1
|
|
content, _, toolCalls, err := parser.Add(chunk, done)
|
|
if err != nil {
|
|
t.Fatalf("Add() error on chunk %d: %v", i, err)
|
|
}
|
|
|
|
finalContent.WriteString(content)
|
|
finalToolCalls = append(finalToolCalls, toolCalls...)
|
|
}
|
|
|
|
if finalContent.String() != "" {
|
|
t.Errorf("expected no content, got %q", finalContent.String())
|
|
}
|
|
|
|
expectedToolCalls := []api.ToolCall{
|
|
{
|
|
Function: api.ToolCallFunction{
|
|
Name: "get_weather",
|
|
Arguments: testArgs(map[string]any{
|
|
"location": "Paris",
|
|
}),
|
|
},
|
|
},
|
|
}
|
|
|
|
if diff := cmp.Diff(expectedToolCalls, finalToolCalls, argsComparer); diff != "" {
|
|
t.Errorf("tool calls mismatch (-want +got):\n%s", diff)
|
|
}
|
|
}
|
|
|
|
func TestGemma4Parser_StreamingSplitThinkingTag(t *testing.T) {
|
|
tests := []struct {
|
|
name string
|
|
chunks []string
|
|
expectedContent string
|
|
expectedThinking string
|
|
}{
|
|
{
|
|
name: "split_channel_open_tag",
|
|
chunks: []string{
|
|
"<|chan",
|
|
"nel>thinking here<channel|>content",
|
|
},
|
|
expectedContent: "content",
|
|
expectedThinking: "thinking here",
|
|
},
|
|
{
|
|
name: "split_channel_close_tag",
|
|
chunks: []string{
|
|
"<|channel>thinking here<chan",
|
|
"nel|>content",
|
|
},
|
|
expectedContent: "content",
|
|
expectedThinking: "thinking here",
|
|
},
|
|
}
|
|
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
parser := &Gemma4Parser{hasThinkingSupport: true}
|
|
parser.Init(nil, nil, &api.ThinkValue{Value: true})
|
|
|
|
var finalContent, finalThinking strings.Builder
|
|
for i, chunk := range tt.chunks {
|
|
done := i == len(tt.chunks)-1
|
|
content, thinking, _, err := parser.Add(chunk, done)
|
|
if err != nil {
|
|
t.Fatalf("Add() error on chunk %d: %v", i, err)
|
|
}
|
|
finalContent.WriteString(content)
|
|
finalThinking.WriteString(thinking)
|
|
}
|
|
|
|
if finalContent.String() != tt.expectedContent {
|
|
t.Errorf("expected content %q, got %q", tt.expectedContent, finalContent.String())
|
|
}
|
|
if finalThinking.String() != tt.expectedThinking {
|
|
t.Errorf("expected thinking %q, got %q", tt.expectedThinking, finalThinking.String())
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestGemma4ArgsToJSON(t *testing.T) {
|
|
tests := []struct {
|
|
name string
|
|
input string
|
|
expected string
|
|
}{
|
|
{
|
|
name: "simple_string",
|
|
input: `{location:<|"|>Paris<|"|>}`,
|
|
expected: `{"location":"Paris"}`,
|
|
},
|
|
{
|
|
name: "multiple_args",
|
|
input: `{location:<|"|>Paris<|"|>,units:<|"|>metric<|"|>}`,
|
|
expected: `{"location":"Paris","units":"metric"}`,
|
|
},
|
|
{
|
|
name: "number_value",
|
|
input: `{value:42}`,
|
|
expected: `{"value":42}`,
|
|
},
|
|
{
|
|
name: "boolean_value",
|
|
input: `{enabled:true}`,
|
|
expected: `{"enabled":true}`,
|
|
},
|
|
{
|
|
name: "nested_object",
|
|
input: `{config:{enabled:true,name:<|"|>test<|"|>}}`,
|
|
expected: `{"config":{"enabled":true,"name":"test"}}`,
|
|
},
|
|
{
|
|
name: "array_value",
|
|
input: `{items:[<|"|>a<|"|>,<|"|>b<|"|>]}`,
|
|
expected: `{"items":["a","b"]}`,
|
|
},
|
|
{
|
|
name: "empty_object",
|
|
input: `{}`,
|
|
expected: `{}`,
|
|
},
|
|
{
|
|
name: "mixed_types",
|
|
input: `{name:<|"|>test<|"|>,count:5,active:true,tags:[<|"|>a<|"|>]}`,
|
|
expected: `{"name":"test","count":5,"active":true,"tags":["a"]}`,
|
|
},
|
|
{
|
|
name: "null_value",
|
|
input: `{value:null}`,
|
|
expected: `{"value":null}`,
|
|
},
|
|
{
|
|
name: "multiline_string_value",
|
|
input: `{command:<|"|>date
|
|
<|"|>}`,
|
|
expected: `{"command":"date\n"}`,
|
|
},
|
|
}
|
|
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
result := gemma4ArgsToJSON(tt.input)
|
|
if result != tt.expected {
|
|
t.Errorf("expected %q, got %q", tt.expected, result)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestGemma4Parser_HasToolSupport(t *testing.T) {
|
|
parser := &Gemma4Parser{}
|
|
if !parser.HasToolSupport() {
|
|
t.Error("Gemma4Parser should support tools")
|
|
}
|
|
}
|
|
|
|
func TestGemma4Parser_HasThinkingSupport(t *testing.T) {
|
|
parser := &Gemma4Parser{hasThinkingSupport: true}
|
|
if !parser.HasThinkingSupport() {
|
|
t.Error("Gemma4Parser with thinking support should report it")
|
|
}
|
|
|
|
parser2 := &Gemma4Parser{hasThinkingSupport: false}
|
|
if parser2.HasThinkingSupport() {
|
|
t.Error("Gemma4Parser without thinking support should not report it")
|
|
}
|
|
}
|